Listview With Checkbox In Android Studio Example

listview with checkbox in android

In Listview with Checkbox in Android Studio example,learn how to make custom Listview with a checkbox.

You will have to create a listview with checkbox in Android Studio when you want to show certain options to the user and wants to take more than one options to be selected.

There is a common problem like “checkbox unchecked when I scroll listview.”

We will solve this problem in this listview with checkbox in Android Studio.

We will use listview’s onitemclicklistener() and checkbox’s OnClickListener() method to get checked items.

In this example, we will get single selection, multiple selection and also select all scenario.

Check out the output of Listview with Checkbox in Android Studio tutorial below which is prepared by Demonuts.com:

If you have not any basic idea about listview and custom adapter, then it is better to learn about them first and then you will find this tutorial easy to understand. Follow this example first about basic listview.

Step 1.  Create a new project in the Android Studio.

Choose empty as your Main Activity.

Step 2. Create a class named Model.java

copy the following source code in it:

/**
 * Created by hardik on 9/1/17.
 */
public class Model {

    private boolean isSelected;
    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

This class represents the various methods to set and get the data in the adapter class.

Objects of this class will be used to maintain the proper data structure.

Step 3. Creating lv_item.xml layout file

Create a new layout resource file named lv_item.xml file and add following

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

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cb"
        android:text="Checkbox"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/animal"
        android:layout_marginLeft="20dp"
        android:textSize="20sp"
        android:text="animal"/>

</LinearLayout>

This file will create the layout for all the rows of the listview. Adapter class will use this file.

It contains one checkbox and one textview.

Step 4. Updating activity_main.xml

Copy and Paste following source code in activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.example.zerones_hardik.listview_with_checkbox_demonuts.MainActivity">

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

    </ListView>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/select"
            android:text="Select all"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/deselect"
            android:text="Deselct all"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/next"
            android:text="Next activity"/>


    </LinearLayout>

</LinearLayout>

I have taken one listview and three buttons in main layout.

Step 5. Create one class and name it: CustomAdapter.java

Copy and paste following code in this class:

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by hardik on 9/1/17.
 */
public class CustomAdapter  extends BaseAdapter {

    private Context context;
    public static ArrayList<Model> modelArrayList;


    public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {

        this.context = context;
        this.modelArrayList = modelArrayList;

    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

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

    @Override
    public Object getItem(int position) {
        return modelArrayList.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
            holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }


        holder.checkBox.setText("Checkbox "+position);
        holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());

        holder.checkBox.setChecked(modelArrayList.get(position).getSelected());

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

        return convertView;
    }

    private class ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;

    }

}

We are getting one arraylist of the objects of the Model class in the constructor.

We are using this arraylist in the below method.

Now check following code snippet:

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

Check first two lines of above snippet. Two tags are set to checkbox

  • One for getting position (checkbox.setTag())
  • And other for getting whole row view in which checkbox is present. (checkbox.getTag())

To set the Tag of view, we need to assign key which is R.integer.btnplusview here.

  • When we are getting this view using getTag, we used the same key to get the whole view as shown in the checkbox.OnClickListener().
  • Now you might say what is R.integer.btnplusview??
  • It is nothing but same as you define your string resources in the string.xml, you can define your integer resources in an integer.xml file.
  • When you create a project in the android studio, string.xml is generated automatically, while you have to manually create integer.xml , that’s it, nothing special.

Create integer.xml under res/values directory(same directory in which string.xml is present) and copy following code:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<integer name="btnplusview">1</integer>
<integer name="btnpluspos">2</integer>

</resources>
  • The Logic for updating value of each model item is written on OnClickListener() of  the checkbox.
  • We have used setTag and getTag to get which checkbox is clicked(position of clicked checkbox), and we can also get the whole view of row item which is clicked, and it is taken as tempview in above code.
  • Using tempview, you can inflate all views(TextView, EditText,ImageView etc.) of that particular row(row which is clicked).

TextView is inflated from tempview, and then we can get the value of this textview to use as per requirements.

Step 6. Copy and paste following code in MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ListView lv;
    private ArrayList<Model> modelArrayList;
    private CustomAdapter customAdapter;
    private Button btnselect, btndeselect, btnnext;
    private  String[] animallist = new String[]{"Lion", "Tiger", "Leopard", "Cat"};

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

        lv = (ListView) findViewById(R.id.lv);
        btnselect = (Button) findViewById(R.id.select);
        btndeselect = (Button) findViewById(R.id.deselect);
        btnnext = (Button) findViewById(R.id.next);

        modelArrayList = getModel(false);
        customAdapter = new CustomAdapter(this,modelArrayList);
        lv.setAdapter(customAdapter);

        btnselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(true);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                lv.setAdapter(customAdapter);
            }
        });
        btndeselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(false);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                lv.setAdapter(customAdapter);
            }
        });
        btnnext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,NextActivity.class);
                startActivity(intent);
            }
        });


    }

    private ArrayList<Model> getModel(boolean isSelect){
        ArrayList<Model> list = new ArrayList<>();
        for(int i = 0; i < 4; i++){

            Model model = new Model();
            model.setSelected(isSelect);
            model.setAnimal(animallist[i]);
            list.add(model);
        }
        return list;
    }

}

There are three buttons in the above code snippet.

Below is the onclick for first one

 btnselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(true);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                lv.setAdapter(customAdapter);
            }
        });

When the user clicks on this button, all the checkboxes in the listview are automatically selected or checked.

Next button will take the user to the Next Activity.

Consider below code

 btndeselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(false);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                lv.setAdapter(customAdapter);
            }
        });

When the user clicks the deselect button, all the checkboxes in the listview are deselected.

This select all and deselect all feature is very useful for user when he wants to do all the process from scratch.

Look at the below method

 private ArrayList<Model> getModel(boolean isSelect){
        ArrayList<Model> list = new ArrayList<>();
        for(int i = 0; i < 4; i++){

            Model model = new Model();
            model.setSelected(isSelect);
            model.setAnimal(animallist[i]);
            list.add(model);
        }
        return list;
    }

getModel() method will create an arraylist of the objects of the model class.

This arraylist is sent to the adapter class via constructor where it will work as the data provider.

Step 7. Create a new activity and name it NextActivity.

Now when clicking on Next button, a new activity opens with names of selected animals as shown in the output video.

So you will have two files: 1. NextActivity.java and 2. activity_next.xml

Copy and paste following code into NextActivity.java class:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class NextActivity extends AppCompatActivity {

    private TextView tv;

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

        tv = (TextView) findViewById(R.id.tv);

        for (int i = 0; i < CustomAdapter.modelArrayList.size(); i++){
            if(CustomAdapter.modelArrayList.get(i).getSelected()) {
                tv.setText(tv.getText() + " " + CustomAdapter.modelArrayList.get(i).getAnimal());
            }
        }
    }
}

for loop in the above code will check all the object one by one. It will print the animal name which are checked.

Copy following in activity_next.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
   tools:context="com.example.zerones_hardik.listview_with_checkbox_demonuts.NextActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:id="@+id/tv"/>

</RelativeLayout>

Observe all the code snippets for listview with checkbox example carefully and understand it throughout so that you can change all things as per your different requirements.

All for Listview with Checkbox in Android Studio. Cheers and happy coding!  

Download Source Code Listview with Checkbox in Android Studio

[sociallocker]Download Demo[/sociallocker]