以编程方式切换应用程序范围的主题? [英] Switching application-wide theme programmatically?

查看:26
本文介绍了以编程方式切换应用程序范围的主题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获得一个用户选择的主题,但我觉得我很接近.在 AndroidManifest.xml 中定义主题可以正常工作,但(尽我所知)不能根据应用偏好进行更改:

I'm attempting to get a user-chosen theme and feel like I'm frustratingly close. Defining the theme in AndroidManifest.xml works as it should, but (as best I can tell) can't change based on app preferences:

<application 
    android:theme="@style/theme_sunshine" 
    android:icon="@drawable/icon" 
    android:label="@string/app_name">

或者,在每个活动中动态设置它也有效:

Alternatively, setting it dynamically in each activity also works:

someChosenTheme = PreferenceManager.getDefaultSharedPreferences(this).getString("themePreference", "theme_twilight");
setTheme(someOtherChosenTheme);

但这看起来很乱,我宁愿在一个地方为整个应用程序设置主题.我的第一个想法是在我的主要活动启动后立即获取应用程序上下文并在那里执行:

But that seems messy, and I'd rather set the theme for the entire app in one place. My first thought was to grab the application context as soon as my main activity launches and do it there:

getApplicationContext().setTheme(R.style.theme_dummy);

尽我所知,这个 应该可以解决问题,但实际上它什么也没做——整个应用程序都具有默认的 Android 样式.以上是否有效,如果有效,我可能会做其他愚蠢的事情吗?

As best I can tell, this ought to do the trick, but in fact it's not doing anything - the entire app has the default Android style. Is the above valid, and if so, might I be doing something else dumb?

如果这很重要,我正在使用 API 级别 3.非常感谢正确方向的刺激!

I'm working in API level 3 if that matters. Prods in the right direction greatly appreciated!

相关问题.

推荐答案

为您的应用创建一个基本活动并覆盖 onCreate 以设置主题.从此基础活动中衍生出所有其他活动.

Create a base activity for your app and override onCreate to set the theme. Derive all your other activities from this base activity.

另请查看本教程:

http://www.androidengineer.com/2010/06/using-themes-in-android-applications.html

这篇关于以编程方式切换应用程序范围的主题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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