如何通过其参考 ID 获取主题

How to obtain a theme by its reference id

我需要从主题中提取默认值,但不是从当前主题中提取。

我知道我可以像这样获取当前主题的属性:

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);

... 我只需要提取单个值,我不想更改当前主题。

似乎没有任何直接的方法可以从资源中实例化或以其他方式创建 Theme 对象,至少据我所知是这样。

最初的建议是创建一个临时 ContextThemeWrapper 并从中获取 Theme 对象。我们包装应用程序 Context,因为它不会(不应该)已经有一个主题:

Theme darkTheme = new ContextThemeWrapper(getApplicationContext(), R.style.AppTheme_Dark).getTheme();

然后我意识到我们可以做类似的事情:

Theme darkTheme = getResources().newTheme();
darkTheme.applyStyle(R.style.AppTheme_Dark, true);

事实证明,这正是 ContextThemeWrapper 解决方案在内部所做的,所以这种方法显然更可取,因为我们不会不必要地创建和丢弃 ContextThemeWrapper 实例。

请注意,在哪个 Context 上调用 getResources() 并不重要;最终 newTheme() 只是 returns 一个空的 Theme。此外,尽管名称(以及样式和主题的一般 non-interchangeability),Theme#applyStyle() 实际上确实采用了主题资源 ID。