问题
I need to extract a default value from a theme, BUT NOT from the current theme.
I know that I can get get the attributes from the current theme like this:
TypedValue typedValue = new TypedValue();
Theme currentTheme = context.getTheme();
currentTheme.resolveAttribute(android.R.attr.windowBackground, typedValue, true);
// result is in: typedValue.data
but I need something like:
Theme darkTheme = getTheme(R.style.AppTheme.Dark);
... I only need to extract a single value, I do not want to change the current theme.
回答1:
It looks like we can do this by creating a temporary ContextThemeWrapper
with the desired theme around our base Context
, though I believe any available Context
will do, as the wrapper should replace any attribute values present in the given theme.
Theme darkTheme = new ContextThemeWrapper(getBaseContext(), R.style.AppTheme_Dark).getTheme();
Another option is as follows. This one might be preferable, since it looks as though a Theme
doesn't hold reference to any Context
.
Theme darkTheme = getResources().newTheme();
darkTheme.applyStyle(R.style.AppTheme_Dark, true);
来源:https://stackoverflow.com/questions/41976965/how-to-obtain-a-theme-by-its-reference-id