2016-11-24 58 views
2

我需要通过编程方式获取一些默认主题颜色值(例如,windowBackground,colorPrimary)。我正在执行一个Activity的代码。我的目标android API是21。我正在使用Theme.Material theme。我已经试过:如何以编程方式在Android中获取当前主题的颜色(Xamarin)

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

不同的资源标识符,但我总是得到一个Android.Util.DataType.Null值。

+0

你检查我的答案? – Ironman

回答

1

使用此代码,我已经测试

WindowBackground

代码:

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; 

输出我的情况是:FAFAFA

对于ColorPrimary使用本:

代码:

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; 

输出我的情况是:0072BA

+0

谢谢。我看到了我缺少的东西。您的代码需要一些改进才能获得实际的颜色:_var windowBackgroundDrawable = Application.Context.GetDrawable(a.ResourceId); var windowBackgroundColor =((Android.Graphics.Drawables.ColorDrawable)windowBackgroundDrawable).Color; _你可以将它添加到你的解决方案吗? – Kalitsov

+0

@Kalitsov我已更新你可以标记为接受答案,所以它有助于其他。 – Ironman

+0

是的,原因。请更新第二个片段。所以它可以是一致的。 – Kalitsov

相关问题