在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的狀態。根據具體情況選擇合適的方式來實現狀態保存和恢復。