【问题标题】:How to implement Xamarin.Forms custom RadioButton renderer? (repost)如何实现 Xamarin.Forms 自定义 RadioButton 渲染器? (转发)
【发布时间】:2021-08-25 10:23:11
【问题描述】:

注意:我最初是在几天前发布的,但由于细节不足/不清楚而被关闭。希望这个转发通过集合

我正在使用 Xamarin.Forms 创建一个 Android/iOS 应用。
我发现选定的 RadioButtons 在 Android 上呈现为红色:

我想在我的应用主题中使用不同的颜色。

我找到了一个 Xamarin 论坛帖子,其中描述了标准机制,即通过在 Android 项目中添加以下代码来实现自定义渲染器:

[assembly: ExportRenderer(typeof(Xamarin.Forms.RadioButton), typeof(MyRenderer))]
namespace MyApp.Droid
{
    public class MyRenderer : RadioButtonRenderer
    {
        public MyRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            if(Control != null)
            {
                Control.ButtonTintList = ColorStateList.ValueOf(Android.Graphics.Color.Yellow);
            }
        }
    }
}

我已经添加了代码(渲染器在我的 Android 项目中);它编译、运行(在 Android 上)、按钮出现和功能等。
但是,从未调用过 MyRenderer() 和 OnElementChanged()。

是否需要额外的东西才能使应用使用自定义渲染器?

谢谢!

【问题讨论】:

    标签: xamarin.forms custom-renderer


    【解决方案1】:

    答案是自定义渲染器似乎只适用于自定义类
    因此,为了使其工作,您必须定义自己的自定义类并将渲染器附加到您的类。当我应该引用我的类型时,我引用了 Xamarin.Forms.RadioButton。

    有效吗:

    ExportRenderer(typeof(Xamarin.Forms.RadioButton), ...
    

    是否工作:

    ExportRenderer(typeof(MyApp.MyRadio), ...
    

    因此,最小的工作实现是在您的主项目中创建您的自定义类(无论是 Android 还是 iOS 特定的):

    namespace MyApp
    {
       // All that's needed is the simplest derived class ever:
       public class MyRadio : RadioButton
       {
       }
    }
    

    然后在您的 Android 项目中:

    [assembly: ExportRenderer(typeof(MyApp.MyRadio), typeof(MyApp.Droid.MyRenderer))]
    namespace MyApp.Droid
    {
       ... same as the code in the question above
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 2017-02-10
      • 2017-01-07
      • 1970-01-01
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      相关资源
      最近更新 更多