Android Kotlin: How to set ListView item height programmatically

Setting ListView Item Height Programmatically in Android Kotlin

This code demonstrates how to programmatically control the height of each item displayed in a ListView within an Android application written in Kotlin.

The code is divided into two main parts: the MainActivity.kt file handling the logic and the activity_main.xml file defining the layout.

Code Breakdown

MainActivity.kt

  1. Imports: Necessary libraries for building the user interface and manipulating data are imported.
  2. Activity Class: MainActivity inherits from the Activity class, which is the base class for most screen components in Android.
  3. onCreate Method: This method is called when the activity is first created.
    • Sets the layout to be inflated using setContentView.
    • Finds the ListView element with the ID listView from the layout.
    • Creates a list of strings to populate the ListView.
    • Initializes an ArrayAdapter with a custom implementation to modify the item view.
      • The adapter uses the default system layout android.R.layout.simple_dropdown_item_1line for a single line text view.
      • The getView method is overridden to customize the view for each list item.
        • Retrieves the TextView from the adapter's default view creation.
        • Sets the height of the TextView's layout parameters to 90dp using a custom extension function.
    • Sets the adapter to the ListView to display the data.

Extension Function:

  • A helper function is defined to convert integer values to device-independent pixels (dp).

activity_main.xml

  • Defines the layout using a ConstraintLayout.
  • A ListView element with ID listView is placed within the constraint layout, taking up the entire available space.

Summary

This code snippet showcases a way to dynamically control the height of each item displayed in a ListView. By overriding the getView method in a custom ArrayAdapter, we can access individual item views and modify their layout parameters. The provided extension function simplifies unit conversion for consistent sizing across different screen resolutions.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
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)


        // list to populate list view
        val list = mutableListOf(
            "Black bean",
            "Black coffee",
            "Black chocolate",
            "Canary yellow",
            "Champagne pink",
            "Congo pink"
        )


        // initialize an array adapter
        val adapter:ArrayAdapter<String> = object: ArrayAdapter<String>(
            this,
            android.R.layout.simple_dropdown_item_1line,
            list
        ){
            override fun getView(position: Int, convertView: View?,
                                 parent: ViewGroup): View {

                val textView:TextView = super.getView(position,
                    convertView, parent) as TextView

                // set list view item height programmatically
                textView.layoutParams.height = 90.toDp(context)

                return textView
            }
        }


        // attach the array adapter with list view
        listView.adapter = adapter
    }
}



// extension method to convert values to dp
fun Int.toDp(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    this.toFloat(),
    context.resources.displayMetrics
).toInt()
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"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>