Android Kotlin: How to dynamically add item to GridView

Dynamically Adding Items to a GridView in Android with Kotlin

This code demonstrates how to dynamically add items to a GridView in an Android application written in Kotlin. It utilizes a GridView to display a list of plants and allows the user to add a new item ("Itchweed") to the list at runtime.

Breakdown

The code is divided into two main parts:

  1. MainActivity.kt: This file handles the logic for the activity. It defines:

    • A mutableListOf to store the plant names.
    • An ArrayAdapter for the GridView that customizes the appearance of each item.
    • An onClickListener for the GridView to capture user selections.
    • An onClickListener for the "Add Item" button to dynamically add "Itchweed" to the list and update the GridView.
  2. activity_main.xml: This file defines the layout for the activity. It includes:

    • A MaterialButton labeled "Add Item: Itchweed" to trigger item addition.
    • A GridView to display the list of plants.
    • A TextView to display messages about adding items.

Summary

By clicking the "Add Item" button, the user triggers adding "Itchweed" to the plant list. The adapter.notifyDataSetChanged() method notifies the adapter about the data change, prompting the GridView to refresh and display the updated list. This example showcases a basic approach to adding items dynamically in Kotlin, and you can modify it to add items at different positions or handle different data types.


MainActivity.kt

package com.example.jetpack

import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
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)

        // mutable list of plants to populate grid view
        val list = mutableListOf(
            "Catalina ironwood",
            "Cabinet cherry",
            "Pale corydalis",
            "Pink corydalis",
            "Land cress",
            "Coast polypody",
            "Water fern"
        )

        // array adapter for grid view
        val adapter = object : ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,list) {
            override fun getView(
                position: Int, convertView: View?,
                parent: ViewGroup
            ): View {

                return (super.getView(position, convertView, parent) as TextView)
                    .apply {
                        text = list[position]
                        gravity = Gravity.CENTER

                        // grid view vertical spacing, horizontal spacing and
                        // item background color together make border between items
                        setBackgroundColor(Color.parseColor("#66DDAA"))
                    }
            }
        }

        gridView.adapter = adapter


        // 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
        }


        // add an item to grid view dynamically
        btnAdd.setOnClickListener {
            // add an item to end of list
            // you may add item at any position using another method
            if(list.add("Itchweed")){
                textView.text = "Item added successfully."
                // notify adapter about data set change
                // so grid view will refresh / repopulate
                adapter.notifyDataSetChanged()
                it.isEnabled = false
            }else{
                textView.text = "Failed to add item."
            }
        }
    }
}
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">

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btnAdd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:backgroundTint="#8DB600"
        android:text="Add Item: Itchweed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <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:horizontalSpacing="3dp"
        android:background="#30BA8F"
        android:numColumns="2"
        android:verticalSpacing="3dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnAdd" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:textColor="#004F98"
        android:textSize="30sp"
        android:fontFamily="sans-serif-condensed-medium"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/gridView"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials