Итак, я новичок, это мое первое приложение, и у меня проблемы с сохранением состояния тумблеров. Когда я выхожу из приложения, он очищает состояние переключателя и делает его похожим, если он не был переключен. Я все рассмотрел для решения, но когда я пытаюсь реализовать, как он предложил, я получаю ошибки и сбои. Все примеры, которые я видел, выглядят просто по сравнению с моим кодом, поэтому я не могу понять, как это сделать.Save Toggle Switch/Checkbox State with SharedPreferences
Проверенный эти темы ранее:
Save SWITCH button state, and recover state with SharedPrefs
Sharedpreferences with switch button
How to save the state of the toogleButton on/off selection?
how to save the state of switch(button) in android
Если кто-то может мне точку в решении я был бы очень счастлив. Вот отрывок из соответствующего кода:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchButton_Stat = (Switch) findViewById(switch_s);
textView_S = (TextView) findViewById(R.id.textView_S);
textView_S.setText(switchOff);
switchButton_Stat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
textView_S.setText(switchOn);
CompoundButton toggle_d = (CompoundButton)findViewById(R.id.switch_d);
if (toggle_d.isChecked()){
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
handler_mon.removeCallbacks(runnable_mon);
handler_sun.postDelayed(runnable_sun,300);
}
else {
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
handler_sun.removeCallbacks(runnable_sun);
handler_mon.postDelayed(runnable_mon,300);
}
}
else {
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
handler_mon.removeCallbacks(runnable_mon);
handler_sun.removeCallbacks(runnable_sun);
textView_S.setText(switchOff);
}
}
});
switchButton_Day = (Switch) findViewById(R.id.switch_d);
textView_D = (TextView) findViewById(R.id.textView_D);
textView_D.setText(MonOff);
switchButton_Day.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean dChecked) {
if (dChecked) {
textView_D.setText(SunOff);
Switch switch_s = (Switch) findViewById(R.id.switch_s);
if (switch_s.isChecked()){
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
handler_mon.removeCallbacks(runnable_mon);
handler_sun.postDelayed(runnable_sun,300);
}
Log.i(TAG, "Day Switch");
} else {
textView_D.setText(MonOff);
Switch switch_s = (Switch) findViewById(R.id.switch_s);
if (switch_s.isChecked()){
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
//NM.cancel(2);
handler_sun.removeCallbacks(runnable_sun);
handler_mon.postDelayed(runnable_mon,300);
}
}
}
});
}
Хорошо, так что я думаю, я понял, что я делаю неправильно ... В моих предыдущих попытках я добавил «SharedPreferences.Editor» пару, чтобы сохранить состояние из переключение в неправильный оператор if/else, поскольку у меня есть инструкции if/else, вложенные друг в друга. Ниже приводится реализация
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchButton_Stat = (Switch) findViewById(switch_s);
SharedPreferences tog_prefs = getSharedPreferences("TOG_PREF", MODE_PRIVATE);
boolean tglpref_1 = tog_prefs.getBoolean("tglpref_1", false);
if (tglpref_1) {
switchButton_Stat.setChecked(true);
} else {
switchButton_Stat.setChecked(false);
}
switchButton_Stat = (Switch) findViewById(switch_s);
textView_S = (TextView) findViewById(R.id.textView_S);
textView_S.setText(switchOff);
switchButton_Stat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
if (bChecked) {
SharedPreferences.Editor editor = getSharedPreferences("TOG_PREF", MODE_PRIVATE).edit();
editor.putBoolean("tglpref_1", true); // value to store
editor.commit();
textView_S.setText(switchOn);
CompoundButton toggle_d = (CompoundButton)findViewById(R.id.switch_d);
if (toggle_d.isChecked()){
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
handler_mon.removeCallbacks(runnable_mon);
handler_sun.postDelayed(runnable_sun,300);
}
else {
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
handler_sun.removeCallbacks(runnable_sun);
handler_mon.postDelayed(runnable_mon,300);
}
}
else {
SharedPreferences.Editor editor = getSharedPreferences("TOG_PREF", MODE_PRIVATE).edit();
editor.putBoolean("tglpref_1", false); // value to store
editor.commit();
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.cancelAll();
handler_mon.removeCallbacks(runnable_mon);
handler_sun.removeCallbacks(runnable_sun);
textView_S.setText(switchOff);
}
}
});
эй, сколько «коммутаторов» есть? один или более чем один? – tpk
Есть 2 переключателя – UberNoob
Все самое лучшее и счастливое кодирование. – tpk