Thursday, July 30, 2020

android kotlin - GridView OnItemClickListener

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        // list of plants to populate grid view
        val list = listOf(
            "Striped alder",
            "Amy root",
            "Arizona sycamore",
            "Green ash",
            "Cherry birch",
            "Gray birch",
            "Mahogany birch",
            "Spice birch",
            "Yellow birch"
        )

        // array adapter for grid view
        ArrayAdapter(this,android.R.layout.simple_list_item_1,list).apply {
            gridView.adapter = this
        }

        // set grid view item click listener
        gridView.setOnItemClickListener { adapterView, view, i, l ->
            // get grid view clicked item text
            val selectedItem = adapterView.getItemAtPosition(i).toString()
            textView.text = selectedItem
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#EDEAE0">

    <GridView
        android:id="@+id/gridView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:background="#F3F0E7"
        android:numColumns="2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:textSize="30sp"
        android:textColor="#00356B"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/gridView"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>