Display List View in Android

A list view is a scrollable list that displays a list of items.

A ListView class is used to create a list view. It is empty and requires an adapter that provides data from source.

app/src/main/res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Using arrayOf() function we create an array that contains a list of items. An ArrayAdapter converts a list of items into View items. A simple_list_item_1 is an built-in XML layout file that contains single TextView.

The setOnItemClickListener() method registers a callback. It will be invoked when an item was clicked. We use getItemAtPosition() method to get the item associated with the specified position in the list.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity()
{
    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val items: Array<String> = arrayOf("Yellow", "Green", "Red", "Blue")

        val adapter: ArrayAdapter<String> = ArrayAdapter(
            this,
            android.R.layout.simple_list_item_1,
            items
        )

        listView.adapter = adapter

        listView.setOnItemClickListener { parent, view, position, id ->
            val item: String = listView.getItemAtPosition(position).toString()
            Log.d("MY_APP", item)
        }
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *