Android Checkbox listview select all (disable/enable)

35,857

Solution 1

This is what finally worked for me, where I'm using a cursor adapter, not just an ArrayListAdapter for my list items:

final ListView list = getListView();
for ( int i=0; i< getListAdapter().getCount(); i++ ) {
        list.setItemChecked(i, true);
}

list.getChildCount doesn't work because it only seems to count what's been drawn immediately (not everything that's off the screen) so childCount might only be 6 or 8 items when the entire list is 100 or more items. Also as I had to use list.setItemChecked to get the items to 'stay checked' -- at least in my case where my list items were instances of CheckedTextView.

Solution 2

for(int i=0; i < listView.getChildCount(); i++){
    RelativeLayout itemLayout = (RelativeLayout)listView.getChildAt(i);
    CheckBox cb = (CheckBox)itemLayout.findViewById(R.id.MyListViewCheckBox);
    cb.setChecked(true);
}

You need to edit this code to handle both enabling and disabling, but I hope you get the idea !

Also, this only checks each checkbox, make sure you are returning an id or object from your list in order to send/save the data elsewhere.

Share:
35,857

Related videos on Youtube

Yousuf Qureshi
Author by

Yousuf Qureshi

GOOD skill, LUCK is for losers!!

Updated on May 01, 2020

Comments

  • Yousuf Qureshi
    Yousuf Qureshi almost 4 years

    I want to disable/enable all checkboxes in listview. infact want to get select all behaviour by clicking on top checkbox.

    thanks

  • Yousuf Qureshi
    Yousuf Qureshi over 13 years
    sorted.. thanks so much Abhinav.. much apprecaited
  • bancer
    bancer about 12 years
    This code creates some weird behavior when I check all items and then uncheck one item. Solution from Thom Nichols is better.
  • Manikandan
    Manikandan almost 12 years
    I have buttons in my listview. When click a button outside of listview, I need to change the background of the entire buttons present in the listview. I used your code, and got error. How to achieve this.
  • Manikandan
    Manikandan almost 12 years
    How can I work with buttons like this?
  • Roy
    Roy about 11 years
    This checks only the items which are currently in view. So if you have a listView with more items than the view can show, not all items will be checked. The answer from Thom Nichols is indeed the proper solution.
  • Faruk
    Faruk over 8 years
    thank you.. i've facing troble because childCount
  • madhu527
    madhu527 almost 8 years
    working like charm

Related