[英]Programmatically accessing themes/styles/attrs in Android
I'd like to access complex resources ("bag resources") compiled into my apk. 我想访问编译到我的apk中的复杂资源(“包资源”)。 For example, getting all the attributes of the current theme, preferably as an xml I can traverse.
例如,获取当前主题的所有属性,最好是我可以遍历的xml。
Themes/styles can be accessed using obtainStyledAttributes() but it requires knowing the attributes in advance. 可以使用obtainStyledAttributes()访问主题/样式,但需要事先知道属性。 Is there a way to get a list of the attributes that exist in a style?
有没有办法获得样式中存在的属性列表?
For example, in a theme like this: 例如,在这样的主题中:
<style name="BrowserTheme" parent="@android:Theme.Black">
<item name="android:windowBackground">@color/white</item>
<item name="android:colorBackground">#FFFFFFFF</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>
</style>
how can I access the items without knowing their names in advance? 如何在不事先知道姓名的情况下访问这些项目?
Another example would be attrs.xml, where some attributes have enums or flags, such as this: 另一个例子是attrs.xml,其中一些属性有枚举或标志,例如:
<attr name="configChanges">
<flag name="mcc" value="0x00000001" />
<flag name="mnc" value="0x00000002" />
...
</attr>
How can an application get these flags without knowing their name? 应用程序如何在不知道其名称的情况下获取这些标志?
Instead of Theme.obtainStyledAttributes(...)
, Resources.obtainTypedArray(int)
can be used to access all the attributes for a style, without having to specify which attributes you are interested in. 可以使用
Resources.obtainTypedArray(int)
代替Theme.obtainStyledAttributes(...)
来访问样式的所有属性,而无需指定您感兴趣的属性。
You can then access the elements of the TypedArray to find the resource id/types/values of each attribute. 然后,您可以访问TypedArray的元素以查找每个属性的资源ID /类型/值。
TypedArray array = getResources().obtainTypedArray(
R.style.NameOfStyle);
for (int i = 0; i < array.length(); ++i) {
TypedValue value = new TypedValue();
array.getValue(i, value);
int id = value.resourceId;
switch (value.type) {
case TypedValue.TYPE_INT_COLOR_ARGB4:
// process color.
break;
// handle other types
}
}
可能有更好的方法,但您始终可以使用getXml访问“原始”XML
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.