Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

OnDraw in custom EntryRenderer only called once

I have the following code in my custom renderer but the OnDraw function is only called once, I figured Invalidate() would force a redraw but that isn't the case, how would I go about redrawing on focus change?

using System.ComponentModel;
using AlloyMobileComponents.Android.CustomControls;
using AlloyMobileComponents.Constants;
using AlloyMobileComponents.CustomControls;
using Android.Content;
using Android.Graphics;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using Color = Android.Graphics.Color;

[assembly: ExportRenderer(typeof(CustomEntry), typeof(CustomEntryRenderer))]

namespace AlloyMobileComponents.Android.CustomControls
{
    sealed class CustomEntryRenderer : EntryRenderer
    {
        public CustomEntryRenderer(Context context) : base(context)
        {
            SetWillNotDraw(false);
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            //Control?.SetPadding(10, 10, 10, 10);
            Control?.SetBackgroundColor(Color.Transparent);

            e.NewElement.Unfocused += (sender, args) => Invalidate();
            e.NewElement.Focused += (sender, args) => Invalidate();
        }

        protected override void OnDraw(Canvas canvas)
        {
            base.OnDraw(canvas);

            var paint = new Paint
            {
                Color = IsFocused ? Color.Crimson : ColourConstants.LightBlue.ToAndroid(),
                StrokeWidth = 1,
                AntiAlias = false,
            };

            var width = Width;
            var height = Height;

            if (IsFocused)
            {
                canvas.DrawLine(0, 0, width, 0, paint);
                canvas.DrawLine(width, 0, width, height, paint);
                canvas.DrawLine(0, height, 0, 0, paint);
            }

            canvas.DrawLine(width, height, 0, height, paint);
        }
    }
}

Best Answer

Answers

  • cmcnicholascmcnicholas Member ✭✭

    hmm maybe the property is never updated, will try storing a local variable

  • cmcnicholascmcnicholas Member ✭✭

    You are correct, leads me to question why IsFocused is available? maybe it isn't updated early enough in the lifecycle (who knows) I added a local variable to track focused state and it works, thanks.

Sign In or Register to comment.