Saturday, August 1, 2020

android kotlin - GridView add item dynamically

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>