Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically accessing themes/styles/attrs in Android

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?

like image 202
Andro Id Avatar asked Nov 30 '11 02:11

Andro Id


2 Answers

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
    }
  }
like image 91
Michael Smith Avatar answered Nov 09 '22 14:11

Michael Smith


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

like image 33
NuSkooler Avatar answered Nov 09 '22 14:11

NuSkooler