kotlin listview example
In this Tutorial Today learn kotlin listview android follow the full Source code kotlin listview example
What is a ListView in android?
Advertisements. Android ListView is a view which groups several items and display them in vertical scrollable list. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database
ArrayAdapter
You can use this adapter when your data source is an array. By default, ArrayAdapter creates a view for each array item by calling toString() on each item and placing the contents in a TextView. Consider you have an array of strings you want to display in a ListView, initialize a new ArrayAdapter using a constructor to specify the layout for each string and the string array
1.MainActivity.kt:
package com.akash.kotlinlistview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
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
}
}
2.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>
No comments:
Post a Comment