Android 如何以编程方式获取内置资源(如colorAccent)的价值?
如何获得参考颜色的实际值。在布局中,我可以使用以下内容Android 如何以编程方式获取内置资源(如colorAccent)的价值?,android,xamarin,xamarin.android,Android,Xamarin,Xamarin.android,如何获得参考颜色的实际值。在布局中,我可以使用以下内容 android:textColor="?android:attr/colorAccent" ..这可以将TextView的文本颜色设置为主题定义的强调色。如何在运行时使用代码获取colorAccent的值 另外,如何找到所有可用值的列表,我必须有一个很长的可用颜色列表,但该列表是在哪里定义的?对于您的示例,您可以通过以下方式获得该值: //default color instead the attribute is not set. va
android:textColor="?android:attr/colorAccent"
..这可以将TextView的文本颜色设置为主题定义的强调色。如何在运行时使用代码获取colorAccent的值
另外,如何找到所有可用值的列表,我必须有一个很长的可用颜色列表,但该列表是在哪里定义的?对于您的示例,您可以通过以下方式获得该值:
//default color instead the attribute is not set.
var color = Color.Blue;
var attributes = new int[] { Android.Resource.Attribute.ColorAccent };
var typeArray = ObtainStyledAttributes(attributes);
//get the fist item (we are sending only one) and passing
//the default value we want, just in case.
var colorAccent = typeArray.GetColor(0, color);
colorAccent
将在主题中为colorAccent
属性(如果有)或默认值设置Color
值得一提的是,此方法ActainStyledAttributes
是上下文的一部分,因此,如果您已经在某个活动中,您将发现它是该活动的一部分,但如果您在任何其他类中,您将需要在上下文中传递,以防它不可用
有关可用值的完整列表,您可以从Android.Resource.Attribute
类中获得它。在VS中,执行检查以查看此类具有的不同属性。也许Android文档有更好的方法
希望这有帮助。-如果资源是Android定义的资源:
var id = Android.Resource.Attribute.ColorAccent;
如果资源位于对话框、小部件等中。。这不是Android系统资源(即获取DatePickerDialog资源)
使用获得的id:
var typedArray = Theme.ObtainStyledAttributes(new int[] { id });
var color = typedArray.GetColor(0, int.MaxValue);
if (color != int.MaxValue)
{
Log.Debug("COLOR", color.ToString());
}
R
列表随API/主题的变化而变化,对于可用的基本值:
- 颜色:
- 风格:
- 等等
但要获得完整的参考,您必须使用Android源代码来获取您正在查看的API:
因此,Oreo beta版中定义的颜色:
然后在特定颜色xml文件中查找它是如何定义的,并使用该定义查找它的实际值(在valueXXX文件中的一个文件中…)
var typedArray = Theme.ObtainStyledAttributes(new int[] { id });
var color = typedArray.GetColor(0, int.MaxValue);
if (color != int.MaxValue)
{
Log.Debug("COLOR", color.ToString());
}