Friday, February 9, 2018

android kotlin - ListView example

MainActivity.kt

package com.cfsuman.kotlinexamples

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import android.widget.AdapterView
import android.widget.ArrayAdapter


class MainActivity : AppCompatActivity() {

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

        // Initializing a list of string
        val colors = listOf("Red", "Green", "Blue", "Yellow", "Black", "Crimson", "Orange")

        // Create an ArrayAdapter from List
        val adapter = ArrayAdapter<String>(
                this, // Context
                android.R.layout.simple_list_item_1, // Layout
                colors // List
        )

        // Finally, data bind the list view object with adapter
        list_view.adapter = adapter;

        // Set an item click listener for ListView
        list_view.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
            // Get the selected item text from ListView
            val selectedItem = parent.getItemAtPosition(position) as String

            // Display the selected item text on TextView
            text_view.text = "Your favorite color: $selectedItem"
        }
    }
}
activity_main.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:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    >
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:textStyle="bold|italic"
        android:textColor="#f72242"
        android:text="Select your favorite color"
        />
    <ListView
        android:id="@+id/list_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="25dp"
        />
</LinearLayout>