你好,我不知道怎么了。我要创建一个开关按钮,该状态保存在“共享首选项”中,并且当“活动”启动时,开关按钮应处于已保存状态。但是,当我将“ if(isChecked)”之后的代码更改为“ editor.putBoolean(“ SOUND”,false);“时,按钮始终为true。则开关按钮始终为假。请告诉我我做错了什么,或者给我工作代码。
public class MainActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
ConstraintLayout startLayout;
AnimationDrawable animationDrawable;
Button start;
TextView rangAnzeige;
static Switch sound;
static Boolean ka;
public static final String NAME = "MeinePrefs";
public static SharedPreferences mySettings;
@SuppressLint({"NewApi", "ResourceAsColor"})
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
startLayout = findViewById(R.id.startLayout);
animationDrawable = (AnimationDrawable) startLayout.getBackground();
animationDrawable.setEnterFadeDuration(4500);
animationDrawable.setExitFadeDuration(4500);
animationDrawable.start();
sound = findViewById(R.id.sound);
rangAnzeige = findViewById(R.id.ranganzeige);
start = findViewById(R.id.starten);
TextView tvhighscore = findViewById(R.id.highscore);
mySettings = getSharedPreferences(NAME, MODE_PRIVATE);
sound.setOnCheckedChangeListener(this);
einstellungenladen();
}
public void einstellungenladen() {
ka = mySettings.getBoolean("SOUND",true);
if (ka = true) {
sound.setChecked(true);
}
else {
sound.setChecked(false);
}
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
SharedPreferences.Editor editor = mySettings.edit();
editor.putBoolean("SOUND",true);
editor.apply();
}
else {
SharedPreferences.Editor editor = mySettings.edit();
editor.putBoolean("SOUND",false);
editor.apply();
}
}
}