开发者

Switching application-wide theme programmatically?

开发者 https://www.devze.com 2023-02-04 05:36 出处:网络
I\'m attempting to get a user-chosen theme and feel like I\'m frustratingly close. Defining the theme in AndroidManifest.xm开发者_JAVA百科l works as it should, but (as best I can tell) can\'t change b

I'm attempting to get a user-chosen theme and feel like I'm frustratingly close. Defining the theme in AndroidManifest.xm开发者_JAVA百科l 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消