Sunday, February 11, 2018

android kotlin - GridView example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.os.Bundle
import android.widget.*


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

        // get the widgets reference from XML layout
        val gridView = findViewById<GridView>(R.id.gridView)
        val textView = findViewById<TextView>(R.id.textView)


        // Initialize a list of string values
        val colors = listOf<String>(
            "Red","Green","Yellow","Blue",
            "Magenta","Pink","White","Gray"
        )


        // Initialize a new array adapter instance
        val adapter = ArrayAdapter(
            this, // Context
            android.R.layout.simple_list_item_1, // Layout
            colors // List
        )


        // Set the grid view adapter/data source
        gridView.adapter = adapter


        // Set an item click listener for grid view items
        gridView.onItemClickListener = AdapterView
            .OnItemClickListener {
                    parent, view, position, id ->

            // Get the GridView selected/clicked item text
            val selectedItem = parent
            .getItemAtPosition(position).toString()

            // Display the selected/clicked
            // item text and position on TextView
            textView.text = "GridView item clicked : $selectedItem" +
                    " \nAt index position : $position"
        }
    }
}
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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC"
    android:padding="24dp">

    <GridView
        android:id="@+id/gridView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="#F8F8F8"
        android:horizontalSpacing="5dp"
        android:numColumns="3"
        android:verticalSpacing="5dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:fontFamily="sans-serif"
        android:textStyle="italic"
        android:textSize="24sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/gridView" />

</androidx.constraintlayout.widget.ConstraintLayout>