Kotlin GridView example: Show List of Items on Grid | Android

GridView is an Android ViewGroup that can show items in a 2-dimensional, scrollable grid. The grid items will be inserted to the layout using an Adapter. In this tutorial, we’re gonna create an Android App that can show List of Items on a Grid using GridView.

More Practice: Kotlin GridView example: Show Item Details | Android

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

2. Project Structure

kotlin-gridview-project-structure

III. Practice

1. Set up Project

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

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

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>
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 image: Int? = null

    constructor(name: String, image: Int) {
        this.name = name
        this.image = image
    }
}
3.2 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.


package com.javasampleapproach.kotlin.gridview

import android.content.Context
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", R.drawable.coffee_pot))
        foodsList.add(Food("Espersso", R.drawable.espresso))
        foodsList.add(Food("French Fires", R.drawable.french_fries))
        foodsList.add(Food("Honey",R.drawable.honey))
        foodsList.add(Food("Strawberry", R.drawable.strawberry_ice_cream))
        foodsList.add(Food("Sugar cubes", 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.setImageResource(food.image!!)
            foodView.tvName.text = food.name!!

            return foodView
        }
    }
}

IV. Source Code

Kotlin-GridView



By grokonez | December 2, 2017.

Last updated on April 12, 2021.



Related Posts


9 thoughts on “Kotlin GridView example: Show List of Items on Grid | Android”

  1. i have followed your instruction, but still get an error in “adapter = FoodAdapter(this, foodsList)”
    it says “Type missmatch : inferred type as fragmentHome but Context was expected”
    can you help me?

    thanks before

  2. Thank you very much ! I’ve never used a gridview before but after reading this I understand it all thank to you!

  3. Thank you, great sample. I have one single problem: in the method getView(…) the “position” parameter is not incremented. Do someoneelse have the same problem? I would appreciate any help. Greetings

Got Something To Say:

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

*