5

我意识到,对于Context.getTheme(),如果我们Application用作Context

MyApplication.singletonInstance().getTheme().resolveAttribute(R.attr.actionBarDeleteIcon, typedValue, true);
// typedValue.resourceId will be 0x0, which is invalid

但是,如果我Activity用作上下文,则效果很好

MyFragment.this.getActivity().getTheme().resolveAttribute(R.attr.actionBarDeleteIcon, typedValue, true);
// typedValue.resourceId is valid

我想知道为什么我们不能通过解析属性Application

在 manifest 中,我们可以在Applicationlevel 中找到特定的主题信息。所以,我认为从Application对象中获取主题确实有意义。

<application
    android:theme="..."
4

1 回答 1

5

它不起作用,因为显然返回的对象getApplicationContext()不是一个完整的Context对象,正如CommonsWare 在这个答案中所指出的:

它不是一个完整的Context,支持所做的一切Activity。您将尝试使用此执行的各种操作Context都会失败,主要与 GUI 有关。

一种可能的解决方案是手动设置主题Context,如下所示:

getApplicationContext().getTheme().applyStyle(R.style.MyTheme, true);

但是这种方法并没有得到 Android 开发团队的认可;正确的解决方案是使用Activity与 UI 相关的内容,例如getTheme().

于 2013-11-22T19:14:40.610 回答