Thursday, 15 March 2018

Android ListView Example Using Kotlin



1. Creating New Project in Kotlin
  • Open Android Studio.
  • Go to File => New => New Project.Give Name To your application. Then, check Include Kotlin Support and click next button.
  • Select minimum SDK you need. However, we have selected 21 as minimum SDK. Then, click next button.
  • Then, select Empty Activity => click next => click finish.
2. Here we take ListView in our layout. As in below xml layout.
main_activity.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"
    tools:context="com.dharmendra.listview.MainActivity">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

3.MainActivity.kt


package com.dharmendra.listview

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Find View By Id for ListView

        val listview = findViewById<ListView>(R.id.listview) as ListView

        //Define ArrayList
        var arrayList = ArrayList<Int>()

        //For Loop to add numbers from 1 to 20 In arrayList

        for (i in 1..20) {

            arrayList.add(i)
        }

        //Create adapter
        val adp: ArrayAdapter<Int> = ArrayAdapter(this@MainActivity, android.R.layout.simple_list_item_1, arrayList)

        //Set Adapter
        listview.adapter = adp

        //ListView Click
        listview.setOnItemClickListener { parent, view, position, id ->
            Toast.makeText(this@MainActivity, "you have Click on " + arrayList.get(position), Toast.LENGTH_LONG).show()

        }


    }
}


Output:


No comments:

Post a Comment