Wednesday, March 11, 2020

android kotlin - ListView item height programmatically

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>
More android examples