Kotlin ListView example | Android

In this Kotlin tutorial, we’re gonna look at way to show list of items with Android ListView.

Related Post: Kotlin GridView example: Show List of Items on Grid | Android

More Practice: Kotlin SQLite example – CRUD operations with ListView | Android

I. Technologies

– Android Studio 3
– Kotlin 1.1.51

II. Overview

1. Goal

We will build an Android App that uses ListView to show list of items:

kotlin-listview-goal

2. Android ListView
2.1 Input Types

Input (items) of a list can be arbitrary Kotlin object. We use an adapter to extract data from this Kotlin object, then assign object fields’value to the views in each row of ListView.

For example:

Class for Kotlin object is called data model.

2.2 Adapter

Adapter (extends the BaseAdapter class) manages the data model and adapts it:

2.3 Listener

We can also set Listener for reacting to selections in the list. For example, handle onItemClick event:

2.4 ViewHolder

ViewHolder allows to avoid the findViewById() method in adapter. It includes references to views in item layout.

BaseAdapter has getView() method that provide a convertView object, we can get the instance of the ViewHolder via the convertView.tag:

3. Project Structure

kotlin-listview-project-structure

III. Practice

1. Set up Project

– Create New Project:
kotlin-listview-create-project

– Add images (found in sourcecode) to drawable.

2. Layout
2.1 Main Activity

Open res/layout/activity_main.xml file, add ListView:

2.2 Item Layout

Add note.xml layout file to res/layout:

3. Data Model

Add Kotlin class:

4. Activity

We will:
– create ViewHolder class
– create BaseAdapter subclass
– set adapter for ListView
– add Listener to ListView

IV. Source Code

Kotlin-ListView

By JavaSampleApproach | December 6, 2017.


Related Posts


3 thoughts on “Kotlin ListView example | Android”

  1. I cannot explain why, but

    has to be changed to

    to get this thing running. Seems to be a change in the target API issue.
    I just adaptet some informations from here: https://stackoverflow.com/questions/45267041/not-enough-information-to-infer-parameter-t-with-kotlin-and-android

  2. sorry, has to be

Got Something To Say:

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

*