how to bind a checkbox to a listview

后端 未结 2 910
灰色年华
灰色年华 2021-01-22 09:55

I have a listview containing on each row a textview with a checkbox, so when the checkbox is checked and we scroll down through the listview the checkbox instance will be taken

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-22 10:28

    It looks like your OnCheckedChangedListener is the problem here. If you look at your code, see that every checkbox is getting a reference to the same listener. So when you check one box, you're setting every other box as checked too - and you're not updating your backing data, either.

    Your OnCheckedChangedListener should not be updating the view state of the checkbox - the callback is fired because the state has already changed.

    So you need to do the following steps when a user checks the checkbox:

    1. Figure out which item was checked, and how that corresponds to your data
    2. Update your data to suit the new checked/unchecked state
    3. Notify your adapter of a data change/update your cursor

    You could do this something like the following, tagging the view with the ID of the row it represents:

    public boolean setViewValue(View view, Cursor cursor, int columnIndex){
        if(view.getId() == R.id.bt_rating){
            view.setTag(cursor.getInt(cursor.getColumnIndex(SomeDBContract.ID)));
            ((CheckBox)view).setChecked(Boolean.valueOf(cursor.getString(cursor.getColumnIndex("Favorites"))));
            ((CheckBox)view).setOnCheckedChangeListener(myCheckChangList);
            return true; //true because the data was bound to the view
        }
        return false;
    }
    

    Then, in your listener you can update your database according to that ID:

    CheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                 int rowId = (int) buttonView.getTag();
                 // Handle updating the database as per normal
                 updateSomeDbRowAsChecked(rowId, isChecked);
            }
        };
    

    Finally, you'll need to update your cursor adapter with a new cursor once the database row is updated:

     myAdapter.swapCursor(newCursor);
    

    You'll have to adjust all of this to suit your code, but it should give you an idea of one way you can approach this problem.

提交回复
热议问题