Sunday, February 11, 2018

android kotlin - GridView example

MainActivity.kt

package com.cfsuman.kotlinexamples

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


class MainActivity : AppCompatActivity() {

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

        // 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
        grid_view.adapter = adapter

        // Set an item click listener for grid view items
        grid_view.onItemClickListener = object : AdapterView.OnItemClickListener {
            override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                // Get the GridView selected/clicked item text
                val selectedItem = parent.getItemAtPosition(position).toString()

                // Display the selected/clicked item text and position on TextView
                text_view.text = "GridView item clicked : $selectedItem \nAt index position : $position"
            }
        }
    }
}
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"
    >
    <GridView
        android:id="@+id/grid_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="3"
        android:background="#a8b7ae"
        android:verticalSpacing="5dp"
        android:horizontalSpacing="5dp"
        />
    <TextView
        android:id="@+id/text_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
        android:textColor="#3e62c7"
        android:layout_marginTop="20dp"
        android:padding="15dp"
        android:background="#ecf8ff"
        />
</LinearLayout>