我的应用程序中有一个设置活动,用户可以在其中选择亮模式、暗模式,并使用三个单选按钮跟随系统。但是,当应用程序重新启动时,无论在单选按钮上选择什么,都会始终应用遵循系统。我用 SharedPreferences 试过,但没有用。我怎样才能解决这个问题?
Java类:
package com.example.formelrechner;
import...
public class Einstellungen extends AppCompatActivity {
RadioGroup radioGroup;
RadioButton radioButton, radioButton2, radioButton3;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MO DE_NIGHT_YES) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
if (AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE_NIGHT_NO) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_einstellungen);
radioGroup = findViewById(R.id.radiogroup);
radioButton = findViewById(R.id.radioButton);
radioButton2 = findViewById(R.id.radioButton2);
radioButton3 = findViewById(R.id.radioButton3);
radioButton.setChecked(Update("SaveStateOne"));
radioButton2.setChecked(Update("SaveStateTwo"));
radioButton3.setChecked(Update("SaveStateThree"));
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean one_isChecked) {
SaveintosharedPrefs("SaveStateOne", one_isChecked);
if (one_isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
}
}
});
radioButton2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean two_isChecked) {
SaveintosharedPrefs("SaveStateTwo", two_isChecked);
if (two_isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
}
}
});
radioButton3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean three_isChecked) {
SaveintosharedPrefs("SaveStateThree", three_isChecked);
if (three_isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
}
}
});
}
private void SaveintosharedPrefs(String key, boolean value) {
SharedPreferences sp = getSharedPreferences("SaveState",MODE_PRIVATE);
final SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(key,value);
editor.apply();
}
private boolean Update(String key) {
SharedPreferences sp = getSharedPreferences("SaveState",MODE_PRIVATE);
return sp.getBoolean(key, false);
}
}