Implementing CheckAll and UncheckAll for a listview in Android

June 21, 2012
By

In this article we are implementing the operations “CheckAll” and “UncheckAll”  for a listview in Android


1. Create an Android project named ListViewCheckAll

Create New Android Project

Figure 1 : Create New Android Project


2.Select build target for this application

Select Android Build Target

Figure 2 : Select Android Build Target


3. Enter application details

Application Details

Figure 3 : Application Details


4. Open and update the file res/values/strings.xml with the given below code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">ListViewCheckAll</string>
    <string name="strAll">All</string>
</resources>

5. Open and update the file res/layout/main.xml with the given below code


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="right"
        android:paddingRight="5dp"
    >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/strAll"
        />

        <CheckBox
            android:id="@+id/chkAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        />

    </LinearLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:choiceMode="multipleChoice"
    />
</LinearLayout>

6. Open and update the file sr/in/wptrafficanalyzer/checkall/MainActivity.java with the given below code


package in.wptrafficanalyzer.checkall;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;

public class MainActivity extends ListActivity {

    /** String array used as the datasource for the ArrayAdapter of the listview **/
    String[] countries = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "Bangladesh",
        "China",
        "Afghanistan"
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** Defining array adapter to store items for the listview **/
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, countries);

        /** Setting the arrayadapter for this listview  **/
        getListView().setAdapter(adapter);

        /** Defining checkbox click event listener **/
        OnClickListener clickListener = new OnClickListener() {

            @Override
            public void onClick(View v) {
                CheckBox chk = (CheckBox) v;
                int itemCount = getListView().getCount();
                for(int i=0 ; i < itemCount ; i++){
                    getListView().setItemChecked(i, chk.isChecked());
                }
            }
        };

        /** Defining click event listener for the listitem checkbox */
        OnItemClickListener itemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            CheckBox chk = (CheckBox) findViewById(R.id.chkAll);
            int checkedItemCount = getCheckedItemCount();

            if(getListView().getCount()==checkedItemCount)
                chk.setChecked(true);
            else
                chk.setChecked(false);
            }
        };

        /** Getting reference to checkbox available in the main.xml layout */
        CheckBox chkAll =  ( CheckBox ) findViewById(R.id.chkAll);

        /** Setting a click listener for the checkbox **/
        chkAll.setOnClickListener(clickListener);

        /** Setting a click listener for the listitem checkbox **/
        getListView().setOnItemClickListener(itemClickListener);

    }

    /**
    *
    * Returns the number of checked items
    */
    private int getCheckedItemCount(){
        int cnt = 0;
        SparseBooleanArray positions = getListView().getCheckedItemPositions();
        int itemCount = getListView().getCount();

        for(int i=0;i<itemCount;i++){
            if(positions.get(i))
                cnt++;
        }
    return cnt;
    }
}


7. Application in execution

CheckAll Android Application in execution

Figure 4: CheckAll Android Application in execution


8. Download the source code


9. Testing the Android Application

The application developed in this article is tested in the article titled “Testing CheckAll and UnCheckAll of Android ListView using Android Testing Framework“.


10. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

7 Responses to Implementing CheckAll and UncheckAll for a listview in Android

  1. Steven on April 12, 2013 at 10:11 am

    I want to know :
    - first checkAll ischecked -> all item ischecked
    - and then I check checkAll again -> all item uncheck (where is code)

    • george on April 12, 2013 at 11:29 am

      Please see the lines from 50 to 63 (highlighted code) of the class “MainActivity”

  2. Deepti on May 9, 2013 at 7:12 pm

    how to get dynamically some checkboxs are check and some chackboxs are uncheck

  3. Tungds on January 1, 2014 at 10:49 pm

    I have same main layout and a baseadapter which includes an image, a textview and a checkbox. When i fill data to adapter, my listview has 10 items(7 visible and 3 invisible(scroll to see)).And I use your code to apply to my code but when i check checkbox(chkAll), nothing happens. Can you help me?

  4. Horace on February 22, 2015 at 5:31 am

    Thanks this helped me a lot

  5. naimuddin on June 5, 2015 at 11:41 am

    You have called getlistview() method.. but where you created this getlistview() method?????

    • tung on June 5, 2015 at 2:35 pm

      getlistview() method is a method of ListActivity. You’ll see “extends ListActivity” on top code

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner