我真的需要一些帮助。即使搜索了几个小时并阅读了有关 SharedPreferences
的主题,我也无法解决我的问题。
即使我离开 Activity ,我也希望复选框(多个复选框!)保持选中/未选中状态。如果我回到原来的 Activity ,复选框应该处于与之前相同的状态。 因此,您基本上可以将应用程序置于后台,如果您再次将其置于前台或进行其他 Activity ,复选框仍应选中/取消选中(取决于用户选中的内容)。
这是我的 Activity.java 代码:
public class TennisActivity extends AppCompatActivity {
//Variabeln
CheckBox cb118;
CheckBox cb119;
CheckBox cb120;
CheckBox cb121;
CheckBox cb122;
CheckBox cb123;
CheckBox cb149;
CheckBox cb150;
CheckBox cb151;
CheckBox cb152;
CheckBox cb153;
//Going back to menu by pressing back on device
@Override
public void onBackPressed() {
//super.onBackPressed();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent homeIntent = new Intent(TennisActivity.this, SportActivity.class);
startActivity(homeIntent);
finish();
}
}, 1);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tennis);
//Variabeln initalisiern
cb118 = (CheckBox) findViewById(R.id.checkBox118);
cb119 = (CheckBox) findViewById(R.id.checkBox119);
cb120 = (CheckBox) findViewById(R.id.checkBox120);
cb121 = (CheckBox) findViewById(R.id.checkBox121);
cb122 = (CheckBox) findViewById(R.id.checkBox122);
cb123 = (CheckBox) findViewById(R.id.checkBox123);
cb149 = (CheckBox) findViewById(R.id.checkBox149);
cb150 = (CheckBox) findViewById(R.id.checkBox150);
cb151 = (CheckBox) findViewById(R.id.checkBox151);
cb152 = (CheckBox) findViewById(R.id.checkBox152);
cb153 = (CheckBox) findViewById(R.id.checkBox153);
}
}
预先感谢您的帮助!
最佳答案
使用Shared Preferences在用户切换复选框时保存当前状态。再次到达 onCreate
后,您可以从中重新加载数据。
获取共享首选项:
SharedPreferences sharedPref =
getActivity().getSharedPreferences("MY_SHARED_APPLICATIONS_NAME", Context.MODE_PRIVATE);
写:
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("MY_BOOL_VARIABLE_KEY", myBoolVariable);
editor.commit();
阅读:
myBoolVariable = sharedPref.getBoolean("MY_BOOL_VARIABLE_KEY", defaultValue);
对于您的特定情况,您将需要一个 key 来识别每个复选框,如下所示:
private static final String cb118Key = "cb118_key";
然后在你初始化复选框之后,你应该根据保存在 SharedPreferences
中的内容设置它们的状态:
cb118Checked = sharedPref.getBoolean(cb118Key, defaultValue);
cb118.setChecked(cb118Key);
唯一缺少的是在用户更改复选框状态时保存新状态:
cb118.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
editor.putBoolean(cb118Key, isChecked);
editor.commit();
}
});
关于java - 如何在离开 Activity 后保持多个复选框的选中状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45620431/