Kotlin ListView CheckBox Android Tutorial Example Get Checked Item

kotlin recyclerview, kotlin listview checkbox, kotlin listview button

Kotlin Listview CheckBox Tutorial with Example is the matter here.

It is not easy to implement the listview with checkbox in it’s every row item especially in the kotlin language.

This tutorial will provide easy to learn and time saving source code.

This example includes the features like select all, deselect all, make multiple selection etc.

We will learn how to get click position on checkbox, get the names of checked items and send it to the next activity.

If you are not familiar with kotlin then visit java version here.

Read Other Kotlin Listview Tutorials

Refer the output of kotlin listview checkbox example in below video.

Step 1. Model Class

Create a new project in the android studio with kotlin support.

Select the default activity as empty activity in your last step.

Now, make a new kotlin class. Give this class a sweet name like Model.kt

Source code for the model class is

class Model {

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

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

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

    fun getSelecteds(): Boolean {
        return isSelected
    }

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

}

Step 3. Listview Layout File

We need to create a layout resource file which will represent the every row’s layout.

Create new layout resource file named lv_item.xml and add below code

<?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>

Step 4. Adding Custom Adapter

Before making adapter, create a new xml file named integer.xml in res/values directory(same directory in which string.xml is there)

Now add following code into integer.xml

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

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

</resources>

Prepare a new class CustomAdapter.kt

Copy and paste below source code into it

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.
 */
class CustomAdapter(private val context: Context, modelArrayList: ArrayList<Model>) : BaseAdapter() {

    private var modelArrayList: ArrayList<Model>

    init {
        this.modelArrayList = modelArrayList
    }

    override fun getViewTypeCount(): Int {
        return count
    }

    override fun getItemViewType(position: Int): Int {

        return position
    }

    override fun getCount(): Int {
        return modelArrayList.size
    }

    override fun getItem(position: Int): Any {
        return modelArrayList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        val holder: ViewHolder

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

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

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

        holder.checkBox!!.text = "Checkbox $position"
        holder.tvAnimal!!.setText(modelArrayList[position].getAnimals())

        holder.checkBox!!.isChecked = modelArrayList[position].getSelecteds()

        holder.checkBox!!.setTag(R.integer.btnplusview, convertView)
        holder.checkBox!!.tag = position
        holder.checkBox!!.setOnClickListener {
            val tempview = holder.checkBox!!.getTag(R.integer.btnplusview) as View
            val tv = tempview.findViewById(R.id.animal) as TextView
            val pos = holder.checkBox!!.tag as Int
            Toast.makeText(context, "Checkbox $pos clicked!", Toast.LENGTH_SHORT).show()

            if (modelArrayList[pos].getSelecteds()) {
                modelArrayList[pos].setSelecteds(false)
                public_modelArrayList = modelArrayList
            } else {
                modelArrayList[pos].setSelecteds(true)
                public_modelArrayList = modelArrayList
            }
        }

        return convertView
    }

    private inner class ViewHolder {

        var checkBox: CheckBox? = null
        var tvAnimal: TextView? = null

    }

    companion object {
        lateinit var public_modelArrayList: ArrayList<Model>
    }

}

setTag() and getTag() methods are used to take care of each checkboxes in listview.

Description of setTag() method

this method is used to set a key and value pair to each view of the listview.

Look at the below lines from the Adapter class

holder.checkBox!!.setTag(R.integer.btnplusview, convertView)
holder.checkBox!!.tag = position

In the first line, converView is set as a value and R.integer.btnplusview is set as a key.

Second line says that the current position is set as a tag.

One important point is that we have make one public arraylist named public_modelArrayList

This arraylist is the list of the objects of the Model class.

Following line declares this public arraylist.

companion object {
        lateinit var public_modelArrayList: ArrayList<Model>
}

This public arraylist is updated when the checkbox is clicked everytime.

Step 5. Making Next Activity

Let us create a next activity in which, we will send the selected checkbox’s values.

Create a new activity named NextActivity.

Add below code into NextActivity.kt class

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
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 CustomAdapter.public_modelArrayList!!.size) {
            if (CustomAdapter.public_modelArrayList!!.get(i).getSelecteds()) {
                tv!!.text = tv!!.text.toString() + " " + CustomAdapter.public_modelArrayList!!.get(i).getAnimals()
            }
        }
    }
}

We are printing the selected checkbox’s values in TextView.

Source code for activity_next.xml is as follows

<?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">

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

</RelativeLayout>

Step 6. Update Main Activity

Make your MainActivity.kt class looks like below

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

class MainActivity : AppCompatActivity() {

    private var lv: ListView? = null
    private var modelArrayList: ArrayList<Model>? = null
    private var customAdapter: CustomAdapter? = null
    private var btnselect: Button? = null
    private var btndeselect: Button? = null
    private var btnnext: Button? = null
    private val animallist = arrayOf("Lion", "Tiger", "Leopard", "Cat")

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

        lv = findViewById(R.id.lv) as ListView
        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 = CustomAdapter(this, modelArrayList!!)
        lv!!.adapter = customAdapter

        btnselect!!.setOnClickListener {
            modelArrayList = getModel(true)
            customAdapter = CustomAdapter(this@MainActivity, modelArrayList!!)
            CustomAdapter.public_modelArrayList = modelArrayList as ArrayList<Model>
            lv!!.adapter = customAdapter
        }
        btndeselect!!.setOnClickListener {
            modelArrayList = getModel(false)
            customAdapter = CustomAdapter(this@MainActivity, modelArrayList!!)
            CustomAdapter.public_modelArrayList = modelArrayList as ArrayList<Model>
            lv!!.adapter = customAdapter
        }
        btnnext!!.setOnClickListener {
            val intent = Intent(this@MainActivity, NextActivity::class.java)
            startActivity(intent)
        }
    }

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

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

}

Logic for select all and deselect all features are written in the above class.

Write below code into 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.parsaniahardik.kotlin_listview_checkbox.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="50dp"
        android:orientation="horizontal">

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:id="@+id/select"
            android:text="Select all"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="50dp"
            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:id="@+id/next"
            android:visibility="visible"
            android:text="Next activity"/>


    </LinearLayout>


</LinearLayout>

This was all the details about making a listview with checkbox in android with kotlin language.

Comment out your queries, we will answer you as soon as possible.

Do not forget to Share this resource in your social network.

Download source code for kotlin listview checkbox example

[sociallocker]Download Kotlin_ListView_CheckBox[/sociallocker]