activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical">
<ListView
android:id="@+id/userlist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
MainActivity.kt
package com.androinidan.list
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
val users = arrayOf(
"Virat Kohli", "Rohit Sharma", "Steve Smith",
"Kane Williamson", "Ross Taylor"
)
var mListView: ListView?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// use arrayadapter and define an array
val arrayAdapter: ArrayAdapter<*>
// access the listView from xml file
mListView = findViewById<ListView>(R.id.userlist)
arrayAdapter = ArrayAdapter(this,
android.R.layout.simple_list_item_1, users)
mListView!!.adapter = arrayAdapter
mListView!!.setOnItemClickListener { parent, view, position, id ->
Toast.makeText(applicationContext,"position"+position,Toast.LENGTH_LONG).show()
}
}
}