select all check box in android listview

MGR picture MGR · May 2, 2013 · Viewed 8.3k times · Source

In my Application, i tried to create a list with multiple check boxes.

for that i tried one ListView with android.R.layout.simple_list_item_multiple_choice for multiple choice in ListView.

My ListView in XML as,..

<ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="468dp"
        android:choiceMode="multipleChoice"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp" >

And i use an CheckBox to select/deselect all the CheckBox in the ListView as

   <CheckBox
            android:id="@+id/select_all"
            android:layout_width="120dp"
            android:layout_height="wrap_content"
            android:layout_column="2"
            android:textSize="18dp"
            android:text="Select all" />

and java code as,..

selectall.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            int size = 0;
            boolean isChecked = selectall.isChecked();
            if (isChecked == true) {
                size = getListView().getCount();
                for (int i = 0; i <= size; i++)
                    l1.setItemChecked(i, true);
            } else if(isChecked==false)
            {
                size = getListView().getCount();
                for (int i = 0; i <= size; i++)
                    l1.setItemChecked(i, false);
            }
        }
    });

Here i have assigned the l1 as my ListView. Now my Select All check box working very well for Select/Deselect all the check boxes in the ListView.

But, if i deselect one of the item after clicking select all check box, its not un-checking..

And if i select all the check boxes in the list manually means, the Select all CheckBox needs to checked automatically..

I used the following codes for ListAdapter

ArrayAdapter<String> adapter1 = new ArrayAdapter<String>
       (this,Android.R.layout.simple_list_item_multiple_choice,list);
     setListAdapter(adapter1);
     l1=getListView();

I'm trying to achieve this Solution..

Answer

An-droid picture An-droid · Jun 18, 2013

you could use a HashMap or a List of theObjectRow to keep track of which sheckbox is checked with a boolean.

then when you click on checkAll you update all boolean in your list to true and do yourAdapter.notifyDataSetChanged();

of course in your adapter (baseadapter for example) you use the HashMap/List in GetView to init the cells.

if(list.get(position).isChecked()){
    cellHolder.checkBox.setChecked(true);
}
else{
    cellHolder.checkBox.setChecked(false);
}

All the boolean are at true so all the checkBox ll be checked (the same logic goes for uncheck)

hope it help good luck