Android ListView with CheckBox Example

Hello Friend, I am going to explain you Android ListView With CheckBox. I have created an Android ListView with Checkbox example project. The ListView is a scrolling view component in Android and it is widely used in many applications. In ListView user can select list items by using CheckBox component. I will explain you in detail of each step to follow to get ListView and it’s CheckBox handling.

This tutorial shows you how to implement Android ListView with CheckBox.. We will develop an adapter to show Android listview with checkboxes.  The listview holds adapter which contains data in multiple rows/items. Each row has  its own CheckBox, ImageView and Title and Subtitle TextViews. Below are the key steps need to fallow to achieve Android ListView with CheckBoxes.

Android ListView With CheckBox:

Here are the screenshots of the application:

Home Screen :

ListViewWithCheckbox-Android-Checkbox-Demo

Android ListView with CheckBox

 

CheckBox Checked with Toast Message:

ListViewWithCheckbox-Android-Checkbox-Checked

 

CheckBox Unchecked with Toast Message:

ListViewWithCheckbox-Android-Checkbox-Unchecked

 

 Android ListView with OnItemClick and Toast Message:

ListViewWithCheckbox-Android-Checkbox-OnItemClick

 

Coding Part:

home_layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white" >
 
    <RelativeLayout
        android:id="@+id/title_bar_view"
        android:layout_width="match_parent"
        android:layout_height="@dimen/title_bar_view_height"
        android:background="@color/title_bar_view_color" >
 
        <RelativeLayout
            android:id="@+id/back_arrow_view"
            android:layout_width="@dimen/title_bar_view_height"
            android:layout_height="@dimen/title_bar_view_height"
            android:background="@color/title_bar_view_color"
            android:onClick="viewClickListener" >
 
            <ImageView
                android:id="@+id/back_arrow_imageview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:src="@drawable/ic_action_arrow_left" />
        </RelativeLayout>
 
        <TextView
            android:id="@+id/title_textview"
            style="@style/TitleTextStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@id/back_arrow_view"
            android:text="@string/app_name" />
    </RelativeLayout>
 
    <TextView
        android:id="@+id/header_textview"
        style="@style/HeaderTitleTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/title_bar_view"
        android:layout_centerHorizontal="true"
        android:padding="@dimen/view_left_right_margin"
        android:text="@string/list_of_fuits" />
 
    <ListView
        android:id="@+id/fruit_listview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/header_textview"
        android:layout_margin="@dimen/view_left_right_padding"
        android:divider="@color/divider_color"
        android:dividerHeight="@dimen/divider_height"
        android:smoothScrollbar="true" >
    </ListView>
 
</RelativeLayout>

 
 
fruit_item_layout.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="blocksDescendants"
    android:padding="@dimen/view_left_right_margin" >
 
    <CheckBox
        android:id="@+id/checkbox_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true" >
    </CheckBox>
 
    <ImageView
        android:id="@+id/profile_imageview"
        android:layout_width="@dimen/profile_photo_width_height"
        android:layout_height="@dimen/profile_photo_width_height"
        android:layout_centerVertical="true" >
    </ImageView>
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_margin="@dimen/relativelayout_margin"
        android:layout_toLeftOf="@id/checkbox_imageview"
        android:layout_toRightOf="@id/profile_imageview" >
 
        <TextView
            android:id="@+id/header_textview"
            style="@style/ListTitleTextStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true" />
 
        <TextView
            android:id="@+id/sub_textview"
            style="@style/ListSubtitleTextStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/header_textview"
            android:ellipsize="end"
            android:lines="2" />
    </RelativeLayout>
 
</RelativeLayout>

 
 
HomeActivity.java:

package com.vishalmobitech.listviewwithcheckbox;
 
import java.util.ArrayList;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
 
import com.vishalmobitech.listviewwithcheckbox.adapter.FruitListAdapter;
import com.vishalmobitech.listviewwithcheckbox.adapter.FruitListAdapter.OnFruitItemClickListener;
import com.vishalmobitech.listviewwithcheckbox.manager.FruitDummyDataManager;
import com.vishalmobitech.listviewwithcheckbox.model.FruitItem;
import com.vishalmobitech.listviewwithcheckbox.util.AppUtils;
 
/**
 * This is activity for this listView example. This will have checked/unchecked
 * action.
 * 
 * @author Amruta.Doye
 * 
 */
public class HomeActivity extends Activity {
 
	// The context variable to use in whole activity in place of
	// "HomeActivity.this".
	private Context mContext;
 
	// The FruitList Adapter to bind the views and show in listview.
	private FruitListAdapter mFruitListAdapter;
 
	// The ArrayList of Fruits<FruitItem>.
	private ArrayList<FruitItem> mFruitList;
 
	// The ListView of fruit message list.
	private ListView mFruitListview;
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_layout);
		mContext = HomeActivity.this;
		initView();
		mFruitList = FruitDummyDataManager.getFruitItemList();
		populateFruitList(mFruitList);
	}
 
	/**
	 * Method to init the views and required resources.
	 */
	private void initView() {
		mFruitListview = (ListView) findViewById(R.id.fruit_listview);
 
		// Setting item click listener
		mFruitListview.setOnItemClickListener(new OnItemClickListener() {
 
			@Override
			public void onItemClick(AdapterView<?> adpView, View view,
					int position, long itemId) {
				Log.d("TEST", "onItemClick");
				if (mFruitListAdapter != null) {
					FruitItem item = mFruitListAdapter.getItem(position);
					AppUtils.showToast(mContext, getString(R.string.item_click)
							+ item.getFruitname());
				}
			}
		});
 
	}
 
	/**
	 * The method to receive click events of views.
	 * 
	 * @param view
	 */
	public void viewClickListener(View view) {
		if (R.id.back_arrow_view == view.getId()) {
			finish();
		}
	}
 
	/**
	 * The listener to get list item click events.
	 */
	private OnFruitItemClickListener listListener = new OnFruitItemClickListener() {
 
		@Override
		public void onCheckboxClicked(int position, FruitItem item) {
			item.setCheckboxChecked(!item.isCheckboxChecked());
			mFruitListAdapter.notifyDataSetChanged();
			if (item.isCheckboxChecked()) {
				AppUtils.showToast(mContext, getString(R.string.fruit_name)
						+ item.getFruitname() + getString(R.string.is_checked));
			} else {
				AppUtils.showToast(mContext, getString(R.string.fruit_name)
						+ item.getFruitname()
						+ getString(R.string.is_unchecked));
			}
 
		}
 
	};
 
	/**
	 * Populate the list.
	 * 
	 * @param list
	 */
	private void populateFruitList(ArrayList<FruitItem> list) {
		if (list != null && list.size() > 0) {
			if (mFruitListAdapter == null) {
				mFruitListAdapter = new FruitListAdapter(mContext, mFruitList);
				mFruitListAdapter.setOnFruitClickListener(listListener);
			}
			mFruitListview.setAdapter(mFruitListAdapter);
		} else {
			mFruitListAdapter.setItemlist(mFruitList);
			AppUtils.showToast(mContext,
					getString(R.string.no_message_list_found));
		}
	}
 
	@Override
	protected void onDestroy() {
		if (mContext != null) {
			mFruitListAdapter = null;
			mFruitList = null;
			mFruitListview = null;
			mContext = null;
			super.onDestroy();
		}
	}
}

 
 

FruitListAdapter.java:

package com.vishalmobitech.listviewwithcheckbox.adapter;
 
import java.util.ArrayList;
 
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
 
import com.vishalmobitech.listviewwithcheckbox.R;
import com.vishalmobitech.listviewwithcheckbox.model.FruitItem;
 
/**
 * The adapter class to bind the views on the list view with contents.
 * 
 * @author Amruta.Doye
 * 
 */
public class FruitListAdapter extends BaseAdapter {
 
	// The ArrayList of Users<MessageItem>
	private ArrayList<FruitItem> mItemsList;
 
	// The LayoutInflater to holds layout inflater to inflate list item.
	private LayoutInflater mLayoutInflater;
 
	// The OnMessageClickListener of listener.
	private OnFruitItemClickListener listener;
 
	/**
	 * Constructor.
	 * 
	 * @param context
	 * @param list
	 */
	public FruitListAdapter(Context context, ArrayList<FruitItem> list) {
		mItemsList = list;
		mLayoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 
	}
 
	/**
	 * Method to set item list and notify adapter to update its views.
	 * 
	 * @param list
	 */
	public void setItemlist(ArrayList<FruitItem> list) {
		mItemsList = list;
		notifyDataSetChanged();
	}
 
	@Override
	public int getCount() {
		if (mItemsList != null) {
			return mItemsList.size();
		} else {
			return 0;
		}
	}
 
	@Override
	public FruitItem getItem(int position) {
		FruitItem item = null;
		if (mItemsList != null && mItemsList.size() > 0) {
			item = mItemsList.get(position);
		}
		return item;
	}
 
	@Override
	public long getItemId(int position) {
		return position;
	}
 
	/**
	 * Method to set the listener class object.
	 * 
	 * @param listener
	 */
	public void setOnFruitClickListener(OnFruitItemClickListener listener) {
		this.listener = listener;
	}
 
