如何在 Android (Xamarin) 中以编程方式从当前主题获取颜色 [英] How to get a color from the current theme programmatically in Android (Xamarin)

查看:48
本文介绍了如何在 Android (Xamarin) 中以编程方式从当前主题获取颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以编程方式获取一些默认主题颜色值(例如 windowBackground、colorPrimary).我正在从 Activity 执行代码.我的目标 android API 是 21.我正在使用 Theme.Material 主题.我试过了:

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)

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

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

推荐答案

使用我测试过的这段代码

Use this code I have tested

对于 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​​

这篇关于如何在 Android (Xamarin) 中以编程方式从当前主题获取颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