Kotlin RecyclerView Checkbox Example Tutorial Get Selected Value

kotlin sqlite multiple tables, kotlin recyclerview checkbox, kotlin recyclerview button, kotlin load html javascript, kotlin recyclerview searchview, kotlin recyclerview search using edittext, kotlin listview with edittext, kotlin recyclerview with edittext, kotlin swipe to delete listview, kotlin recyclerview swipe to delete, kotlin expandablelistview with checkbox, kotlin custom ratingbar, kotlin change tab, Kotlin Select Multiple Images From Gallery, Kotlin Custom Dialog With Image And Title, kotlin select multiple video

Kotlin RecyclerView Checkbox Example Tutorial is here for information.

In this example, you will learn how to implement checkbox in the each row of the recycler view.

You will learn,

  • How to save state in recycler view
  • Get selected checkbox value from recycler view
  • Select all checkbox in single click

This kotlin recyclerview checkbox tutorial will solve your problem like “checkbox in recyclerview keeps on checking different items”

Now, see the following video for further output reference.

 

Step 1. Separate New Project

In your android studio, make a new project with empty activity as the default one.

Also, do not forget to set Kotlin as the primary source language for your android app.

Step 2. Gradle Tasks

Open up your build.gradle(Module : app) file. You need to add below two lines in this file.

 implementation 'com.android.support:recyclerview-v7:28.0.0'
 implementation 'com.android.support:cardview-v7:28.0.0'

First line will add the classes which will allow us to create recycler view in our app.

Second line will help us to make cards in the each recycler view row item.

Step 3. Separate File For Card View

We need to make one XML drawable file which will allow us to design the card view.

So, in your app->res->drawable directory, make a new XML file.

You should set the name of the file as cardview.xml and add the below codes in 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 create some gradient color effects to the card view.

It will create circular corners with “4 dp” radius. You can change the colors , effects and size of the radius as per your choice.

Step 4. Model and XML For Recycler Child

Inside app->res->layout directory, create a new XML file and set it’s name as rv_item.xml

You need to write the below coding lines in this rv_item.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="wrap_content"
    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>

This file will help us to create view of every child of the recycler view.

Compiler will use this file and it’s components to make the look and feel of the recycler view items.

We have added checkbox in this layout file.

Let us make a model class which will help us to maintain data inside recycler view.

Make a new file called ReModel.kt and add the below code in it

class ReModel {

    var isSelected: Boolean = false
    var animal: String? = null

    fun getAnimals(): String {
        return animal.toString()
    }

    fun setAnimals(animal: String) {
        this.animal = animal
    }

    fun getSelecteds(): Boolean {
        return isSelected
    }

    fun setSelecteds(selected: Boolean) {
        isSelected = selected
    }

}

This file have one boolean variable and one string variable. It also has getter and setter methods for both of these variables.

Compiler will use these methods to bind data to the recycler view rows in the adapter class.

Now let us create this adapter class.

Step 5. Making An Adapter

Create a new Kotlin class and give it a name like ReAdapter.kt

ReAdapter.kt file should have the below source code snippet

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.
 */
class ReAdapter(private val ctx: Context, imageModelArrayListMain: ArrayList<ReModel>) :
    RecyclerView.Adapter<ReAdapter.MyViewHolder>() {

    companion object {
         lateinit var imageModelArrayList: ArrayList<ReModel>
    }

    private val inflater: LayoutInflater
   // var imageModelArrayList: ArrayList<ReModel>

    init {

        inflater = LayoutInflater.from(ctx)
        imageModelArrayList = imageModelArrayListMain
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ReAdapter.MyViewHolder {

        val view = inflater.inflate(R.layout.rv_item, parent, false)

        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: ReAdapter.MyViewHolder, position: Int) {

        holder.checkBox.text = "Checkbox $position"
        holder.checkBox.isChecked = imageModelArrayList[position].getSelecteds()
        holder.tvAnimal.setText(imageModelArrayList[position].getAnimals())

        // holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.tag = position
        holder.checkBox.setOnClickListener {
            val pos = holder.checkBox.tag as Int
            Toast.makeText(ctx, imageModelArrayList[pos].getAnimals() + " clicked!", Toast.LENGTH_SHORT).show()

            if (imageModelArrayList[pos].getSelecteds()) {
                imageModelArrayList[pos].setSelecteds(false)
            } else {
                imageModelArrayList[pos].setSelecteds(true)
            }
        }


    }

    override fun getItemCount(): Int {
        return imageModelArrayList.size
    }

    inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

         var checkBox: CheckBox
         val tvAnimal: TextView

        init {

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

    }

}

Adapter will give the data to the each row of the recycler view.

See the onCreateViewHolder() method. Compiler will simply inflating the rv_item.xml file.

Look at the onBindViewHolder() method. Here, compiler is accessing the components of the rv_item.xml file.

It will set the text of checkbox and text view in this method. On click event for checkbox is also written here.

When the user clicks the checkbox, compiler will check whether the checkbox is checked or not. If it is checked then it will uncheck it otherwise it will check it.

Step 6. Displaying Checked Items

Let us make a new activity and set it’s name like Next Activity.

You need to add the following source code in activity_next.xml

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

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

</RelativeLayout>

This file contains only one text view. We will print the checked animal names in this text view.

Now in your NextActivity.kt file, you should write the below source lines.

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

class NextActivity : AppCompatActivity() {

    private var tv: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_next)

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

        for (i in 0 until ReAdapter.imageModelArrayList.size) {
            if (ReAdapter.imageModelArrayList.get(i).getSelecteds()) {
                tv!!.text = tv!!.text.toString() + " " + ReAdapter.imageModelArrayList.get(i).getAnimals()
            }
        }
    }
}

In this file, we will access the imageModelArrayList from the ReAdapter class.

This imageModelArrayList will help us to fetch the checked items. For this, compiler will use one for loop.

During the each iteration, compiler will check if the item is checked or not. If yes, then it will print the animal name in the text view otherwise simply it will ignore it.

Step 7. Last Tasks

Our final work is to write the Main Activity. So, add the below code 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>

This file have one recycler view and three buttons at the bottom side.

Now following is the full source code lines for MainActivity.kt

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.widget.Button
import java.util.ArrayList

class MainActivity : AppCompatActivity() {

    private var recyclerView: RecyclerView? = null
    private var modelArrayList: ArrayList<ReModel>? = null
    private var customAdapter: ReAdapter? = null
    private var btnselect: Button? = null
    private var btndeselect: Button? = null
    private var btnnext: Button? = null
    private val animallist = arrayOf("Lion", "Tiger", "Leopard", "Cat", "Balu" , "wolf", "monkey", "Elephant" ,"Panda", "Rabbit","Giraffe")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView = findViewById(R.id.recycler) as RecyclerView
        btnselect = findViewById(R.id.select) as Button
        btndeselect = findViewById(R.id.deselect) as Button
        btnnext = findViewById(R.id.next) as Button

        modelArrayList = getModel(false)
        customAdapter = ReAdapter(this, modelArrayList!!)
        recyclerView!!.adapter = customAdapter
        recyclerView!!.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)

        btnselect!!.setOnClickListener {
            modelArrayList = getModel(true)
            customAdapter = ReAdapter(this@MainActivity, modelArrayList!!)
            recyclerView!!.adapter = customAdapter
        }
        btndeselect!!.setOnClickListener {
            modelArrayList = getModel(false)
            customAdapter = ReAdapter(this@MainActivity, modelArrayList!!)
            recyclerView!!.adapter = customAdapter
        }
        btnnext!!.setOnClickListener {
            val intent = Intent(this@MainActivity, NextActivity::class.java)
            startActivity(intent)
        }

    }

    private fun getModel(isSelect: Boolean): ArrayList<ReModel> {
        val list = ArrayList<ReModel>()
        for (i in 0..10) {

            val model = ReModel()
            model.setSelecteds(isSelect)
            model.setAnimals(animallist[i])
            list.add(model)
        }
        return list
    }
}

Focus on above

First of all, see the below

 private var recyclerView: RecyclerView? = null
    private var modelArrayList: ArrayList<ReModel>? = null
    private var customAdapter: ReAdapter? = null
    private var btnselect: Button? = null
    private var btndeselect: Button? = null
    private var btnnext: Button? = null
    private val animallist = arrayOf("Lion", "Tiger", "Leopard", "Cat", "Balu" , "wolf", "monkey", "Elephant" ,"Panda", "Rabbit","Giraffe")

Compiler will first create the object of recycler view, button, ReAdapter etc. It will also create the arraylist (modelArrayList) with the objects of ReModel class.

An array animallist contains the names of the variable.

Now focus on the below

 modelArrayList = getModel(false)
        customAdapter = ReAdapter(this, modelArrayList!!)
        recyclerView!!.adapter = customAdapter
        recyclerView!!.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false)

Compiler will initialize the object of adapter class and then it will bind to the recycler view.

In the first line, compiler is filling the modelArrayList using the getModel() method.

Below is the code for getModel() method.

  private fun getModel(isSelect: Boolean): ArrayList<ReModel> {
        val list = ArrayList<ReModel>()
        for (i in 0..10) {

            val model = ReModel()
            model.setSelecteds(isSelect)
            model.setAnimals(animallist[i])
            list.add(model)
        }
        return list
    }

This method will get one boolean value (true or false) in the parameter. It will create one for loop.

It will create the object of the ReModel and will set the name of the animal the checkbox state (true or false) in the each iteration of for loop.

It will set the checkbox status as per the boolean value from the parameter.

Now see the below

  btnselect!!.setOnClickListener {
            modelArrayList = getModel(true)
            customAdapter = ReAdapter(this@MainActivity, modelArrayList!!)
            recyclerView!!.adapter = customAdapter
        }

When the user clicks the Select All button, compiler will call the above method. It will call the getModel() method with boolean value as true in the parameter.

Then it will simply update the adapter and recycler view.

Compiler will execute the below code when the user clicks the  DeSelect All button

   btndeselect!!.setOnClickListener {
            modelArrayList = getModel(false)
            customAdapter = ReAdapter(this@MainActivity, modelArrayList!!)
            recyclerView!!.adapter = customAdapter
        }

It will also do same thing as done on the click of Select All button but just one change. In the parameter of getModel() method, boolean value will be false.

Focus on below now

  btnnext!!.setOnClickListener {
            val intent = Intent(this@MainActivity, NextActivity::class.java)
            startActivity(intent)
        }

When the user click the Next Activity button, compiler will simply open the NextActivity.

Download Code For RecyclerView Checkbox Kotlin

Hit me to go to github to download code