Kalitsov Kalitsov - 16 days ago 11
Android Question

How to get a color from the current theme programmatically in android(Xamarin)

I need to get some default theme color values programmatically (e.g. windowBackground, colorPrimary). I'm executing the code from an Activity. My target android API is 21. I'm using a

Theme.Material theme
. I've tried:

var attributeValue = new Android.Util.TypedValue();
this.Theme.ResolveAttribute(Resource.Attribute.colorPrimary, attributeValue, true)


with different resource identifier, but i always get a
Android.Util.DataType.Null
value.

Answer

Use this code I have tested

For WindowBackground :

Code :

Android.Util.TypedValue a = new Android.Util.TypedValue();
Theme.ResolveAttribute(Android.Resource.Attribute.WindowBackground, a , true);
var windowBackgroundDrawable = Application.Context.GetDrawable(a.ResourceId);      
var windowBackgroundColor = ((Android.Graphics.Drawables.ColorDrawable)windowBackgroundD‌​rawable).Color;

Output My Case is : FAFAFA

For ColorPrimary use this :

Code :

Android.Util.TypedValue a = new Android.Util.TypedValue();
Theme.ResolveAttribute(Android.Resource.Attribute.ColorPrimary, a , true);
var colorPrimarya = Application.Context.GetDrawable(a.ResourceId);      
var colorPrimary = ((Android.Graphics.Drawables.ColorDrawable) colorPrimarya).Color;

Output My Case is : 0072BA