以编程方式切换应用程序范围的主题?

发布于 2024-10-11 05:37:19 字数 994 浏览 3 评论 0原文

我正在尝试获取用户选择的主题,但令人沮丧的是,我感觉很接近。在 AndroidManifest.xml 中定义主题可以正常工作,但是(据我所知)不能根据应用程序首选项进行更改:

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

或者,在每个活动中动态设置它也可以:

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

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

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

据我所知, this 应该可以解决问题,但实际上它没有做任何事情 - 整个应用程序具有默认的 Android 风格。上述内容是否有效,如果有效,我可能会做其他愚蠢的事情吗?

如果这很重要的话,我正在 API 级别 3 工作。非常感谢正确方向的产品!

相关问题。

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

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?

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

Related question.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

挥剑断情 2024-10-18 05:37:19

为您的应用创建一个基本 Activity 并重写 onCreate 以设置主题。从这个基本活动中派生出所有其他活动。

另请检查本教程:

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

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

Also check this tutorial:

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

各自安好 2024-10-18 05:37:19

对此可能有一个很好的解决方案,但我找不到一个,所以我最终在一个辅助类中创建了一个静态辅助方法,该方法接受一个 Activity 并基本上执行您编写的这两行。当然,它并不完美,但只需向我的应用程序中的每个 onCreate() 方法添加一小行代码就可以了。

There may be a good solution to this, but I couldn't find one, so I ended up making a little static helper method in a helper class that takes an Activity and basically performs those two lines you wrote. Sure, it's not perfect, but just adding one short line of code to every onCreate() method in my app was tolerable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文