11 Aug 2014

Checkbox Listview | custom listview with checkbox in android

Hello Friends,

This tutorial shows you how to add android check box in a list view. We will develop custom adapter to populate our android list view with check box and search record from list view.

Out Put :


Step 1: selector_checkbox.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_checkbox" android:state_selected="false"/>
    <item android:drawable="@drawable/ic_checkbox_active" android:state_selected="true"/>
    <item android:drawable="@drawable/ic_checkbox"/> <!-- default -->


</selector>

Step 2: Create main.xml :

<?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:background="@android:color/white"
    android:focusableInTouchMode="true"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/edtSearch"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="5dp"
            android:layout_weight="1"
            android:drawableLeft="@drawable/ic_search"
            android:drawablePadding="5dp"
            android:focusableInTouchMode="true"
            android:gravity="center_vertical"
            android:hint="Search"
            android:inputType="text"
            android:singleLine="true"
            android:textAppearance="?android:attr/textAppearanceSmall" />
    </LinearLayout>

    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent"
        android:paddingTop="5dp" />

    <Button
        android:id="@+id/btnDone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Done" />

</LinearLayout>

Step 3: Create row_item.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical" >

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:orientation="vertical"
        android:padding="10dp" >

        <TextView
            android:id="@+id/txtItemName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:text="@string/app_name"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="@android:color/black" />
    </LinearLayout>

    <ImageView
        android:id="@+id/imgvCheck"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:contentDescription="@string/app_name"
        android:paddingRight="10dp"
        android:src="@drawable/selector_checkbox" />

</LinearLayout>

Step 4: Create class  ItemBean.java: 

public class ItemBean
{     
       public String ItemName;
       public boolean isSelected ;

       public String getItemName()
       {
              return ItemName;
       }
       public void setItemName(String displayName)
       {
              this.ItemName = displayName;
       }
       public boolean isSelected()
       {
              return isSelected;
       }
       public void setSelected(boolean isSelected)
       {
              this.isSelected = isSelected;
       }
}

Step 5: Create ItemAdapter.java :

import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ItemAdapter extends BaseAdapter
{
       private Context mContext;
       private LayoutInflater inflater;
       public List<ItemBean> arraylistData = null;
       private ArrayList<ItemBean> arraylist;

       public ItemAdapter(Context context, List<ItemBean> listbean)
       {
              mContext = context;
              this.arraylistData = listbean;
              inflater = LayoutInflater.from(mContext);

              this.arraylist = new ArrayList<ItemBean>();
              this.arraylist.addAll(listbean);

       }

       public class ViewHolder
       {
              TextView txtItemName;
              ImageView imgvCheck;
       }

       @Override
       public int getCount()
       {
              return arraylistData.size();
       }

       @Override
       public ItemBean getItem(int position)
       {
              return arraylistData.get(position);
       }

       @Override
       public long getItemId(int position)
       {
              return position;
       }     

       public View getView(final int position, View view, ViewGroup parent)
       {
              final ViewHolder holder;
              if (view == null)
              {
                     holder = new ViewHolder();
                     view = inflater.inflate(R.layout.row_item, null);
                     holder.txtItemName = (TextView) view.findViewById(R.id.txtItemName);
                     holder.imgvCheck = (ImageView) view.findViewById(R.id.imgvCheck);
                     view.setTag(holder);

              }
              else
              {
                     holder = (ViewHolder) view.getTag();
              }

              // Set data to view=================================================
              try
              {
                     ItemBean bean = arraylistData.get(position);

                     if (bean.isSelected)
                           holder.imgvCheck.setSelected(true);
                     else
                           holder.imgvCheck.setSelected(false);


                     holder.txtItemName.setText(bean.getItemName());


                     view.setOnClickListener(new View.OnClickListener()
                     {
                           public void onClick(View v)
                           {
                                  for (int i = 0; i < arraylistData.size(); i++)
                                  {
                                         ItemBean bean = arraylistData.get(position);
                                         if (i == position)
                                         {            
                                                if(bean.isSelected())
                                                {
                                                       bean.setSelected(false);
                                                }
                                                else
                                                {                                                     
                                                       bean.setSelected(true);
                                                }

                                         }                                       
                                         notifyDataSetChanged();
                                  }
                           }
                     });
                     holder.imgvCheck.setTag(bean);
              }
              catch (Exception e)
              {
                     e.printStackTrace();
              }

              return view;
       }

       // Filter Class
       public void filter(String charText)
       {
              charText = charText.toLowerCase();
              arraylistData.clear();
              if (charText.length() == 0)
              {
                     arraylistData.addAll(arraylist);
              }
              else
              {
                     for (ItemBean contact : arraylist)
                     {
                           if (contact.getItemName().toLowerCase().contains(charText))
                           {
                                  arraylistData.add(contact);
                           }
                     }
              }
              notifyDataSetChanged();
       }

}

Step 6: MainActivity.java :

import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener
{
       private ListView listview;
       private ItemAdapter adapter;
       private EditText editsearch;
       private ArrayList<ItemBean> arrlistItems = new ArrayList<ItemBean>();
       int selectionCount=0;
       private Button btnDone;

       @Override
       protected void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.layout_main);

              initializeViews();

              //Add data in arraylist
              for (int i = 0; i < 10; i++)
              {
                     ItemBean bean=new ItemBean();
                     bean.setItemName("Item " + (i));

                     arrlistItems.add(bean);
              }

              adapter = new ItemAdapter(MainActivity.this, arrlistItems);
              listview.setAdapter(adapter);
       }


       // views=========================================
       void initializeViews()
       {
              listview = (ListView) findViewById(R.id.listview);
              editsearch = (EditText) findViewById(R.id.edtSearch);
              btnDone=(Button) findViewById(R.id.btnDone);

              btnDone.setOnClickListener(this);

              // Search contact like text enter in edit text.
              editsearch.addTextChangedListener(new TextWatcher()
              {
                     @Override
                     public void afterTextChanged(Editable arg0)
                     {
                           String text = editsearch.getText().toString().toLowerCase();
                           adapter.filter(text);
                     }

                     @Override
                     public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
                     {
                     }

                     @Override
                     public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
                     {
                     }
              });
       }


       @Override
       public void onClick(View v)
       {
              switch (v.getId())
              {
              case R.id.btnDone:

                     ArrayList<ItemBean> arrayList=new ArrayList<ItemBean>();

                     ArrayList<ItemBean> arraydata = (ArrayList<ItemBean>) adapter.arraylistData;

                     for (int i = 0; i < arraydata.size(); i++)
                     {
                           ItemBean bean = arraydata.get(i);

                           if (bean.isSelected)
                           {
                                  arrayList.add(arraydata.get(i));
                           }
                     }                         
                     Toast.makeText(MainActivity.this, "Selected count = "+arrayList.size(), Toast.LENGTH_SHORT).show();

                     break;

              default:
                     break;
              }
       }
}


I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)