在 Android 中以编程方式访问主题/样式/属性
我想访问编译到我的 apk 中的复杂资源(“包资源”)。例如,获取当前主题的所有属性,最好是作为我可以遍历的 xml。
可以使用 getStyledAttributes() 访问主题/样式,但需要提前了解属性。有没有办法获取样式中存在的属性列表?
例如,在这样的主题中:
<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>
如何在不事先知道项目名称的情况下访问这些项目?
另一个示例是 attrs.xml,其中某些属性具有枚举或标志,例如:
<attr name="configChanges">
<flag name="mcc" value="0x00000001" />
<flag name="mnc" value="0x00000002" />
...
</attr>
应用程序如何在不知道其名称的情况下获取这些标志?
I'd like to access complex resources ("bag resources") compiled into my apk. For example, getting all the attributes of the current theme, preferably as an xml I can traverse.
Themes/styles can be accessed using obtainStyledAttributes() but it requires knowing the attributes in advance. 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:
<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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以使用
Resources.obtainTypedArray(int)
代替Theme.obtainStyledAttributes(...)
来访问样式的所有属性,而无需指定您要访问哪些属性。然后您可以访问 TypedArray 的元素来查找每个属性的资源 id/类型/值。
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.You can then access the elements of the TypedArray to find the resource id/types/values of each attribute.
可能有更好的方法,但您始终可以使用 getXml
There is probably a better way, but you can always access the 'raw' XML using getXml