如何在代码中而不是在清单中为整个应用程序设置主题? [英] How to set a theme to whole application in code, but not in the Manifest?

查看:104
本文介绍了如何在代码中而不是在清单中为整个应用程序设置主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在清单中将主题设置为整个应用程序,但是如何以编程方式将主题设置为整个应用程序?我正在尝试:getApplicationContext. setTheme(R.style .mytheme),但是它不起作用.

I know how to set theme to whole application in manifest,but how to set theme to whole application programmatically ? I am trying this: getApplicationContext.setTheme(R.style.mytheme), but it doesn't work.

我认为getApplicationContext应用程序的上下文,它可以设置整个应用程序主题.

I think the getApplicationContext is the Application's Context, which can set whole application theme.

推荐答案

除非使用Java代码修改清单文件,否则无法将其从Java应用于整个应用程序.您想要将主题应用到的其他活动甚至可能没有运行,因此Android如何将主题应用到它们?在退出并返回程序后,所有更改都将丢失,您需要再次应用主题.

You can't apply it to a whole application from Java, unless you use Java code to modify the manifest file. The other activities you want to apply the theme to might not even be running so how would Android apply a theme to them? And after exiting and returning to your program all the changes would be lost and you'd need to apply the theme again.

getApplicationContext确实返回了应用程序上下文-但是仅仅因为方法采用了Context并不意味着将其传递给ApplicationContext会突然使它影响整个应用程序.实际上,通常它不会,并且就像您使用普通的Context一样可以正常工作.

getApplicationContext does return the application context - but just because a method takes a Context doesn't mean that passing it an ApplicationContext will suddenly make it affect the whole application. In fact in general it won't, and will just work as if you used a normal Context.

相反,不同上下文的重要性在于它们存在的时间不同-活动上下文是随活动创建和销毁的,但是在第一个应用程序组件运行时会创建应用程序上下文,而在最后一个组件运行时会销毁它被摧毁.

Rather the importance of the different contexts is that they are around for different amounts of time - an activity context is created and destroyed with the activity, but an Application context is created when the first application component runs and destroyed when the last component is destroyed.

这篇关于如何在代码中而不是在清单中为整个应用程序设置主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