保存单选按钮的状态 [英] Save the state of radiobutton
问题描述
我有我的应用程序5单选按钮,我想挽救自己的状态,这样,当我离开,然后再返回给应用程序,然后我看到相同的按钮,点击它被点击我退出应用程序之前,
I am having 5 radiobuttons in my application and i want to save their states so that when i exit and then come back to the application then i see the same button clicked which was clicked prior to my exiting the application
以下是我的code保存状态
Following is my code for saving the state
private int flag1 = true;
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", true);
}
protected void onPause() {
super.onPause();
save(!flag1);
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
}
@Override
protected void onResume() {
super.onResume();
save(load());
Toast.makeText(getApplicationContext(),""+load(), Toast.LENGTH_LONG).show();
}
I am calling the save method from inside the onCheckedChangeListener for every radiobutton but nothing happens.
有没有使用共享preferences ??的任何其他方法
Is there any other method of using sharedpreferences ??
推荐答案
您使用的是相同的密钥(检查)保存所有按钮的状态。尝试这样的事情
you are saving all button state using same key(check). Try something like this
private void save(int radioid,final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check"+radioid, isChecked);
editor.commit();
}
在通过所有单选按钮加载方法循环
In load method loop through all radiobutton
private void load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
for(int i=0;i<radioGroup.getChildCount();i++){
RadioButton rbtn=(RadioButton)radioGroup.getChildAt(i);
rbtn.setChecked(sharedPreferences.getBoolean("check"+rbtn.getId(), false));
}
}
更新
在RadioGroup中只有一个按钮在时间检查。
所以店里选中按钮ID而不是
In RadioGroup only one button is checked at a time. so store check button id instead.
private void save(int radioid) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("check", radioid);
editor.commit();
}
和使用以下code以恢复
and use following code to restore
private void load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
int radioId=sharedPreferences.getInt("check", 0);
if(radioId>0){
RadioButton rbtn=(RadioButton)radioGroup.findViewById(radioId);
rbtn.setChecked(true);
}
}
这篇关于保存单选按钮的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!