以编程方式切换应用程序范围的主题?
我正在尝试获取用户选择的主题,但令人沮丧的是,我感觉很接近。在 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为您的应用创建一个基本 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
对此可能有一个很好的解决方案,但我找不到一个,所以我最终在一个辅助类中创建了一个静态辅助方法,该方法接受一个 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.