Now let’s see about ListView in android.
In this project, we are going to show a list of android versions in a ListView.
for that create a new project named List_View (you can change the name as your wish :p ).
Now enter the following data in your activity_main.xml file
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout 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="com.a4akhilsudha.list_view.MainActivity"> <ListView android:id="@+id/listView" android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="8dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout>
Now create a string array in your string.xml file. In here we are creating a list of android versions.
<resources> <string name="app_name">List_View</string> <string-array name="android_versions"> <item>Apple pie</item> <item>Banana bread</item> <item>Cupcake</item> <item>Donut</item> <item>Eclair</item> <item>Froyo</item> <item>Gingerbread</item> <item>Honeycomb</item> <item>Ice cream sandwich</item> <item>Jellybean</item> <item>Kitkat</item> <item>Lollipop</item> <item>Marshmallow</item> <item>Nougat</item> <item>Oreo</item> </string-array> </resources>
Now open your MainActivity.kt file and enter the following data.
package com.a4akhilsudha.list_view import android.support.v7.app.AppCompatActivity import android.os.Bundle 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 the id of the ListView*/ val listView = findViewById(R.id.listView) as ListView /*Set an adapter for the list view having the string array*/ listView.adapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, resources.getStringArray(R.array.android_versions)) /*set click listener for listView*/ listView.setOnItemClickListener { parent, view, position, id -> Toast.makeText(this@MainActivity, "You have Clicked " + parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show() } } }
Now run (Shift + f10) the program on a real device or in a virtual device.
Congrats …. 🙂 You just created an android app which displays a list of android versions.
Output :
A good little programme.