	/**
	 * Interface to provide click events to the required classes.
	 * 
	 * @author Amruta.Doye
	 * 
	 */
	public interface OnFruitItemClickListener {
 
		/**
		 * The method declaration for user selected. This method will be fired
		 * when user click on check/uncheck the checkbox on the list item.
		 * 
		 * @param position
		 * @param item
		 */
		public void onCheckboxClicked(int position, FruitItem item);
 
	}
 
	/**
	 * 
	 * @return update list from array list.
	 */
	public ArrayList<FruitItem> getUpdatedList() {
		return mItemsList;
	}
 
	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		View view = convertView;
		if (view == null) {
			ViewHolder viewHolder = new ViewHolder();
			view = mLayoutInflater.inflate(R.layout.fruit_item_layout, parent,
					false);
			viewHolder.header_textview = (TextView) view
					.findViewById(R.id.header_textview);
			viewHolder.sub_textview = (TextView) view
					.findViewById(R.id.sub_textview);
			viewHolder.profile_imageview = (ImageView) view
					.findViewById(R.id.profile_imageview);
			viewHolder.checkbox = (CheckBox) view
					.findViewById(R.id.checkbox_imageview);
			view.setTag(viewHolder);
		}
 
		ViewHolder viewHolder = (ViewHolder) view.getTag();
		final FruitItem item = getItem(position);
		if (item != null && viewHolder != null) {
			viewHolder.header_textview.setText(item.getFruitname());
			viewHolder.sub_textview.setText(item.getMessage());
			viewHolder.profile_imageview.setBackgroundResource(item
					.getPictureResId());
 
			viewHolder.checkbox.setTag(position);
			viewHolder.checkbox.setChecked(item.isCheckboxChecked());
			viewHolder.checkbox.setOnClickListener(new OnClickListener() {
 
				@Override
				public void onClick(View view) {
					listener.onCheckboxClicked(position, item);
				}
			});
 
		}
		return view;
	}
 
	/**
	 * View holder class to hold the views to bind on list view.
	 * 
	 * @author Amruta.Doye
	 * 
	 */
	public static class ViewHolder {
		TextView header_textview;
		TextView sub_textview;
		ImageView profile_imageview;
		CheckBox checkbox;
 
	}
 
}

 
 

FruitItem.java:

package com.vishalmobitech.listviewwithcheckbox.model;
 
import java.io.Serializable;
 
/**
 * The class to hold the fruit item.
 * 
 * @author Amruta.Doye
 * 
 */
public class FruitItem implements Serializable {
 
	private String fruitname;
	private String message;
	private int pictureResId;
	private boolean isCheckboxChecked;
 
	/**
	 * @return the pictureResId
	 */
	public int getPictureResId() {
		return pictureResId;
	}
 
	/**
	 * @param pictureResId
	 *            the pictureResId to set
	 */
	public void setPictureResId(int pictureResId) {
		this.pictureResId = pictureResId;
	}
 
	/**
	 * 
	 * @return fruitname
	 */
 
	public String getFruitname() {
		return fruitname;
	}
 
	/**
	 * 
	 * @param fruitname
	 */
	public void setFruitname(String fruitname) {
		this.fruitname = fruitname;
	}
 
	/**
	 * 
	 * @return message
	 */
	public String getMessage() {
		return message;
	}
 
	/**
	 * 
	 * @param message
	 */
	public void setMessage(String message) {
		this.message = message;
	}
 
	/**
	 * Method to check the check box is checked or not.
	 * 
	 * @return isCheckboxChecked
	 */
	public boolean isCheckboxChecked() {
		return isCheckboxChecked;
	}
 
	/**
	 * 
	 * @param isCheckboxChecked
	 */
	public void setCheckboxChecked(boolean isCheckboxChecked) {
		this.isCheckboxChecked = isCheckboxChecked;
	}
 
}

 
 

FruitDummyDataManager.java:

package com.vishalmobitech.listviewwithcheckbox.manager;
 
import java.util.ArrayList;
import java.util.Random;
 
import android.util.Log;
 
import com.vishalmobitech.listviewwithcheckbox.R;
import com.vishalmobitech.listviewwithcheckbox.model.FruitItem;
 
/**
 * This class is a manager class to manage and provide the contents.
 * 
 * @author Amruta.Doye
 * 
 */
public class FruitDummyDataManager {
 
	/**
	 * The array to hold pictures names.
	 */
	public static final int[] pictures = new int[] { R.drawable.ic_apple,
			R.drawable.ic_banana, R.drawable.ic_orange, R.drawable.ic_mango,
			R.drawable.ic_papaya, R.drawable.ic_pomegranate,
			R.drawable.ic_strawberry, R.drawable.ic_watermelon };
 
