35

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(..))

6
  • For anyone interested I found the solution by myself :) Commented May 19, 2011 at 0:43
  • 1
    TypedArray a = getTheme().obtainStyledAttributes(R.style.ThemeName, new int[] {R.attr.attribute_name}); Commented May 19, 2011 at 0:43
  • 2
    Kid24, You can post an answer to your own question. This is useful since then it shows up as an answered question. Commented May 19, 2011 at 0:45
  • 1
    thanks, I'll follow your advice, but later, cause unfortunately - "New users can't answer their own question for 8 hours" :) Commented May 19, 2011 at 1:01
  • 3
    Don't forget a.recycle()! Reference: stackoverflow.com/questions/7252839/… Commented Sep 23, 2013 at 16:20

3 Answers 3

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

...and if you are looking for a way to also get the themes style resource id dynamically see here: stackoverflow.com/a/9537629/317889
You should call a.recycle() when you're done with the TypedArray.
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.

1 Comment

What happens, if not? E.g. because I leave the function scope?
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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.