在 android studio 中,我正在尝试创建一个用户可以翻转的开关,表明他或她在线。该开关工作正常,但是任何时候方向发生变化或用户退出应用程序时,该开关都会默认并且是因此不再在线。我尝试过使用 onSaveInstanceState 进行实验,但不知道如何传递变量来指示按钮已翻转,并且应该在不同 Intent 和退出应用程序期间保持翻转状态。目前,我的按钮代码是:
location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(boolean isChecked) {
if(isChecked){
FirebaseDatabase.getInstance().goOnline();
startLocationUpdates();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are online", Snackbar.LENGTH_SHORT).show();
}else{
FirebaseDatabase.getInstance().goOffline();
stopLocationUpdates();
mCurrent.remove();
mMap.clear();
handler.removeCallbacks(drawPathRunnable);
Snackbar.make(mapFragment.getView(),"You are offline", Snackbar.LENGTH_SHORT).show();
}
}
});
我是否可以完全保存此 Intent 中的所有信息?如果没有,我只想保持按钮打开。
最佳答案
在 setContentView
之后的 onCreate
中执行以下操作:
SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
location_switch = (MaterialAnimatedSwitch)findViewById(R.id.location_switch);
// Set the status of the switch from shared preferences
location_switch.setChecked(sharedPreferences.getBoolean("location_switch_state", false));
location_switch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(boolean isChecked) {
// Save the switch status in shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("location_switch_state", isChecked);
editor.apply();
if(isChecked){
FirebaseDatabase.getInstance().goOnline();
startLocationUpdates();
displayLocation();
Snackbar.make(mapFragment.getView(),"You are online", Snackbar.LENGTH_SHORT).show();
}else{
FirebaseDatabase.getInstance().goOffline();
stopLocationUpdates();
mCurrent.remove();
mMap.clear();
handler.removeCallbacks(drawPathRunnable);
Snackbar.make(mapFragment.getView(),"You are offline", Snackbar.LENGTH_SHORT).show();
}
}
});
关于java - MaterialAnimatedSwitch 保存状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870035/