How to create a listView with a checkBox in Kotlin?

Kotlin Apps/ApplicationsMobile Development

This example demonstrates how to Create a listView with a checkBox in 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.

Example

<?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:padding="4dp"
   tools:context=".MainActivity">
<ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</RelativeLayout>

Step 3 − Add the following code to src/MainActivity.kt

Example

import android.view.View
import android.widget.AdapterView.OnItemClickListener
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import java.util.*
class MainActivity : AppCompatActivity() {
   private var dataModel: ArrayList<DataModel>? = null
   private lateinit var listView: ListView
   private lateinit var adapter: CustomAdapter
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      listView = findViewById<View>(R.id.listView) as ListView
      dataModel = ArrayList<DataModel>()
      dataModel!!.add(DataModel("Apple Pie", false))
      dataModel!!.add(DataModel("Banana Bread", false))
      dataModel!!.add(DataModel("Cupcake", false))
      dataModel!!.add(DataModel("Donut", true))
      dataModel!!.add(DataModel("Eclair", true))
      dataModel!!.add(DataModel("Froyo", true))
      dataModel!!.add(DataModel("Gingerbread", true))
      dataModel!!.add(DataModel("Honeycomb", false))
      dataModel!!.add(DataModel("Ice Cream Sandwich", false))
      dataModel!!.add(DataModel("Jelly Bean", false))
      dataModel!!.add(DataModel("Kitkat", false))
      dataModel!!.add(DataModel("Lollipop", false))
      dataModel!!.add(DataModel("Marshmallow", false))
      dataModel!!.add(DataModel("Nougat", false))
      adapter = CustomAdapter(dataModel!!, applicationContext)
      listView.adapter = adapter
      listView.onItemClickListener = OnItemClickListener { _, _, position, _ ->
         val dataModel: DataModel = dataModel!![position] as DataModel
         dataModel.checked = !dataModel.checked
         adapter.notifyDataSetChanged()
      }
   }
}

Step 4  − Create a new Kotlin class (CustomAdapter.kt) and add the following code to src/CustomAdapter.kt

Example

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.TextView
import java.util.*
class CustomAdapter(private val dataSet: ArrayList<*>, mContext: Context) :
ArrayAdapter<Any?>(mContext, R.layout.row_item, dataSet) {
   private class ViewHolder {
      lateinit var txtName: TextView
      lateinit var checkBox: CheckBox
   }
   override fun getCount(): Int {
      return dataSet.size
   }
   override fun getItem(position: Int): DataModel {
      return dataSet[position] as DataModel
   }
   override fun getView(
   position: Int,
   convertView: View?,
   parent: ViewGroup
   ): View {
      var convertView = convertView
      val viewHolder: ViewHolder
      val result: View
      if (convertView == null) {
         viewHolder = ViewHolder()
         convertView =
         LayoutInflater.from(parent.context).inflate(R.layout.row_item, parent, false)
         viewHolder.txtName =
         convertView.findViewById(R.id.txtName)
         viewHolder.checkBox =
         convertView.findViewById(R.id.checkBox)
         result = convertView
         convertView.tag = viewHolder
      } else {
         viewHolder = convertView.tag as ViewHolder
         result = convertView
      }
      val item: DataModel = getItem(position)
      viewHolder.txtName.text = item.name
      viewHolder.checkBox.isChecked = item.checked
      return result
   }
}

Step 5 − Create a new Kotlin class (DataModel.kit) and add the following code to src/DataModel.kt

package app.com.q3
class DataModel internal constructor(var name: String?, var checked: Boolean)

Step 6 − Create a Layout resource file (row_item.xml) and add the following code −

Example

<?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"
   android:padding="2dp">
   <TextView
      android:id="@+id/txtName"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentStart="true"
      android:layout_centerVertical="true"
      android:textColor="@android:color/background_dark"
      android:textSize="16sp" />
   <CheckBox
      android:id="@+id/checkBox"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentTop="true"
      android:layout_alignParentEnd="true" />
</RelativeLayout>

Step 7 − Add the following code to androidManifest.xml

Example

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.q1">
   <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 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

raja
Published on 23-May-2020 13:16:27
Advertisements