How to create a ListView from array in Kotlin using Android Studio?
DESCRIPTION
In this tutorial we will create a ListView using array , array items will be displayed in ListView. We will also handle Item Clicks , I'll display a Toast on each item click , you can do your functionality.VIDEO
SOURCE CODE
Step 1: Create a new project OR Open your project
Step 2: Code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".MainActivity"><ListViewandroid:id="@+id/listView"android:layout_width="match_parent"android:layout_height="match_parent" /></LinearLayout>
MainActivity.kt
package com.blogspot.devofandroid.kotlinpracticeimport android.os.Bundleimport android.support.v7.app.AppCompatActivityimport android.widget.ArrayAdapterimport android.widget.ListViewimport android.widget.Toastclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val values = arrayOf("Item One" , "Item Two" , "Item Three" , "Item Four" , "Item Five")val mListView = findViewById<ListView>(R.id.listView)val adapter = ArrayAdapter<String>(this , android.R.layout.simple_list_item_1 , values)mListView.adapter =adaptermListView.setOnItemClickListener{parent , view , position , id ->//Toast.makeText(this@MainActivity , "You have Clicked " + parent.getItemAtPosition(position) , Toast.LENGTH_SHORT).show()if (position==0){Toast.makeText(this@MainActivity , "Item One" , Toast.LENGTH_SHORT).show()}if (position==1){Toast.makeText(this@MainActivity , "Item Two" , Toast.LENGTH_SHORT).show()}if (position==2){Toast.makeText(this@MainActivity , "Item Three" , Toast.LENGTH_SHORT).show()}if (position==3){Toast.makeText(this@MainActivity , "Item Four" , Toast.LENGTH_SHORT).show()}if (position==4){Toast.makeText(this@MainActivity , "Item Five" , Toast.LENGTH_SHORT).show()}}}}
0 Response to "Listview Using Array With Item Click Listener (Kotlin)"