【问题标题】:I need checkboxes to save their state whn i go out of app or the activity当我退出应用程序或活动时,我需要复选框来保存它们的状态
【发布时间】:2017-10-31 20:18:52
【问题描述】:

所以当我退出或切换活动时,我需要复选框来保存状态。我需要很多复选框,所以我需要一个适用于所有复选框的函数。 请帮忙。

【问题讨论】:

  • 当您说“退出”时,您的意思是强制关闭应用程序吗?或者只是返回启动器并将应用程序留在后台?
  • 我相信他/她指的是后者!在这种情况下,OP 应该考虑将最后一个复选框状态 onDestroy 存储在首选项中;
  • 强制关闭,例如将其从最近的应用程序或其名称中滑开。但是当我回击并离开活动时它也会重置

标签: android


【解决方案1】:

简单的解决方案是使用 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);

}

现在覆盖 onBackPressedonDestroy 方法并像这样调用 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方法就完成了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2011-12-31
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 2013-09-05
    相关资源
    最近更新 更多