Maintaining checkbox states in listview with CursorAdapter

前端 未结 3 1391
小鲜肉
小鲜肉 2020-12-10 18:02

For my Android project, I have a listview which has a checkbox for every item. The data is loaded from an SQLite database by using a CursorAdapter class. However, whenever I

3条回答
  •  被撕碎了的回忆
    2020-12-10 18:48

    Try this

    public class VocabCursorAdapter extends CursorAdapter { 
    
       private ArrayList itemChecked = new ArrayList(); // array list for store state of each checkbox
    
       public VocabCursorAdapter(Context context, Cursor c, int flags) {
    
           for (int i = 0; i < c.getCount(); i++) { // c.getCount() return total number of your Cursor
                itemChecked.add(i, false); // initializes all items value with false
           }
       }
    
        @Override
        public void bindView(View view, Context context, Cursor cursor) {
    
            ...
            final int position = cursor.getPosition(); // get position by cursor
    
            CheckBox checkBox = (CheckBox) view.findViewById(R.id.editCheckbox);
            checkBox.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {
    
                        if (itemChecked.get(position) == true) { // if current checkbox is checked, when you click -> change it to false
                            itemChecked.set(position, false);
                        } else {
                            itemChecked.set(position, true);
                        }
                    }
           });
    
           checkBox.setChecked(itemChecked.get(position)); // set the checkbox state base on arraylist object state
           Log.i("In VocabCursorAdapter","position: "+position+" - checkbox state: "+itemChecked.get(position));
        }
    }
    

提交回复
热议问题