How to add custom renderers to only some specific Layouts?

耗尽温柔 提交于 2019-12-08 06:35:51

问题


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?


回答1:


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" };


来源:https://stackoverflow.com/questions/38781477/how-to-add-custom-renderers-to-only-some-specific-layouts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!