Adding Items to ListView Programmatically in Android (Kotlin)
This code demonstrates how to add items to a ListView programmatically in an Android application written in Kotlin. It showcases various functionalities and best practices for managing a list view dynamically.
Breakdown:
Setting Up the Activity:
- The
MainActivity
class inherits fromActivity
. - In
onCreate
, the layout (activity_main.xml
) is inflated and references to widgets (Button, ListView, TextView) are obtained.
- The
Populating the ListView:
- A mutable list (
list
) is created containing initial items.
- A mutable list (
ArrayAdapter for ListView:
- An
ArrayAdapter
is created, responsible for converting data (list) into view elements for the ListView. android.R.layout.simple_dropdown_item_1line
is the default layout for each item in the list.
- An
ListView Click Listener:
- An
onItemClickListener
is set for the ListView. - When an item is clicked, the selected item's text is displayed in the TextView.
- An
Adding Items Programmatically (Button Click):
- A button click listener is set for the "Add Items" button.
- Clicking the button disables itself to prevent multiple clicks.
- Various methods are used to modify the
list
:add
adds an item to the end.add(index, element)
adds an item at a specific index (beginning in this case).addAll
adds all elements from another list.- Conditional check ensures
add
at index 5 only happens if the list has at least 5 elements.
- After modifications,
adapter.notifyDataSetChanged
notifies the adapter about the data change, triggering the list view to update.
Summary
This code effectively demonstrates how to manage a ListView dynamically in an Android app using Kotlin. It covers essential aspects like setting up the adapter, handling user interaction (clicks), and programmatically modifying the list data with various functionalities. The code also includes best practices like disabling the button after click and notifying the adapter about data changes.
package com.cfsuman.kotlintutorials
import android.app.Activity
import android.os.Bundle
import android.widget.*
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// get the widgets reference from XML layout
val button = findViewById<Button>(R.id.button)
val listView = findViewById<ListView>(R.id.listView)
val textView = findViewById<TextView>(R.id.textView)
// list to populate list view
val list = mutableListOf(
"Antique ruby",
"Bitter lemon"
)
// initialize an array adapter
val adapter:ArrayAdapter<String> = ArrayAdapter(
this,
android.R.layout.simple_dropdown_item_1line,list
)
// attach the array adapter with list view
listView.adapter = adapter
// list view item click listener
listView.onItemClickListener = AdapterView.OnItemClickListener {
parent, view, position, id ->
val selectedItem = parent.getItemAtPosition(position)
textView.text = "Selected : $selectedItem"
}
// add list view items programmatically
button.setOnClickListener {
// disable the button itself
it.isEnabled = false
// add an items to list view bottom
list.add("Black bean")
// add an item to list first
list.add(0,"Blue sapphire")
// insert multiple items at a time
val newItems = listOf("Brick red","Bright green")
list.addAll(newItems)
// insert element at index 5 position
if(list.size>=5){
list.add(5,"Cadmium red")
}
// finally, notify the adapter for data set changed
adapter.notifyDataSetChanged()
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rootLayout"
android:background="#DCDCDC"
android:padding="24dp">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Items"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="@+id/listView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="24dp"
app:layout_constraintBottom_toTopOf="@+id/textView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/button" />
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Select your favorite color"
android:fontFamily="sans-serif"
android:gravity="center"
android:textColor="#333399"
android:textSize="24sp"
android:textStyle="italic"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>