	/**
	 * The array to hold pictures names.
	 */
	public static final String[] titles = new String[] { "Apple", "Banana",
			"Orange", "Mango", "Papaya", "Pomegranate", "Strawberry",
			"Watermelon" };
 
	/**
	 * The array to hold messages.
	 */
	public static final String[] messages = new String[] {
			"Apple color is red.",
			"Banana color is yellow.",
			"Nagpur is famous for orange, thats why it is known as orange city.",
			"Mango is king of fruits.", "Papaya is best for skin.",
			"Pomegranate is most useful for increasing blood level.",
			"Strawberry color is red.", "Watermelon is very useful in summer." };
 
	/**
	 * Method to get fruit list using titles and messages arrays values.
	 * 
	 * @return list
	 */
	public static ArrayList<FruitItem> getFruitItemList() {
		ArrayList<FruitItem> list = new ArrayList<FruitItem>();
		for (int i = 0; i < titles.length; i++) {
			FruitItem item = new FruitItem();
			item.setFruitname(titles[i]);
			item.setMessage(messages[i]);
			item.setPictureResId(pictures[i]);
			list.add(item);
 
		}
		return list;
	}
 
	/**
	 * Method to get new fruits<FruitItem>, generated just to show demo with
	 * hardcoded fruit names and messages randomly.
	 * 
	 * @return item
	 */
	public static FruitItem getRandomItem() {
		FruitItem item = new FruitItem();
		int randomValue = new Random().nextInt(titles.length);
		item.setFruitname(titles[randomValue]);
		item.setMessage(messages[randomValue]);
		item.setPictureResId(pictures[randomValue]);
		return item;
	}
 
}

 
 

AppUtils.java:

/**
 * 
 */
package com.vishalmobitech.listviewwithcheckbox.util;
 
import android.content.Context;
import android.widget.Toast;
 
/**
 * The utility class where all utility methods are present and can be used
 * anywhere in the app.
 * 
 * @author Amruta.Doye
 * 
 */
public class AppUtils {
 
	/**
	 * The method to show toast messages.
	 * 
	 * @param context
	 * @param message
	 */
	public static void showToast(Context context, String message) {
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}
}

 
 

strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="app_name">ListView With Checkbox</string>
    <string name="list_of_fuits">List of Fruits</string>
    <string name="no_message_list_found">"Sorry, no fruits in list!!!"</string>
    <string name="fruit_name">"FruitName: "</string>
    <string name="item_click">"On Item Click FruitName: "</string>
    <string name="is_checked">" is Checked."</string>
    <string name="is_unchecked">" is Unchecked."</string>
 
</resources>

 
 

colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <color name="divider_color">#a6a6a6</color>
    <color name="list_title_text_color">#3F51B5</color>
    <color name="list_subtitle_text_color">#616161</color>
    <color name="title_bar_view_color">#3F51B5</color>
    <color name="white">#FFFFFF</color>
    <color name="green">#8BC34A</color>
 
</resources>

 
 

dimens.xml:

<resources>
 
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="title_bar_view_height">40dip</dimen>
    <dimen name="view_left_right_margin">10dip</dimen>
    <dimen name="view_left_right_padding">5dip</dimen>
    <dimen name="divider_height">0.5dip</dimen>
    <dimen name="profile_photo_width_height">50dip</dimen>
    <dimen name="relativelayout_margin">5dip</dimen>
    <dimen name="list_title_text_size">16sp</dimen>
    <dimen name="list_subtitle_text_size">14sp</dimen>
    <dimen name="title_text_size">16sp</dimen>
    <dimen name="label_text_size">14sp</dimen>
 
</resources>

 
 

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
 
    <style name="ListTitleTextStyle">
        <item name="android:textSize">@dimen/list_title_text_size</item>
        <item name="android:textColor">@color/list_title_text_color</item>
    </style>
 
    <style name="ListSubtitleTextStyle">
        <item name="android:textSize">@dimen/list_subtitle_text_size</item>
        <item name="android:textColor">@color/list_subtitle_text_color</item>
    </style>
 
     <style name="TitleTextStyle">
        <item name="android:textSize">@dimen/title_text_size</item>
        <item name="android:textColor">@color/white</item>
    </style>
 
     <style name="HeaderTitleTextStyle">
        <item name="android:textSize">@dimen/label_text_size</item>
        <item name="android:textColor">@color/green</item>
         <item name="android:textStyle">bold</item>
    </style>
 
</resources>

 
 

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vishalmobitech.listviewwithcheckbox"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="21" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_apple"
        android:label="@string/app_name" >
        <activity
            android:name="com.vishalmobitech.listviewwithcheckbox.HomeActivity"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>