RecyclerView Checkbox Android Example Get Checked Item Position

RecyclerView Checkbox

Warm welcome to RecyclerView Checkbox Android Studio example.

In this RecyclerView Checkbox Android example, we will cover single selection, multiple selection and also select all scenario.

There is a common problem like “checkbox unchecked when I scroll recyclerview.” We will solve this problem in this  RecyclerView Checkbox Android tutorial.

We will also send selected or checked items to next activity.

You can learn how to use onItemClickListener, onClickListener, onItemTouchListener etc. for recyclerview.

Kotlin Course

Follow below course for quick android development.

Android development course for beginners.

If you have not implement basic recyclerview with custom adapter yet, check recyclerview android example first.

Also checkout,

Now checkout the output of RecyclerView Checkbox Android example, then we will develop it.

Step 1: Create a new project in Android Studio.

Prepare a new project in android studio with empty activity as a default activity of your project.

Step 2: Updating build.gradle(Module:app) file

Add below source code into dependencies{}

compile 'com.android.support:recyclerview-v7:23.4.0'
compile 'com.android.support:cardview-v7:23.3.+'

Step 3: Coding cardview.xml

Create a new file into drawable folder and name it cardview.xml

Add below source code into it.

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

    <item android:state_focused="true">
        <shape android:shape="rectangle">
            <padding
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
                />
            <gradient android:startColor="#1c88b7" android:endColor="#2972ba" android:angle="270" />

            <corners android:topLeftRadius="4dp" android:topRightRadius="4dp"/>
        </shape>
    </item>

    <item android:state_focused="false"
        >
        <shape android:shape="rectangle">
            <padding
                android:left="4dp"
                android:top="4dp"
                android:right="4dp"
                android:bottom="4dp"
                />

            <gradient android:startColor="#b71c83" android:endColor="#29ba41" android:angle="270" />

            <corners android:topLeftRadius="4dp" android:topRightRadius="4dp" />
        </shape>
    </item>

</selector>
  • This file is used to create gradient effect with two different colors.
  • With help of this file, we will add some attractive design to our cardviews.
  • It will add this effect at the upper side of every card. You show this design in the above output video as well.

Step 4: Making rv_item.xml

Create a new layout resource file named rv_item.xml

Copy following source code into it

<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="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="0dp"
        card_view:cardCornerRadius="4dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/tv"
                android:height="40dp"
                android:background="@drawable/cardview"
                android:gravity="center_vertical"
                android:paddingLeft="10dp"
                android:text="Awesome design"
                android:textColor="#fff"
                android:textStyle="bold"
                android:textSize="18sp" />

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

                <CheckBox
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    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:layout_marginTop="5dp"
                    android:text="animal"/>

            </LinearLayout>



        </LinearLayout>

    </android.support.v7.widget.CardView>
</RelativeLayout>
  • Above file is the common layout for each row of the recyclerview.
  • Adapter will create a view for every row item using this file.
  • I have taken one textview first. Here I have used it’s background design as a file named cardview.xml that we created in the previous step.
  • Now after that, I have taken one checkbox and one textview side by side (with horizontal orientation in LinearLayout)
  • textview represents the name of the animal.

Step 5: Making Model class

Create a new JAVA class named Model.java and paste below

/**
 * 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;
    }
}

Step 6: Adding integer.xml

Create a new file named integer.xml  in values directory and add below

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="btnplusview">1</integer>
    <integer name="btnpluspos">2</integer>
</resources>

Step 7: Code for CustomAdapter.java

Let’s create Custom Adapter for RecyclerView.

Make a new JAVA class named CustomAdapter.java and add below

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Created by Parsania Hardik on 29-Jun-17.
 */
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    public static ArrayList<Model> imageModelArrayList;
    private Context ctx;

    public CustomAdapter(Context ctx, ArrayList<Model> imageModelArrayList) {

        inflater = LayoutInflater.from(ctx);
        this.imageModelArrayList = imageModelArrayList;
        this.ctx = ctx;
    }

    @Override
    public CustomAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.rv_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(final CustomAdapter.MyViewHolder holder, int position) {

        holder.checkBox.setText("Checkbox " + position);
        holder.checkBox.setChecked(imageModelArrayList.get(position).getSelected());
        holder.tvAnimal.setText(imageModelArrayList.get(position).getAnimal());

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

                Integer pos = (Integer) holder.checkBox.getTag();
                Toast.makeText(ctx, imageModelArrayList.get(pos).getAnimal() + " clicked!", Toast.LENGTH_SHORT).show();

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


    }

    @Override
    public int getItemCount() {
        return imageModelArrayList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;

        public MyViewHolder(View itemView) {
            super(itemView);

            checkBox = (CheckBox) itemView.findViewById(R.id.cb);
            tvAnimal = (TextView) itemView.findViewById(R.id.animal);
        }

    }
}

Describing CustomAdapter

holder.checkBox.setTag(position);
  • Above code will set a tag for position.

Now look at below source code

 holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Integer pos = (Integer) holder.checkBox.getTag();
                Toast.makeText(ctx, imageModelArrayList.get(pos).getAnimal() + " clicked!", Toast.LENGTH_SHORT).show();

                if (imageModelArrayList.get(pos).getSelected()) {
                    imageModelArrayList.get(pos).setSelected(false);
                } else {
                    imageModelArrayList.get(pos).setSelected(true);
                }
            }
        });
  • We will get position (which we set above using setTag() method) in onClick method.

Step 8: Making NextActivity

Create a new activity named “NextActivity

Add below source code into NextActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.imageModelArrayList.size(); i++){
            if(CustomAdapter.imageModelArrayList.get(i).getSelected()) {
                tv.setText(tv.getText() + " " + CustomAdapter.imageModelArrayList.get(i).getAnimal());
            }
        }
    }
}

Copy following code into 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.exampledemo.parsaniahardik.myapplication.NextActivity">

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

</RelativeLayout>

Step 9: Finally Update activity_main.xml and MainActivity.java

Updating activity_main.xml

Add following into activity_main.xml

<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=".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:layout_marginTop="15dp"/>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:background="@drawable/cardview"
            android:textColor="#fff"
            android:layout_weight="1"
            android:id="@+id/select"
            android:text="Select all"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_marginLeft="5dp"
            android:background="@drawable/cardview"
            android:textColor="#fff"
            android:layout_weight="1"
            android:id="@+id/deselect"
            android:text="Deselct all"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_weight="1"
            android:layout_marginLeft="5dp"
            android:background="@drawable/cardview"
            android:textColor="#fff"
            android:id="@+id/next"
            android:visibility="visible"
            android:text="Next activity"/>


    </LinearLayout>

</LinearLayout>

Updating MainActivity.java

Copy folowing into MainActivity.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerView;
    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);

        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        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);
        recyclerView.setAdapter(customAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

        btnselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(true);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                recyclerView.setAdapter(customAdapter);
            }
        });
        btndeselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(false);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                recyclerView.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;
    }
}

Explaining Above

Look at the below line

private  String[] animallist = new String[]{"Lion", "Tiger", "Leopard", "Cat"};
  • Compiler will create a string array named animallist. It includes the names of the animals.

Consider the below code snippet

 modelArrayList = getModel(false);
  • This line is preparing a arraylist to generate data.
  • Compiler is using getModel() method to have useful data.

Following is the code structure for getModel() 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;
    }
  • Compiler will run a for loop with four iterations.
  • In every iteration, compiler will create one object of the Model class.
  • Then it will set the name of the animal using string array (animallist). It will set the value of checkbox using isSelect boolean variable which is coming from the parameter.

Select All

We have taken a select all button in the activity_main.xml file.

Compiler will run the following code when the user clicks this button.

  btnselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(true);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                recyclerView.setAdapter(customAdapter);
            }
        });
  • On the click of the button, compiler will generate new model arraylist with the help of getModel() method.
  • Here a parameter of getModel() method is set as a true. So data set will check all the checkboxes of the recyclerview rows.

Deselect All

  • I have taken a deselect all button in the activity_main.xml file.
  • System will execute the below code when user clicks this button.
  btndeselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                modelArrayList = getModel(false);
                customAdapter = new CustomAdapter(MainActivity.this,modelArrayList);
                recyclerView.setAdapter(customAdapter);
            }
        });
  • Here, system will run the getModel() method with the parameter value as a false.
  • So all the checkboxes are deselected.

This was all for RecyclerView Checkbox Android tutorial. Thank you.

Download Source Code for RecyclerView Checkbox Android example

[sociallocker]Download RecyclerView_checkbox [/sociallocker]