简单的解决方案是使用 SharedPreferences,
你可以阅读它here
代码
在您的活动中创建这两种方法:
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方法就完成了。