Android 如何使用共享首选项在列表视图中保存切换按钮的状态
我是android新手,面临着共享偏好的问题 这就是我要做的Android 如何使用共享首选项在列表视图中保存切换按钮的状态,android,listview,sharedpreferences,togglebutton,Android,Listview,Sharedpreferences,Togglebutton,我是android新手,面临着共享偏好的问题 这就是我要做的 我的应用程序包含微调器和列表视图 列表视图由我成功构建的微调器填充 列表视图的每一行都包含一个切换按钮,这将在用户选择时提醒对话框或警报 为了保存切换按钮的状态,我正在使用共享首选项,现在我在这里被绊倒了 final ToggleButton btnlock = (ToggleButton) view.findViewById(R.id.btn); btnlock.setTag(pIndex)
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();
}
这个吐司味精显示我总是错误的,位置总是一个常数
为什么我会得到这个,以及如何解决这个问题 在保存部分,您正在加载名为“MyPref”的共享首选项文件 在加载部分,您正在加载名为“MY_Pref”的共享首选项文件 这是两个完全不同的文件,这就是为什么您看不到保存的密钥强> 为了避免将来出现此类问题,请将文件名放在常量中
public static final String PREF_FILE = "SomethingSomethingSomething"
然后像这样获取您的SharedReference:
SharedPreferences prefs = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE).edit();
什么是“sp”?评论太短SP是共享首选项名称请回答,您的问题是不同的文件名称我已更正,但toast msg对每个位置显示为false,并且位置正在更新
public static final String PREF_FILE = "SomethingSomethingSomething"
SharedPreferences prefs = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE).edit();