android – 为什么getTheme在Application上运行不正常

前端之家收集整理的这篇文章主要介绍了android – 为什么getTheme在Application上运行不正常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我意识到,对于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,true);
// typedValue.resourceId is valid

我想知道为什么我们不能通过应用程序解析属性

在清单中,我们在应用程序级别找到特定的主题信息.所以,我认为从Application对象获取主题确实有意义.

<application
    android:theme="..."

解决方法

它不起作用,因为getApplicationContext()返回的对象显然不是一个完整的Context对象,如 in this answer by CommonsWare所示:

It’s not a complete Context,supporting everything that Activity does. VarIoUs things you will try to do with this Context will fail,mostly related to the GUI.

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

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

但这种方法并未得到Android开发团队的认可;正确的解决方案是使用Activity来处理与UI相关的事情,比如getTheme().

猜你在找的Android相关文章