How to get all checked items in listView using Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to get all checked items in listView using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/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"
   android:padding="16dp"
   tools:context="MainActivity">
   <ListView
      android:id="@+id/listView"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:layout_weight="1">
   </ListView>
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="50dp"
      android:orientation="horizontal">
   <Button
      android:id="@+id/select"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_gravity="center"
      android:layout_weight="1"
      android:text="Select all" />
   <Button
      android:id="@+id/deSelect"
      android:layout_width="match_parent"
      android:layout_height="50dp"
      android:layout_weight="1"
      android:text="Deselect all" />
   <Button
      android:id="@+id/viewSelected"
      android:layout_width="match_parent"
      android:layout_height="50dp"
      android:layout_weight="1"
      android:text="Next activity"
      android:visibility="visible" />
   </LinearLayout>
</LinearLayout>

Step 3 − Create a java class (CustomAdapter.kt) and the following code

package app.com.myapplication
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
class CustomAdapter(private val context: Context, private var modelArrayList: ArrayList<Model>) :
BaseAdapter() {
   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: View? = convertView
      val holder: ViewHolder
      if (convertView == null) {
         holder = ViewHolder()
         val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 
            as LayoutInflater convertView = inflater.inflate(R.layout.listitem, null, true)
         holder.checkBox = convertView!!.findViewById(R.id.checkBox) as CheckBox holder.tvPlayer = convertView.findViewById(R.id.playerNameList) 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.tvPlayer!!.text = modelArrayList[position].getPlayer()
      holder.checkBox!!.isChecked = modelArrayList[position].getSelected()
      holder.checkBox!!.setTag(R.integer.btnPlusPos, convertView)
      holder.checkBox!!.tag = position
      holder.checkBox!!.setOnClickListener {
         val pos = holder.checkBox!!.tag as Int
         Toast.makeText(
            context, "Checkbox " + pos + "Clicked!",
            Toast.LENGTH_SHORT
         ).show()
         if (modelArrayList[pos].getSelected()) {
            modelArrayList[pos].setSelected(false)
         }
         else {
            modelArrayList[pos].setSelected(true)
         }
      }
   return convertView
}
private inner class ViewHolder {
   var checkBox: CheckBox? = null
   var tvPlayer: TextView? = null
}

Step 4 − Create a java class (Model.kt) and the following code

package app.com.myapplication
class Model {
   private var isSelected = false
   private var player: String? = null
   fun getPlayer(): String? {
      return player
   }
   fun setPlayer(player: String?) {
      this.player = player
   }
   fun getSelected(): Boolean {
      return isSelected
   }
   fun setSelected(selected: Boolean) {
      isSelected = selected
   }
}

Step 5 − Add the following code in res/values/strings.xml

<integer name="btnPlusView">1</integer>
<integer name="btnPlusPos">2</integer>

Step 6 − Create a layout for you listView (listItem.xml) and add the following code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal">
   <CheckBox
      android:id="@+id/checkBox"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/playerNameList"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="20dp"
      android:textSize="20sp" />
</LinearLayout>

Step 7 &minusl Add the following code to src/MainActivity.kt

package app.com.myapplication
import android.os.Bundle
import android.widget.Button
import android.widget.ListView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   private var listView: ListView? = null
   private var modelArrayList: ArrayList<Model>? = null
   private var customAdapter: CustomAdapter? = null
   lateinit var btnSelect: Button
   lateinit var btnDeSelect: Button
   val playerList = arrayOf(
      "Sunil Chetri - INDIA",
      "Cristiano Ronaldo - Portugal",
      "Lionel Messi - Argentina",
      "Neymar Jr - Brazil",
      "Eden Hazard - Belgium",
      "Gigi Buffon - Italy",
      "James Rodrigues - Columbia",
      "Sadio Mane - Senegal",
      "Toni Kroos - Germany"
   )
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      listView = findViewById(R.id.listView)
      btnSelect = findViewById(R.id.select)
      btnDeSelect = findViewById(R.id.deSelect)
      modelArrayList = getModel(false)
      customAdapter = CustomAdapter(this, modelArrayList!!)
      listView!!.adapter = customAdapter
      btnSelect.setOnClickListener {
         modelArrayList = getModel(true)
         customAdapter = CustomAdapter(this@MainActivity, modelArrayList!!)
         listView!!.adapter = customAdapter
         Toast.makeText(
            applicationContext, "Checked all items",
            Toast.LENGTH_SHORT
            ).show()
         }
         btnDeSelect.setOnClickListener {
            modelArrayList = getModel(false)
            customAdapter = CustomAdapter(this@MainActivity, modelArrayList!!)
            listView!!.adapter = customAdapter
            Toast.makeText(
               applicationContext, "Unchecked all items",
               Toast.LENGTH_SHORT
            ).show()
         }
      }
      private fun getModel(isSelect: Boolean): java.util.ArrayList<Model>? {
         val list: ArrayList<Model> = ArrayList()
         for (i in 0..8) {
            val model = Model()
            model.setSelected(isSelect)
            model.setPlayer(playerList[i])
            list.add(model)
         }
         return list
   }
}

Step 8 − Add the following code to androidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.myapplication">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
</application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Click here to download the project code.

raja
Published on 20-Apr-2020 15:54:50
Advertisements