ListView using Array from strings.xml with Item Click Listener kotlin

How to create a ListView from array in strings.xml in Kotlin using Android Studio?

In this tutorial we will create a ListView with Item Click Listener, we will write string array in strings.xml. When a list item is clicked a Toast will be displayed, you can change the functionality.

Step 1: Create a new project OR Open your project

Step 2: Code

strings.xml

<resources>
    <string name="app_name">Kotlin Practice</string>

    <string-array name="arrayelements">
        <item>Item 1</item>
        <item>Item 2</item>
        <item>Item 3</item>
        <item>Item 4</item>
        <item>Item 5</item>
    </string-array>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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" />

</LinearLayout>

ActivityMain.kt

package com.jigopost.kotlinpractice

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

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

        val mListView = findViewById<ListView>(R.id.listView)

        mListView.adapter = ArrayAdapter(this,android.R.layout.simple_expandable_list_item_1,resources.getStringArray(R.array.arrayelements))

        mListView.setOnItemClickListener{parent, view, position, id ->

            //Toast.makeText(this@MainActivity, "You have Clicked " + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show()

            if (position==0){
                Toast.makeText(this@MainActivity, "Item One",   Toast.LENGTH_SHORT).show()
            }
            if (position==1){
                Toast.makeText(this@MainActivity, "Item Two",   Toast.LENGTH_SHORT).show()
            }
            if (position==2){
                Toast.makeText(this@MainActivity, "Item Three", Toast.LENGTH_SHORT).show()
            }
            if (position==3){
                Toast.makeText(this@MainActivity, "Item Four",  Toast.LENGTH_SHORT).show()
            }
            if (position==4){
                Toast.makeText(this@MainActivity, "Item Five",  Toast.LENGTH_SHORT).show()
            }
        }
    }

}

Step 3: Output

Leave a Reply