MainActivity.kt
When we have created layout, we need to load the XML layout resource from our activity onCreate() callback method and access the UI element form the XML using findViewById.
import android.widget.ArrayAdapter
import android.widget.ListView
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// use arrayadapter and define an array
val arrayAdapter: ArrayAdapter<*>
val users = arrayOf(
"Virat Kohli", "Rohit Sharma", "Steve Smith",
"Kane Williamson", "Ross Taylor"
)
// access the listView from xml file
var mListView = findViewById<ListView>(R.id.userlist)
arrayAdapter = ArrayAdapter(this,
android.R.layout.simple_list_item_1, users)
mListView.adapter = arrayAdapter
}
}
ListView Output:
We need to run using Android Virtual Device(AVD) to see the output.
Android ListView in Kotlin
Android ListView is a ViewGroup which is used to display the list of items in multiple rows and contains an adapter which automatically inserts the items into the list. The main purpose of the adapter is to fetch data from an array or database and insert each item that is placed into the list for the desired result. So, it is the main source to pull data from strings.xml file which contains all the required strings in Kotlin or XML files.
In this article, we will learn how to use Android ListView in Kotlin.