[英]how to save the state of toggle button in list view using shared preferences
我是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();
}
此吐司味精向我顯示總是錯誤,並且位置始終是常數,為什么我得到此錯誤以及如何解決此問題?
在保存部分中,您正在加載名為“ 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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.