Javatpoint Logo
Javatpoint Logo

Kotlin Android ListView

Android ListView is a view component that contains the list of items and is displayed in a scrollable list. The list items are automatically added to the list using the Adapter class. The Adapter class bridges the list of data between an AdapterViews other Views components (ListView, ScrollView, etc.).

Call the setAdapter(adapter) to connect an adapter with the list to display the items in list view. To know more about Android ListView go to https://www.javatpoint.com/android-listview-exampler

Kotlin Android ListView Example

In this example, we will create a ListView and perform click action on the list items. The items of a list can be created in the class file or in a separate file such as in strings.xml.

For example, create list items in a class file and add it on ArrayAdapter class:

Creating list items in a separate strings.xml file and added it on ArrayAdapter class:

activity_main.xml

Add a ListView component to display the list of items in the activity_main.xml file.

strings.xml

In the strings.xml file, create a string-array and add the list items in the item tag.

MainActivity.kt

Add the following code in the MainActivity.kt class file. In this class, we are getting the list of items from the strings.xml file using resource.getStringArray() method. The ArrayAdapter class initialized with the application context, sets the resource type of list and array items as an argument. The listView.adapter = arrayAdapter sets the adapter to the ListView. To perform the click action on items of the list, call the OnItemClickListener{}.

Output:

Kotlin Android ListView Kotlin Android ListView
Next Topic#




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA