Android Kotlin: How to add a header to a ListView programmatically

Adding a Header to a ListView in Android with Kotlin

This code demonstrates how to programmatically add a header view to a ListView in an Android application written in Kotlin. It achieves this by inflating a separate layout for the header and then customizing its appearance before adding it to the ListView.

Breakdown

  1. Setting Up the Activity:

    • The MainActivity class extends the Activity class and defines the onCreate method, which is the entry point for the activity.
    • Inside onCreate, the layout (activity_main.xml) is inflated and assigned to the activity using setContentView.
    • References to the ListView (listView) and a TextView (textView) are obtained using findViewById.
  2. Populating the ListView:

    • A list of color names is created and stored in a mutableListOf.
    • An ArrayAdapter is created using the list data and assigned to the ListView's adapter using listView.adapter. This adapter handles displaying the list items.
  3. Handling Item Clicks:

    • An OnItemClickListener is set for the ListView. This listener gets called whenever an item in the list is clicked.
    • Inside the listener, the selected item's text is retrieved and displayed in the textView.
  4. Creating and Customizing the Header:

    • A new TextView is inflated using the system layout simple_dropdown_item_1line as a base. This layout provides a basic one-line text view.
    • The header text ("List of colors.") is set for the TextView.
    • The text is made bold using setTypeface.
    • A background color and text color are set for the header using setBackgroundColor and setTextColor.
  5. Adding the Header to the ListView:

    • Finally, the customized TextView is added as a header view to the ListView using listView.addHeaderView. The third argument (false) ensures the header is not clickable/selectable.

Summary

This code effectively demonstrates how to add a custom header view to a ListView in Kotlin. By inflating a separate layout and customizing its appearance, the developer can create a visually distinct header that enhances the user experience of the list.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.graphics.Color
import android.graphics.Typeface
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 listView = findViewById<ListView>(R.id.listView)
        val textView = findViewById<TextView>(R.id.textView)


        // list to populate list view
        val list = mutableListOf(
            "Celadon blue",
            "Alloy orange",
            "Amaranth pink",
            "Apple green",
            "Cameo pink",
            "Black chocolate"
        )


        // 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"
        }


        // get the layout for list view header view
        val header:TextView = layoutInflater.inflate(
            android.R.layout.simple_dropdown_item_1line,
            listView,
            false
        ) as TextView


        // set text for header view
        header.text = "List of colors."


        // make header text bold
        header.setTypeface(header.typeface, Typeface.BOLD)


        // give a background color to header
        header.setBackgroundColor(Color.parseColor("#A1CAF1"))


        // set header text color
        header.setTextColor(Color.parseColor("#1B1811"))


        // finally, add the header view to list view
        listView.addHeaderView(
            header,
            null,
            false // make it not selectable/clickable
        )
    }
}
activity_main.xml

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

    <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_toTopOf="parent" />

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