【发布时间】:2021-12-25 10:31:48
【问题描述】:
我正在尝试在我的应用中实现浅色/深色主题。如果我不杀死该应用程序,主题的更改效果很好。但是如果我这样做,例如,在杀死它之前我已经将它设置为黑暗主题。重启应用后,每个 Activity 和 Fragment 都会再次回到 Light Theme。
我实现了共享首选项,但似乎仍然无法弄清楚问题所在。
设置主题确定按钮代码:
bottomSheetView.findViewById(R.id.settingsGeneral_changeTheme_btnOK).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (tempTheme) {
case 1:
theme = 1; //update global value
//update theme in shared pref
if (mPreferences.contains(SP_THEME_KEY)) {
SharedPreferences.Editor spEditor = mPreferences.edit();
spEditor.putInt(SP_THEME_KEY, theme);
spEditor.apply();
}
//set theme
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case 2:
theme = 2; //update global value
//update theme in shared pref
if (mPreferences.contains(SP_THEME_KEY)) {
SharedPreferences.Editor spEditor = mPreferences.edit();
spEditor.putInt(SP_THEME_KEY, theme);
spEditor.apply();
}
//set theme
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
}
bottomSheetDialog.dismiss();
}
});
在非常活动或片段的 oncreate 方法中,我这样做:
mPreferences = getSharedPreferences(spFileName, MODE_PRIVATE); //get sp file
if (mPreferences.contains(SP_THEME_KEY)) { //if got this key
theme = mPreferences.getInt(SP_THEME_KEY, 2);
switch(theme){
case 1: //dark
setTheme(R.style.darkTheme);
break;
case 2: //light
setTheme(R.style.appTheme);
break;
}
} else { //if don't have this key (app first launch)
theme = 2; //by default its light mode
SharedPreferences.Editor spEditor = mPreferences.edit();
spEditor.putInt(SP_THEME_KEY, theme);
spEditor.apply();
setTheme(R.style.appTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general_settings);
应用onCreate代码:
public class MigotoApplication extends Application {
private final String SP_THEME_KEY = "sp_theme_key";
private SharedPreferences mPreferences;
private String spFileName = "settingsSpFile";
private int theme;
@Override
public void onCreate() {
super.onCreate();
if (mPreferences.contains(SP_THEME_KEY)) { //if got this key
theme = mPreferences.getInt(SP_THEME_KEY, 2);
switch(theme){
case 1: //dark
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
case 2: //light
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
}
} else { //if don't have this key (app first launch)
theme = 2; //by default its light mode
SharedPreferences.Editor spEditor = mPreferences.edit();
spEditor.putInt(SP_THEME_KEY, theme);
spEditor.apply();
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
}
【问题讨论】:
标签: java android sharedpreferences android-dark-theme