ListView In Android Using Kotlin

ListView In Android Using Kotlin: ListView Example in Kotlin

In this tutorial, I will explain how you can make a ListView In Android Using Kotlin in Android Studio. We will design a simple ListView and add list items as an ArrayList. This is a very easy and simple example of a ListView In Android Using Kotlin language.

So, In this example, we are going to take a ListView and add items into the List using a String Array. We will display List items with the help of an adapter. And we are going to put a method setOnItemClickListener on each List Item. It will show display the position of that List item and its text. Let’s start making our ListView In Android Using Kotlin.

Listview In Android Using Kotlin

1- Start a new Android Studio Project and name it “ListViewKotlin” or you can name it whatever you want. Select API level 19 and the default language should be Kotlin.

2- Go to activity_main.xml and change the default Constraint Layout to Relative Layout.

3- In the activity_main.xml file take a ListView with wrap_content width and height.

4- Your ListView should have an id and look like this.

 

 

5- The final activity_main.xml file will look like this.

 

 

MainActivity.kt Code

 

6- Now we will start our Kotlin code. Come to MainActivity.kt file and define an array that will contain your List elements.

 

 

7-  In the onCreate method, we will use an adapter for our Array that will help us to display our items into the ListView. It will take three parameters ( Context, Resource, and List of Objects ). After that, we will set an adapter on our ListView.

 

 

Note: listview is the Id of our ListView in XML.

8- Now we want to display the text on each position of the List and also we will display the current position of the clicked item in the List. Here is how to do that.

 

 

9- We are done with everything here. The final MainActivity.kt file will look like this.

 

 

OUTPUT

 

 

ListView In Android Using Kotlin
ListView In Android Using Kotlin

ListView In Android Using Kotlin

ListView In Android Using Kotlin

 

 

More Android Posts

Leave a Comment

Your email address will not be published. Required fields are marked *

error: Content is protected !!