34

Is it possible to obtain styled attributes values from particular Theme without setting the theme up to application/activity? (I mean before invoking context.setTheme(..))

Praful Bhatnagar
  • 7,425
  • 2
  • 36
  • 44
Kid24
  • 4,401
  • 4
  • 23
  • 19
  • For anyone interested I found the solution by myself :) – Kid24 May 19 '11 at 00:43
  • 1
    TypedArray a = getTheme().obtainStyledAttributes(R.style.ThemeName, new int[] {R.attr.attribute_name}); – Kid24 May 19 '11 at 00:43
  • int attributeResourceId = a.getResourceId(0, 0); – Kid24 May 19 '11 at 00:44
  • 2
    Kid24, You can post an answer to your own question. This is useful since then it shows up as an answered question. – Cheryl Simon May 19 '11 at 00:45
  • 1
    thanks, I'll follow your advice, but later, cause unfortunately - "New users can't answer their own question for 8 hours" :) – Kid24 May 19 '11 at 01:01
  • 3
    Don't forget `a.recycle()`! Reference: http://stackoverflow.com/questions/7252839/what-is-the-use-of-recycle-method-in-typedarray – KitKat Sep 23 '13 at 16:20

3 Answers3

49

For example, to get editTextColor attribute's value of a theme called MyTheme:

TypedArray a = getTheme().obtainStyledAttributes(
        R.style.MyTheme,
        new int[] { R.attr.editTextColor });

// Get color hex code (eg, #fff)
int intColor = a.getColor(0 /* index */, 0 /* defaultVal */);
String hexColor = Integer.toHexString(intColor);

// Don't forget to recycle
a.recycle();
Clint
  • 1,014
  • 1
  • 10
  • 15
Kid24
  • 4,401
  • 4
  • 23
  • 19
  • 2
    ...and if you are looking for a way to also get the themes style resource id dynamically see here: http://stackoverflow.com/a/9537629/317889 – HGPB Jan 24 '13 at 17:25
  • 2
    You should call [`a.recycle()`](http://developer.android.com/reference/android/content/res/TypedArray.html#recycle()) when you're done with the TypedArray. – ayke Aug 22 '15 at 21:48
2

JavaDoc:

method TypedArray android.content.res.Resources.Theme.obtainStyledAttributes(int[] attrs)

Return a TypedArray holding the values defined by Theme which are listed in attrs.

Be sure to call TypedArray.recycle() when you are done with the array.

KitKat
  • 1,495
  • 14
  • 15
2

if you need it in the xml file, you can use something like this:

style="?android:attr/panelTextAppearance"

for example:

<TextView
    style="?android:attr/panelTextAppearance"
    android:paddingTop="?android:attr/paddingTop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/your_text"
    />

if you're using eclipse, control+click on the item, to see other possible values (a file attrs.xml will open).

lenooh
  • 10,364
  • 5
  • 58
  • 49