nix
nix

Reputation: 2285

How to add custom renderers to only some specific Layouts?

Let's say, I wanna change the font of the label. That means that I'll have to write something like that:

[assembly: ExportRenderer(typeof(Label), typeof(LabelFontRenderer))]
namespace MyApp.Droid
{
    public class LabelFontRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            var label = (TextView)Control; // for example
            Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Roboto-Regular.ttf");  // font name specified here
            label.Typeface = font;
        }
    }
}

However, adding that to a project will make all labels render with the specified font. What if I want to make only some, specific labels render with that font?

Maybe a solution is to inherit from Label and add renderer to that inherited class, thus applying it only to the instances of that particular class and therefore applying it only to specified labels. Thus, my question consists of two parts: (1) is the way that I described the correct way and will it work, and if not, (2) what is the correct way?

Upvotes: 1

Views: 377

Answers (1)

Prashant Cholachagudda
Prashant Cholachagudda

Reputation: 13092

Maybe a solution is to inherit from Label and add renderer to that inherited class, thus applying it only to the instances of that particular class and therefore applying it only to specified labels.

This is the correct way of doing custom renderers for your controls/needs. By exporting the renderer for Label type, you're modifying the all the labels in the app.

You have to create a inherited Label class in the shared project and define a custom renderer for it. For example:

In shared/portable project:

public class MyLabel : Label {}

In Android project:

[assembly: ExportRenderer(typeof(MyLabel), typeof(LabelFontRenderer))] 
namespace MyApp.Droid
{
    public class LabelFontRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            var label = (TextView)Control; // for example
            Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "Roboto-Regular.ttf");  // font name specified here
            label.Typeface = font;
        }
    }
}

Usage:

var myLabel = new MyLabel { Text = "Hello" };

Upvotes: 2

Related Questions