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?
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().
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.
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.
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.
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)) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With