Xamarin Android DatePicker Disabled Text Color

Issue

In my Xamarin Forms app, I have a DatePicker that can appear as disabled. On Android, the DatePicker renders the text as black when the DatePicker is disabled. Due to a dark background, I’d like to change that color to gray.

I have tried many approaches in my custom renderer, but I have not been able to figure it out. I’ve even tried ColorStateList to no avail. I can’t set it in styles because the background color can change between light and dark.

What is the proper approach to change the color of the date field when a DatePicker is disabled?

Solution

You can use a Custom Renderer and override OnElementPropertyChanged to change the Text Color anytime IsEnabled is toggled.

Android Custom Renderer

using Android.Content;

using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

using CustomDatePicker.Droid;

[assembly: ExportRenderer(typeof(Picker), typeof(DisabledDatePickerRenderer))]
namespace CustomDatePicker.Droid
{
    public class DisabledDatePickerRenderer : DatePickerRenderer
    {
        public DisabledDatePickerRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (e.PropertyName.Equals(nameof(Element.IsEnabled)) && Control ! null)
            {
                if (Element.IsEnabled)
                {
                    //Set the text color when the DatePicker is enabled
                    Control.SetTextColor(Android.Graphics.Color.Black);
                }
                else
                {
                    //Set the text color when the DatePicker is disabled
                    Control.SetTextColor(Android.Graphics.Color.Gray);
                }
            }
        }
    }
}

Answered By – Brandon Minnick

Leave a Comment