Android ListView with Checkbox


We implemented listview and added on item click listener in last two tutorials. Most of the time you need to implement the listview in which user has to select multiple items. So, this tutorial will take you on advance level. I have read multiple listview checkbox tutorials. Most of them looks very complicated but this tutorial shows you the easiest way to implement it. We will implement checkbox in a listview in very simple way.

ListView with Checkbox Implementation

The idea is to use the CheckedTextView inside the listview.

The screenshot of the tutorial

list-view-checbox-android

If you haven't read the basic listview tutorial and are unfamiliar with listview in android then i request you to go back and read those tutorials first.

For listview we need two layout files.

  1. First file to hold our listview
  2. Second file to hold view-item of listview.

First Layout file

This file is a simple xml file containing a listview.
activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>

Now let us see the code of second layout file.

list_item.xml

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    	
        android:id="@+id/checkedTextView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:gravity="center"
        android:drawableLeft="?android:attr/listChoiceIndicatorMultiple"
         />

In the above layout we have added "CheckedTextView" which is a view with a "text" and a "checkbox". Initially the checkbox is hidden. To enable it we need to add the following line of code

android:drawableLeft="?android:attr/listChoiceIndicatorMultiple"

Also you need to add namespace to make our "CheckedTextView" available as a layout xml file. We need to bound this URI to make it a part of android layout.

xmlns:android="http://schemas.android.com/apk/res/android"

Now we are done with our layout files, let us move towards implementing the activity. We have already learned about creation of simple listview. If you want to revise then you can see the detailed explanation in my previous notes.

Explanation :

  • Get the reference of listview.
  • Create and adapter which will take the layout as an argment and the array of data.
  • Adapter will load the items inside listview when we call setAdapter() method of listview.
  • Now the most important code which helps us to select multiple checkbox is
    listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
  • CHOICE_MODE_MULTIPLE tells to listview that we will be selecting multiple items. If you remove this line of code then only one item of listview can be clicked.

MainActivity.java

package com.example.activitykb4dev;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	ListView listview;
	String[] foody;
	Context context;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		listview = (ListView)findViewById(R.id.listView1);
	//string array
	String[] foody = {"pizza", "burger", "chocolate", "ice-cream", "banana", "apple"}; 
	// set adapter for listview	
	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, foody);
	listview.setAdapter(adapter);
	listview.setItemsCanFocus(false);
        // we want multiple clicks 
	listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

 

How to get Selected Values

We have added checkboxes to our list. In this part of the tutorial, we explain how to get the selected values.

Screenshot of the layout

How can you achieve this kind of layout ?

 

By using android:weight with linear layouts we can assign weights to different views i.e we will be telling that how much space should be given to a particular view-item.

 

For example if there are four TextView. Three of them demands android:weight="1"  and fourth is given no weight. Then the weight of three items will grow as screen grows but fourth one will get only enough space to get occupy.

Below xml will help you to create a layout with weight attribute.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
   >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1" >
    </ListView>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Submit" />

</LinearLayout>

Now for listening to the events you need to add OnItemClickListener. Steps involved are :

  • Create a class and make it implement interface OnItemClickListener
    public class CheckBoxClick implements OnItemClickListener{
    
    	@Override
    	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    		// TODO Auto-generated method stub
    		
    	}	
    }
  • Implement onItemClick() which is an unimplemented method for OnItemClickListener interface.
  • In your onCreate() method of activity add following statement to set event listener for checkbox items.
    listview.setOnItemClickListener(new CheckBoxClick());
  • CheckBoxClick class :
    public class CheckBoxClick implements OnItemClickListener{
    
    	@Override
    	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    		// TODO Auto-generated method stub
    		CheckedTextView ctv = (CheckedTextView)arg1;
    		if(ctv.isChecked()){
    			Toast.makeText(MainActivity.this, "now it is unchecked", Toast.LENGTH_SHORT).show();
    		}else{
    			Toast.makeText(MainActivity.this, "now it is checked", Toast.LENGTH_SHORT).show();
    		}	
    	}	
    }
  • In the above code we have fetched the view which was clicked. We will check the previous state of this view and depending upon previous state we will do desired action

So it was about adding event to checbox. In the next article we will click the button to get all the checked items from listview and we will pass it to the next activity.