How to obtain a theme by its reference id

折月煮酒 提交于 2019-12-11 03:54:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!