Create CheckBox For Each Item in ListView in Android
A ListView in Android is a UI element used to display a list of items from the main code with the use of an array adapter. Other similar views require separate layouts for displaying data. Whereas, ListView has pre-determined item layouts available because of which no separate layout is to be created. However, all these layouts support only TextView because of which other UI elements cannot be added. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
So in this article, we will show you how you could add a CheckBox in ListView item layout in Android. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a ListView as shown below.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > < ListView android:id = "@+id/list_view_1" android:layout_width = "match_parent" android:layout_height = "match_parent" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
Step 3: Create a layout for the ListView item raw_item.xml file
Navigate to the app > res > layout and create a new Android Resource Layout by right-clicking on the layout folder and selecting the appropriate option. We named this file raw_item.xml. Now add a TextView and a CheckBox in this layout as shown below.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout 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 4: Create an item class DataModel.kt
Create a new Kotlin class for defining the model object as shown below.
Kotlin
package org.geeksforgeeks.checkboxinlistview class DataModel internal constructor(var name: String?, var checked: Boolean) |
Step 5: Create an adapter for the listview CustomAdapter.kt
Create a new Kotlin file for developing an adapter. The name of this file is CustomAdapter.kt. Adapter is used to display DataModel objects in the ListView. Below is the code for the custom adapter.
Kotlin
package org.geeksforgeeks.checkboxinlistview 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 class CustomAdapter( private val dataSet: ArrayList<*>, mContext: Context) : ArrayAdapter<Any?>(mContext, R.layout.raw_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.raw_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 6: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package org.geeksforgeeks.checkboxinlistview import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.AdapterView import android.widget.ListView class MainActivity : AppCompatActivity() { // Declaring the DataModel Array private var dataModel: ArrayList<DataModel>? = null // Declaring the elements from the main layout file private lateinit var listView: ListView private lateinit var adapter: CustomAdapter override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the elements from the main layout file listView = findViewById<View>(R.id.list_view_1) as ListView // Initializing the model and adding data // False = not checked; True = checked 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 )) // Setting the adapter adapter = CustomAdapter(dataModel!!, applicationContext) listView.adapter = adapter // Upon item click, checkbox will be set to checked listView.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ -> val dataModel: DataModel = dataModel!![position] as DataModel dataModel.checked = !dataModel.checked adapter.notifyDataSetChanged() } } } |
Output:
Upon item click, the item will be checked.
Please Login to comment...