Programmatically accessing themes/styles/attrs in Android

6

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?

android
android-layout
apk
asked on Stack Overflow Nov 30, 2011 by Andro Id • edited Dec 24, 2018 by Cœur

2 Answers

3

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.

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
    }
  }
answered on Stack Overflow Jan 19, 2012 by Michael Smith
1

There is probably a better way, but you can always access the 'raw' XML using getXml

answered on Stack Overflow Jan 11, 2012 by NuSkooler

User contributions licensed under CC BY-SA 3.0