Select all checkbox in android list

In my application, I tried to create a list with several checkboxes.

for this i tried one ListView with android.R.layout.simple_list_item_multiple_choice for multiple selection in ListView .

My ListView in XML is like ..

 <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 CheckBox to select / deselect all CheckBox in 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 like, ..

 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 assigned l1 as my ListView . Now, my Select All checkbox works very well for selecting / deselecting all the checkboxes in the ListView .

But if I canceled the selection of one of the items after clicking, select all the checkbox, do not cancel the check.

And if I select all the checkboxes in the list manually, select "Select All" CheckBox , which you need to check 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 am trying to reach this solution.

+4
source share
1 answer

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

then when you click checkAll , you will update all the booleans in your list to true and do yourAdapter.notifyDataSetChanged ();

Of course, in your adapter (for example, the base adapter), you use the HashMap / List in GetView to initialize the cells.

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

All booleans are true, so all checkBox will be checked (the same logic goes to uncheck)

hope this helps good luck

+1
source

All Articles