所以我需要复选框来保存退出或切换活动时的状态。我需要很多复选框,所以我需要一个适用于所有复选框的函数。请帮忙。
简单的解决方案是使用SharedPreferences,你可以在这里阅读它
法典
在您的活动中创建以下 2 种方法:
private void saveCheckboxesStates(){
SharedPreferences sharedPref =getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);//replace fileName with any name you like
SharedPreferences.Editor editor = sharedPref.edit();
//suppose we have 3 checkboxes that we want to save their states
editor.putBoolean("checkbox1_state", checkBox1.isChecked()));
editor.putBoolean("checkbox2_state", checkBox2.isChecked()));
editor.putBoolean("checkbox3_state", checkBox3.isChecked()));
editor.apply();
}
private void loadCheckboxesStates(){
SharedPreferences sharedPref = getActivity().getSharedPreferences("fileName",Context.MODE_PRIVATE);
boolean checkbox1State= sharedPref.getBoolean("checkbox1_state", false);
boolean checkbox2State= sharedPref.getBoolean("checkbox2_state", false);
boolean checkbox3State= sharedPref.getBoolean("checkbox3_state", false);
checkBox1.setChecked(checkbox1State);
checkBox2.setChecked(checkbox2State);
checkBox3.setChecked(checkbox3State);
}
现在重写onBackPressed
和onDestroy
方法并像这样调用saveCheckboxesStates
:
@Override
public void onBackPressed() {
super.onBackPressed();
saveCheckboxesStates();
}//this handle the case when the user clicks back the activity
@Override
public void onDestroy () {
super.onDestroy();
saveCheckboxesStates();
}//this handle the case when your app gets killed
然后在onCreate
方法中调用该方法loadCheckboxesStates
,您就完成了。