Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to obtain the resource ID of the current theme?

Tags:

android

In Android, you can get the current theme of an activity as a Resource.Theme object from getTheme(). Also, you can set the theme to a different one via that other theme's resource id, as in setTheme(R.style.Theme_MyTheme).

But how do I find out whether it's worth it -- whether the current theme is already the one that I would want to set? I am looking for something like getTheme().getResourceId(), in order to write something like:

protected void onResume() {     int newThemeId = loadNewTheme();     if (newThemeId != getTheme().getResourceId()) { // !!!! How to do this?         setTheme(newThemeId);         // and rebuild the gui, which is expensive     } } 

Any ideas?

like image 889
marc1s Avatar asked Sep 01 '11 08:09

marc1s


People also ask

How to check current theme in android?

To get the current theme (to decide if it's the one you want), simply use the getApplication(). getTheme() . If it's the theme you want, you don't have to do anything. If you want to apply logic and programatically set the theme, use the getApplication().

What is obtainStyledAttributes in android?

obtainStyledAttributes. Return a TypedArray holding the attribute values in set that are listed in attrs . In addition, if the given AttributeSet specifies a style class (through the "style" attribute), that style will be applied on top of the base attributes it defines.

What is theme resource?

A ThemeResource is a technique for obtaining values for a XAML attribute that are defined elsewhere in a XAML resource dictionary. The markup extension serves the same basic purpose as the {StaticResource} markup extension.

Where are Android studio themes?

Under the Appearance & Behaviour -> Appearance, you will find Theme. Choose the right theme from the drop-down and click on Apply and then Ok. Here you can see the background and color scheme for all three themes.


1 Answers

I found a way to solve the requirement without getting the resource id.

I'm adding an item to each of my themes with the name of the string:

<item name="themeName">dark</item> 

And in the code I check the name like so:

TypedValue outValue = new TypedValue(); getTheme().resolveAttribute(R.attr.themeName, outValue, true); if ("dark".equals(outValue.string)) {    ... } 
like image 159
marmor Avatar answered Sep 17 '22 21:09

marmor