Select All items of a ListView (custom row with checkbox in it)
Asked Answered
G

3

14

What I have: I have a ListView with custom rows, having a CheckBox & two TextViews in each row. I have a button for "Select All".

What i want: I want that when I click the button, all the CheckBox in ListView get checked/unchecked.

What is the problem: In OnClick of the "Select All" button. i am doing this:

public void OnClickSelectAllButton(View view)
{
    ListView l = getListView();
    int count = l.getCount();
    for(int i=0; i<count; ++i) 
    {
       ViewGroup row = (ViewGroup)l.getChildAt(i);
       CheckBox check = (CheckBox) row.findViewById(R.id.checkBoxID);
       check.setChecked(true); // true for select all and false for unselect all etc..
    }
}

Here l.getChildAt(i) is giving me the visible items only. And when the index goes out of visible items, the problem occurs. I want to check all the CheckBox in List, not just the visible ones.

Gesso answered 9/2, 2011 at 7:59 Comment(1)
possible duplicate of Android Checkbox listview select all (disable/enable)Manikin
I
21

It will occur, because ListView adapter reuses views. The way you are trying to do is incorrect. I don't think you ever should access listview rows through listview children.

Introduce a variable in your activity, that will hold the current state (boolean checkAll). When the user presses the button, it must set "checkAll" to true, and call notifyDataSetChanged() (for arrayadapter), or requery() (for cursoradapter) on your ListView's adapter. In adapter's getView() method introduce a check for this flag, so if (checkAll) {check the check box}

Impeachable answered 9/2, 2011 at 8:14 Comment(0)
S
3

have you looked this Correct way to check all checkboxes in ListView?

int count = getListAdapter().getCount();
Shriek answered 9/2, 2011 at 8:9 Comment(0)
C
0

I think you should run this long-running task off the UI thread. When you click button in OnClickListener:

new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < list.getAdapter().getCount(); i++) {
                                final int position = i;
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        list.setItemChecked(pos, true);  
                                    }
                                });
                            }
                        }
                    }).start();     

and in onCreate() :

this.mHandler = new Handler();

Each item in list view should be Checkable like CheckableRelativeLayout that implements Checkable interface.

Caesarea answered 19/12, 2014 at 8:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.