Kotlin ListView

In this tutorial you will learn about the Kotlin ListView and its application with practical example.

ListView with Kotlin

ListView is a view from which we can display group of items in vertical scrollable list. List items are automatically inserted with the help of adapter.
Adapter is a bridge UI component and data source, It pulls data from database or an array.
It is briefly discussed in Android ListView Article . Please check that article.

Table Of Contents

Here we are going to discuss ListView with Kotlin in Android.

 

Example: Let’s create new project and do not forget check “Include Kotlin Support”. Used classes and Xml are listed below.

  1. MainActivity
  2. LangListAdapter
  3. Langauge(Model)
  4. activity_main.xml
  5. layout_adapter.xml
  6. header.xml
  7. colors.xml

Let’s understand each class one by one.

#Langauge(Model): In Kotlin we do not need to write getter and setter method in model. It is very simple to create model in Kotlin support. Just check below model, you will get understand what I am trying to say.

so it is pretty simple to create model just need to declare our variable.

 

#LangListAdapter: Below is the Adapter Code, code is reduced by Kotlin and it is very easy to get understand, methods are same as we already discussed in ListAdapter in Android Article. So Let’s write code of it. Here It extends Base Adapter which is clearly explained in Android Tutorial. BaseAdapter is very generic adapter which allows you to do pretty much whatever you want . Its custom Adapter from which you can do whatever you want to do with grid and list, But you need to do some coding for it.

# layout_adapter.xml : The below layout is associated with Above adapter class. Just check it.

#MainActivity: Now it is time to finish our last stage that is Activity which is associated with Model and Adapter. We have added data from here. The adding process is about same Like we used to use before, but some changes are there, Kotlin also reduced code here and did simple work for us. Checkout below code.

#activity_main.xml: The Associated XML file with Above activity is below you can simply use it.

#Header.xml: The Header file which I have used in activity_main.xml is below, you can modified it according to you.

#colors.xml: Some colors I have used so that it look good, you can use it.

Run: We are all set from coding site. So its time to run this project on your device or Emulator. I have used Emulator. The result of above project will look like below image.

1

In this tutorial we have learn about the Kotlin ListView and its application with practical example. I hope you will like this tutorial.