我是Android新手,面临共享偏好问题 这就是我想要做的事情
用于保存切换按钮的状态我现在正在使用共享偏好设置我被卡住了
final ToggleButton btnlock = (ToggleButton) view.findViewById(R.id.btn);
btnlock.setTag(pIndex);
btnlock.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(btnlock.isChecked()){
btnlock.setButtonDrawable(a_icon);
btnlock.setChecked(true);
position = (Integer) buttonView.getTag();
sp = getPreferences(MODE_PRIVATE);
Editor editor = getSharedPreferences("MyPref", 0).edit();
editor.putBoolean("in"+month+"_"+position, true);
editor.commit();
}else{
btnlock.setButtonDrawable(a_dicon);
btnlock.setChecked(false);
sp = getPreferences(MODE_PRIVATE);
Editor editor = getSharedPreferences("MyPref", 0).edit();
editor.putBoolean("in"+month+"_"+position, false); editor.commit();
}
}
});
列表我正在使用此
public View getView(final int index, View view, final ViewGroup parent) {
sp = getSharedPreferences("MY_Pref", 0);
btnlock.setChecked(sp.getBoolean("in"+month+"_"+position,false));
Toast.makeText(getApplicationContext(), "chking"+month+"_"+position+"_"+sp.getBoolean("on"+position ,false),
Toast.LENGTH_LONG).show();
}
这个toast msg告诉我总是假的,而且这个位置总是一个常数 为什么我得到这个以及如何解决这个问题?
答案 0 :(得分:1)
在保存部分中,您正在加载名为" MyPref"
的共享首选项文件 Editor editor = getSharedPreferences("MyPref", 0).edit();
并在加载部分中加载名为" MY_Pref"
的共享首选项文件sp = getSharedPreferences("MY_Pref", 0);
这两个完全不同的文件,这就是您没有看到保存的密钥的原因!
为了避免将来出现此类问题,请将文件名置于常量
public static final String PREF_FILE = "SomethingSomethingSomething"
然后得到你的sharedPreferences:
SharedPreferences prefs = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE).edit();