如何通过参考编号获取主题 [英] How to obtain a theme by its reference id
问题描述
我需要从一个主题中提取一个默认值,而不是从当前主题中提取一个值.
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
但是我需要类似的东西
Theme darkTheme = getTheme(R.style.AppTheme.Dark);
... 我只需要提取一个值,就不需要更改当前主题.
... I only need to extract a single value, I do not want to change the current theme.
推荐答案
我们可以通过在基本Context
周围创建具有所需主题的临时ContextThemeWrapper
来实现此目的,尽管我相信任何可用的Context
这样就可以了,因为包装程序应该替换给定主题中存在的所有属性值.
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();
另一个选项如下.可能更可取,因为它看起来好像Theme
不保存对任何Context
的引用.
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);
这篇关于如何通过参考编号获取主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!