【发布时间】:2021-02-23 06:35:45
【问题描述】:
我正在使用秒表应用程序。 我在主布局上有不同背景的 Switchcompat。 当我在运行时间时点击开关时,它会重置为 00:00:00。
有什么方法可以在不重置计时器的情况下使用开关?
以下是部分代码。
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();
}
}
});
}
【问题讨论】:
标签: java android switchcompat