Kotlin GridView example: Show Item Details | Android

In previous post, we had known how to show list of Items using GridView. This tutorial shows you way to implement onClick Event on Item and come into its details.

Related Post: Kotlin ListView example | Android

I. Technologies

– Android Studio 3
– Kotlin 1.1.51

II. Overview

1. Goal

We will build an example that uses GridView to show list of food items like this:
kotlin-gridview-goal

When clicking on any Item, we can go to its details in new Activity:
kotlin-gridview-show-details-goal

2. Project Structure

kotlin-gridview-show-details-structure

In this example, we add FoodDetails Activity class. Clicking on any Item in MainActivity will direct us to FoodDetails (with image, name, description).

III. Practice

1. Set up Project

– Create New Project:
kotlin-gridview-create-project

– Add each item insides sample_images to res/drawable folder.

– Add FoodDetails Activity:
kotlin-gridview-add-activity-details

2. Layout

2.1 Container Layout

Open res/layout/activity_main.xml file:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.javasampleapproach.kotlin.gridview.MainActivity">

    <GridView
        android:id="@+id/gvFoods"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="150dp"
        android:horizontalSpacing="15dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="15dp" />

</LinearLayout>

2.2 Item Layout

Add food_entry.xml file to res/layout folder:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:background="#ddd"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="15dp">

        <ImageView
            android:id="@+id/imgFood"
            android:layout_width="150dp"
            android:layout_height="120dp"
            app:srcCompat="@drawable/french_fries" />

        <TextView
            android:id="@+id/tvName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="French Fries"
            android:textSize="20sp" />
</LinearLayout>

2.3 Item Details Layout

Open res/layout/activity_food_details.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center_horizontal"
    android:orientation="vertical"
    android:padding="15dp">
    tools:context="com.javasampleapproach.kotlin.gridview.FoodDetails">

    <ImageView
        android:id="@+id/imgFoodDetails"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:layout_marginTop="30dp"
        app:srcCompat="@drawable/strawberry_ice_cream" />

    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="TextView"
        android:textColor="@color/colorPrimary"
        android:textSize="24sp" />

    <TextView
        android:id="@+id/tvDetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="TextView" />

</LinearLayout>

3. Logic

3.1 Item Class

This class represents data of each Food Item:


package com.javasampleapproach.kotlin.gridview

class Food {
    var name: String? = null
    var description: String? = null
    var image: Int? = null

    constructor(name: String, description: String, image: Int) {
        this.name = name
        this.description = description
        this.image = image
    }
}

3.2 Main Activity Class

We will:
– Create a BaseAdapter subclass.
– Set an instance of this class as data provider to the GridView.
– Return each cell’s view from getView() on your adapter.
– Add OnClickListener for Item’s image.


package com.javasampleapproach.kotlin.gridview

import android.content.Context
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.food_entry.view.*

class MainActivity : AppCompatActivity() {

    var adapter: FoodAdapter? = null
    var foodsList = ArrayList()

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

        // load foods
        foodsList.add(Food("Coffee", "Coffee preparation is the process of turning coffee beans into a beverage. While the particular steps vary with the type of coffee and with the raw materials, the process includes four basic steps; raw coffee beans must be roasted, the roasted coffee beans must then be ground, the ground coffee must then be mixed with hot water for a certain time (brewed), and finally the liquid coffee must be separated from the used grounds.",
                R.drawable.coffee_pot))
        foodsList.add(Food("Espersso", "Espresso’s authentic formula is clear and basic, its proper execution a matter of training, experience and natural talent.  A jet of hot water at 88°-93°C (190°-200°F) passes under a pressure of nine or more atmospheres through a seven-gram (.25 oz) cake-like layer of ground and tamped coffee. Done right, the result is a concentrate of not more than 30 ml (one oz) of pure sensorial pleasure.",
                R.drawable.espresso))
        foodsList.add(Food("French Fires", "Heat a few inches of vegetable oil to 300 degrees F in a heavy pot. In 3 or 4 batches, fry the potatoes about 4 to 5 minutes per batch, or until soft. They should not be brown at all at this point-you just want to start the cooking process. Remove each batch and drain them on new, dry paper towels.",
                R.drawable.french_fries))
        foodsList.add(Food("Honey", "While it is less likely that anyone would do this on their own if they are not a beekeeper, this might be useful for those who aspire to become one. Bees are really great and easy to keep, even in the urban environment! As Novella Carpenter calls them, bees are "gateway animal for urban farmers". All you need is some space in the backyard/deck. The process of honey harvesting and extraction most likely happens on a separate days.",
                R.drawable.honey))
        foodsList.add(Food("Strawberry", "Preparation. Coarsely mash strawberries with sugar, lemon juice, and salt using a potato masher in a large bowl. Let stand, stirring and mashing occasionally, 10 minutes. Transfer half of strawberry mixture to a blender and purée with cream until smooth. Freeze mixture in ice cream maker.",
                R.drawable.strawberry_ice_cream))
        foodsList.add(Food("Sugar cubes", "Sugar cubes are extremely simple to make at home - all you need is sugar and water. In addition to standard cubes, you can add color and flavor to add fun flair to a tea party or another gathering. Learn how to make sugar cubes using two different methods: using a pan in the oven or an ice cube tray you leave out overnight.",
                R.drawable.sugar_cubes))
        adapter = FoodAdapter(this, foodsList)

        gvFoods.adapter = adapter
    }

    class FoodAdapter : BaseAdapter {
        var foodsList = ArrayList()
        var context: Context? = null

        constructor(context: Context, foodsList: ArrayList) : super() {
            this.context = context
            this.foodsList = foodsList
        }

        override fun getCount(): Int {
            return foodsList.size
        }

        override fun getItem(position: Int): Any {
            return foodsList[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            val food = this.foodsList[position]

            var inflator = context!!.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            var foodView = inflator.inflate(R.layout.food_entry, null)
            foodView.imgFood.setOnClickListener {

                val intent = Intent(context, FoodDetails::class.java)
                intent.putExtra("name", food.name!!)
                intent.putExtra("description", food.description!!)
                intent.putExtra("image", food.image!!)
                context!!.startActivity(intent)
            }
            foodView.imgFood.setImageResource(food.image!!)
            foodView.tvName.text = food.name!!

            return foodView
        }
    }
}

3.2 Item Details Activity Class


package com.javasampleapproach.kotlin.gridview

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_food_details.*

class FoodDetails : AppCompatActivity() {

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

        val bundle = intent.extras

        imgFoodDetails.setImageResource(bundle.getInt("image"))
        tvName.text = bundle.getString("name")
        tvDetails.text = bundle.getString("description")
    }
}

IV. Source Code

GridView-ItemDetails



By grokonez | December 3, 2017.

Last updated on May 21, 2021.



Related Posts


1 thought on “Kotlin GridView example: Show Item Details | Android”

Got Something To Say:

Your email address will not be published. Required fields are marked *

*