[英]how to save the state of toggle button in list view using shared preferences
I am new in android and facing problem with shared preferences here is what i am trying to do 我是android的新手,面临共享首选项的问题,这是我想要做的
for saving state of toggle button i am using shared preferences now here i am getting stucked 用于保存切换按钮的状态我现在在使用共享首选项在这里我被卡住了
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();
}
}
});
on list i am using this 在清单上我正在使用这个
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();
}
this toast msg is showing me always false and the position is always a constant why i am getting this and how to solve this? 此吐司味精向我显示总是错误,并且位置始终是常数,为什么我得到此错误以及如何解决此问题?
in the saving part you are loading shared preference file named "MyPref" 在保存部分中,您正在加载名为“ MyPref”的共享首选项文件
Editor editor = getSharedPreferences("MyPref", 0).edit();
and in the loading part you are loading shared preference file named "MY_Pref" 在加载部分中,您正在加载名为“ MY_Pref”的共享首选项文件
sp = getSharedPreferences("MY_Pref", 0);
those are two completely different files, which is why you're not seeing your saved key! 这是两个完全不同的文件,这就是为什么您看不到保存的密钥的原因!
to avoid this type of problem in the future, put your file name in a constant 为避免将来出现此类问题,请将文件名放在一个常量中
public static final String PREF_FILE = "SomethingSomethingSomething"
and then get your sharedPreferences like this: 然后像这样获取您的sharedPreferences:
SharedPreferences prefs = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE,Context.MODE_PRIVATE).edit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.