在Android中,可以通过以下几种方式来保存和恢复Switch的状态:
SharedPreferences preferences = getSharedPreferences("switch_state", Context.MODE_PRIVATE);
boolean switchState = preferences.getBoolean("switch", false);
Switch switchButton = findViewById(R.id.switchButton);
switchButton.setChecked(switchState);
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("switch", isChecked);
editor.apply();
}
});
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("switch", switchButton.isChecked());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolean switchState = savedInstanceState.getBoolean("switch");
switchButton.setChecked(switchState);
}
public class SwitchViewModel extends ViewModel {
private MutableLiveData<Boolean> switchState = new MutableLiveData<>();
public void setSwitchState(boolean state) {
switchState.setValue(state);
}
public LiveData<Boolean> getSwitchState() {
return switchState;
}
}
SwitchViewModel switchViewModel = new ViewModelProvider(this).get(SwitchViewModel.class);
switchViewModel.getSwitchState().observe(this, new Observer<Boolean>() {
@Override
public void onChanged(Boolean state) {
switchButton.setChecked(state);
}
});
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switchViewModel.setSwitchState(isChecked);
}
});
通过以上方式,可以在Android应用中保存和恢复Switch的状态。根据具体情况选择合适的方式来实现状态保存和恢复。