我正在尝试使用共享偏好设置保存复选框。但是......随机复选框正在被选中。请帮我调试代码...... 基本上创建了三个checkboxese但我无法保存它们......
package com.isit.finale;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.view.Menu;
public class History extends Activity implements OnClickListener {
CheckBox c1;
CheckBox c2;
CheckBox c3;
Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
c1 = (CheckBox) findViewById(R.id.checkBox1);
c2 = (CheckBox) findViewById(R.id.checkBox2);
c3 = (CheckBox) findViewById(R.id.checkBox3);
b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(this);
loadSavedPreferences();
}
private void loadSavedPreferences() {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences= PreferenceManager.getDefaultSharedPreferences(this);
boolean c1Val= sharedPreferences.getBoolean("CheckBox_Value", false);
boolean c2Val= sharedPreferences.getBoolean("CheckBox_Value", false);
boolean c3Val= sharedPreferences.getBoolean("CheckBox_Value", false);
if (c1Val)
{c1.setChecked(true);
}
else{
{c1.setChecked(false);
}
};
if(c2Val){
c2.setChecked(true);
}
else{ c2.setChecked(false);
};
if (c3Val){
c3.setChecked(true);
}
else{ c3.setChecked(false);
}
}
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(c1.isChecked())
savePreferences("CheckBox_Value",c1.isChecked()); if(c2.isChecked())
savePreferences("CheckBox_Value",c2.isChecked() if(c3.isChecked())
savePreferences("CheckBox_Value",c3.isChecked());
finish();
}
}`
答案 0 :(得分:4)
您尚未保存复选框偏好设置。
private void savePreferences(String key, boolean value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
请记住为每个复选框首选项添加唯一键
在加载时检索正确的密钥。
答案 1 :(得分:1)
而不是每个复选框的相同键,您应该为每个复选框创建唯一的键。