dlchambers
dlchambers

Reputation: 3752

How to implement Xamarin.Forms custom RadioButton renderer? (repost)

Note: I originally posted this a couple days ago, but it got closed due to insufficient/unclear detail. Hopefully this repost passes muster

I'm creating an Android/iOS app using Xamarin.Forms.
I've found that selected RadioButtons render in red on Android:
enter image description here
I want to use a different color that's in my app's theme.

I found a Xamarin forum post which described the standard mechanism for this, which is to implement a custom renderer by adding the following code in the Android project:

[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);
            }
        }
    }
}

I've added the code (renderer is in my Android project); it compiles, runs (on Android), the button appears & functions, etc.
However, neither MyRenderer() nor OnElementChanged() is ever called.

Is there something additional needed to cause the app to use the custom renderer?

Thanks!

Upvotes: 2

Views: 873

Answers (1)

dlchambers
dlchambers

Reputation: 3752

The answer is that it seems Custom Renderers only work on custom classes.
So, in order for this to work you MUST define your own custom class and attach the renderer to your class. I was referencing Xamarin.Forms.RadioButton when I should have been referencing my type.

Does not work:

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

Does work:

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

So the minimal working implementation is to create your custom class in your main project (neither Android or iOS specific):

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

then in your Android project:

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

Upvotes: 3

Related Questions