开发者

changing theme in java doesn't change background-color

开发者 https://www.devze.com 2023-04-06 02:00 出处:网络
I\'m trying to change the theme on runtime with java-code, because I want to have the user be able to change the app-theme via the preferences-menu.

I'm trying to change the theme on runtime with java-code, because I want to have the user be able to change the app-theme via the preferences-menu. so, I let the user the theme, and then read the results like this:

if (...) {
    getApplication().setTheme(R.style.BlackTheme);
} else {
    getApplication().setTheme(R.style.LightTheme);
}

unfortunately this doesnt work for some reason.... the font-color slightly shifts from darker gray (light theme) to a brighter gray (black theme) but the background always stays white/black (depending on which theme wes initially selected in the manifest-file)

If I completely remove the th开发者_如何转开发eme-entry in the manifest file, then its as if I would have selected the black-theme....

....is there something I'm overlooking?


I had the same problem and I solved in this way..

@Override
public void onCreate(Bundle savedInstanceState) {

    if (getIntent().hasExtra("bundle") && savedInstanceState==null){
        savedInstanceState = getIntent().getExtras().getBundle("bundle");
    }

    //add code for theme

    switch(theme)
    {
    case LIGHT:
        setTheme(R.style.LightTheme);
        break;
    case BLACK:
        setTheme(R.style.BlackTheme);
        break;

    default:
    }
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //code

}

this code is for recreate the Activity saving Bundle and changing the theme. You have to write your own onSaveInstanceState(Bundle outState); From API-11 you can use the method recreate() instead

Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();


You can't set the app theme at runtime. If you want to change the the theme everywhere in your application, you must call

setTheme(resId)

as a first thing in Activity's onCreate().

Eg:

@Override public void onCreate(Bundle savedInstanceState) { setTheme(resId) }

If you want to change the theme of already started activities, then you have to re-create them.


This is a known issue: https://code.google.com/p/android/issues/detail?id=3793

You have to change the background color manually, setTheme() will not change it.

0

精彩评论

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