Switching application-wide theme programmatically?

家住魔仙堡 提交于 2019-11-26 02:53:44

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4663752/switching-application-wide-theme-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!