How to Change a Custom Button's Color When Focused?

zack19zack19 Member ✭✭
edited May 30 in Xamarin.Forms

I have a custom button renderer in my app that creates a gradient button. I would like to be able to use a keyboard with my app, and so I need a method of highlighting which button is currently focused. I have tried creating an if statement in my Android code to check if the button is focused, but have not been successful. Any help would be greatly appreciated.

[assembly: ExportRenderer(typeof(CustomButton), typeof(GradientButtonRenderer))]
    namespace MyApp.Droid.Renderers
    {
        public class GradientButtonRenderer : ButtonRenderer
        {
            public GradientButtonRenderer(Context context) : base(context) { }
            protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
            {
                base.OnElementChanged(e);

                var btn = this.Control as Android.Widget.Button;
                btn?.SetBackgroundResource(Resource.Drawable.gradient_button_style);

                if (btn.IsFocused == true)
                {
                    btn?.SetBackgroundColor(Android.Graphics.Color.Green); 
                }
            }
        }
    }

Answers

  • MommMomm USMember ✭✭✭

    I belive you should use OnElementPropertyChanged method.

  • zack19zack19 Member ✭✭
    edited May 31

    Thank you, that did help. The only issue is that for some reason the gradients have disappeared and the buttons are now gray. However when I focus on a specific button, it gets darker and I can distinguish it from the rest. Do you by any chance know why the colors are no longer appearing?

    For reference, this is how I changed my code.

    protected void OnElementPropertyChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
            {
                base.OnElementChanged(e);
    
                var btn = this.Control as Android.Widget.Button;
                btn?.SetBackgroundResource(Resource.Drawable.gradient_button_style);
    
                if (btn.IsFocused == true)
                {
                    btn?.SetBackgroundResource(Resource.Drawable.gradient_button_style2); 
                }
            }
    
Sign In or Register to comment.