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

对着背影说爱祢 提交于 2021-02-08 03:26:17

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/40784769/how-to-get-a-color-from-the-current-theme-programmatically-in-android-xamarin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!