我创建了暗模式,并且可以在设置我要进行切换的活动中很好地工作,但是我无法添加到其他活动中(我不知道如何操作)。 这是我的代码
sharedprefs = new SharedPrefs(this);
if (sharedprefs.loadNightModeState()==true){
setTheme(R.style.darktheme);
}
else setTheme(R.style.AppTheme);
if (sharedprefs.loadNightModeState()==true){
darkmode.setChecked(true);
}
darkmode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
sharedprefs.setNightModeState(true);
restartApp();
}
else {
sharedprefs.setNightModeState(false);
restartApp();
}
}
public void restartApp() {
Intent i = new Intent(getApplicationContext(), SettingsActivity.class);
startActivity(i);
finish();
}
});
我在SharedPrefs.java中还有另一个代码
public class SharedPrefs {
SharedPreferences mySharedPref ;
public SharedPrefs(Context context) {
mySharedPref = context.getSharedPreferences("filename",Context.MODE_PRIVATE);
}
// this method will save the nightMode State : True or False
public void setNightModeState(Boolean state) {
SharedPreferences.Editor editor = mySharedPref.edit();
editor.putBoolean("NightMode",state);
editor.commit();
}
// this method will load the Night Mode State
public Boolean loadNightModeState (){
Boolean state = mySharedPref.getBoolean("NightMode",false);
return state;
}
}
我如何使它适用于每个活动?
答案 0 :(得分:0)
尝试将其放在每个活动的开头,当 onCreate 方法启动时。这是我用过的,非常适合我。
SharedPreferences userPref = androidx.preference.PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//Use preference to set night or light mode
if(userPref.getBoolean(getString(R.string.displayMode),false)){
if(userPref.getBoolean(getString(R.string.overideMode), true)){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
PS - 只需确保将我使用的变量更改为您使用的变量,否则显然无法正常工作。如果你卡住了,请告诉我。一切顺利!!