[英]How to save checkbox state in listview using sharedpreference
我在listview中有復選框,我希望在我點擊它時保存復選框狀態,現在當我恢復我的應用程序時,所有復選框都將被取消選中。我正在嘗試開發TODO列表應用程序列表行textview將被刪除和復選框將被檢查,我如何將復選框狀態和striken textview保存到共享首選項和加載。
protected void onCreate(Bundle saved) {
super.onCreate(saved);
setContentView(R.layout.cbox_list);
Listvw = (ListView) findViewById(R.id.clistvw);
Listvw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
cText = (TextView) view.findViewById(R.id.ctext);
cBox = (CheckBox) view.findViewById(R.id.cbox);
cBox.setChecked(true);
//Toast.makeText(getActivity(),"Clicked",Toast.LENGTH_LONG).show();
cText.setPaintFlags(cText.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
//boolean value=cBox.isChecked();
int b = Listvw.getAdapter().getCount();
for (int i1 = 0; i1 < b; i1++) {
if (cBox.isChecked()) {
SharedPreferences spf = PreferenceManager.getDefaultSharedPreferences(CBox_InListView.this);
SharedPreferences.Editor edit = spf.edit();
edit.putBoolean("name"+i1, cBox.isChecked());
edit.commit();
}
}
}
});
model = new CheckModel[12];
model[0] = new CheckModel("Item1", 0);
model[1] = new CheckModel("Item", 0);
model[2] = new CheckModel("Item", 0);
model[3] = new CheckModel("Item", 0);
model[4] = new CheckModel("Item", 0);
model[5] = new CheckModel("Item", 0);
model[6] = new CheckModel("Item", 0);
model[7] = new CheckModel("Home Head", 0);
model[8] = new CheckModel("Item", 0);
model[9] = new CheckModel("Item", 0);
model[10] = new CheckModel("Item", 0);
model[11] = new CheckModel("Item", 0);
CustomAdapter adpter = new CustomAdapter(this, model);
int c=Listvw.getAdapter().getCount();
for(int i=0;i<c;i++)
{
SharedPreferences pf=PreferenceManager.getDefaultSharedPreferences(CBox_InListView.this);
boolean chkbx=pf.getBoolean("name"+i,false);
if(chkbx){
cBox.setChecked(true);
}else{
cBox.setChecked(false);
}
}
Listvw.setAdapter(adpter);
對大數據使用SharedPreferences並不是一個好方法。 你應該使用的是SQLlite數據庫來維護你的TODO列表的當前狀態。 將todo的標題設置為主鍵,並且CheckModel類中應該有一個布爾變量,用於定義是否選中復選框。
然后,您必須在適配器的getView方法中實現邏輯,以將復選框設置為已選中或未選中狀態,而不是您現在正在執行此操作的方式。
- >創建Sqlite數據庫並創建一個包含應用程序所需字段的表,並為復選框狀態創建一個字段
- >現在在加載復選框活動時加載數據庫,並在listview填充數據庫中的數據時填充復選框狀態。
- >當用戶選擇或取消選中復選框時,偵聽復選框狀態並更新數據庫
對每個列表項使用共享首選項並不好,數據庫是不錯的選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.