I am having Stopwatch app. I have Switchcompat for different backgrounds on the main layout. When I tap the switch while running the time, it is reset to 00:00:00.
Is there any way to use the switch without resetting the timer?
Here are some parts of the code.
MainActivity
SwitchCompat switchCompat;
SharedPreferences sharedPreferences = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchCompat = findViewById(R.id.switchCompat);
sharedPreferences = getSharedPreferences("night", 0);
Boolean booleanValue = sharedPreferences.getBoolean("NightMode", false);
if (booleanValue) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
}
switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
switchCompat.setChecked(true);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("NightMode", true);
editor.commit();
}else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
switchCompat.setChecked(false);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("NightMode", false);
editor.commit();
}
}
});
}
check out saving instance state pattern - store time value and re-store when Activity
recreates
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("SwitchText", switchCompat.getText().toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
switchCompat = findViewById(R.id.switchCompat);
if (savedInstanceState != null) { // is null on first start
String switchText = savedInstanceState.getString("SwitchText");
// may be null when no value stored under given key
if (switchText != null) switchCompat.setText(switchText);
}
...
Activity
gets recreated/restared because in onCheckedChanged
you are calling AppCompatDelegate.setDefaultNightMode
- this is forcing Activity
to restart and apply new theme, and you have to write some additional code for saving previous state