Open In App

Android GridView in Kotlin

Last Updated : 06 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A Grid View is a type of adapter view that is used to display the data in the grid layout format. For setting the data to the grid view adapter is used with the help of the setAdapter() method. This adapter helps to set the data from the database or array list to the items of the grid view. In this article, we will take a look at How to implement Grid View in Android using Kotlin language. A sample video is given below to get an idea about what we are going to do in this article.

Note: If you are looking to implement Grid View in Android using Java. Check out the following article: Grid View in Android using Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--on below line we are creating a grid view-->
    <GridView
        android:id="@+id/idGRV"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="6dp"
        android:numColumns="2"
        android:verticalSpacing="6dp" />
 
</RelativeLayout>


Step 3: Create an XML layout file for each item of GridView

Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as gridview_item. Below is the code for the gridview_item.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="5dp">
 
    <!--on below line we are creating
        a linear layout for grid view item-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
 
        <!--on below line we are creating
             a simple image view-->
        <ImageView
            android:id="@+id/idIVCourse"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:padding="4dp"
            android:src="@mipmap/ic_launcher" />
 
        <!--on below line we are creating
            a simple text view-->
        <TextView
            android:id="@+id/idTVCourse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:padding="4dp"
            android:text="@string/app_name"
            android:textAlignment="center"
            android:textColor="@color/black" />
 
    </LinearLayout>
 
</androidx.cardview.widget.CardView>


Step 4: Create a Modal Class for storing Data

Modal Class is the JAVA Class that handles data to be added to each GridView item of GridView. For Creating Modal Class. Navigate to app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and specify the name as GridViewModal and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
// on below line we are creating a modal class.
data class GridViewModal(
    // we are creating a modal class with 2 member
    // one is course name as string and
    // other course img as int.
    val courseName: String,
    val courseImg: Int
)


Step 5: Creating the Adapter class 

Adapter Class adds the data from Modal Class in each item of GridView which is to be displayed on the screen. For Creating Adapter Class. Navigate to the app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and specify the name as GridRVAdapter and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
 
// on below line we are creating an
// adapter class for our grid view.
internal class GridRVAdapter(
    // on below line we are creating two
    // variables for course list and context
    private val courseList: List<GridViewModal>,
    private val context: Context
) :
    BaseAdapter() {
    // in base adapter class we are creating variables
    // for layout inflater, course image view and course text view.
    private var layoutInflater: LayoutInflater? = null
    private lateinit var courseTV: TextView
    private lateinit var courseIV: ImageView
 
    // below method is use to return the count of course list
    override fun getCount(): Int {
        return courseList.size
    }
 
    // below function is use to return the item of grid view.
    override fun getItem(position: Int): Any? {
        return null
    }
     
    // below function is use to return item id of grid view.
    override fun getItemId(position: Int): Long {
        return 0
    }
 
    // in below function we are getting individual item of grid view.
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
        var convertView = convertView
        // on blow line we are checking if layout inflater
        // is null, if it is null we are initializing it.
        if (layoutInflater == null) {
            layoutInflater =
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        }
        // on the below line we are checking if convert view is null.
        // If it is null we are initializing it.
        if (convertView == null) {
            // on below line we are passing the layout file
            // which we have to inflate for each item of grid view.
            convertView = layoutInflater!!.inflate(R.layout.gridview_item, null)
        }
        // on below line we are initializing our course image view
        // and course text view with their ids.
        courseIV = convertView!!.findViewById(R.id.idIVCourse)
        courseTV = convertView!!.findViewById(R.id.idTVCourse)
        // on below line we are setting image for our course image view.
        courseIV.setImageResource(courseList.get(position).courseImg)
        // on below line we are setting text in our course text view.
        courseTV.setText(courseList.get(position).courseName)
        // at last we are returning our convert view.
        return convertView
    }
}


Step 6: Adding images to the drawable folder 

Copy your images. And navigate to the app > res > drawable > Right-click on it and paste all the images which are copies within the drawable folder. Refer to this article How to Add Image to Drawable Folder in Android Studio

Step 7: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.os.Bundle
import android.widget.AdapterView
import android.widget.GridView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.*
import kotlin.collections.ArrayList
 
class MainActivity : AppCompatActivity() {
    // on below line we are creating
    // variables for grid view and course list
    lateinit var courseGRV: GridView
    lateinit var courseList: List<GridViewModal>
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // initializing variables of grid view with their ids.
        courseGRV = findViewById(R.id.idGRV)
        courseList = ArrayList<GridViewModal>()
        
        // on below line we are adding data to
        // our course list with image and course name.
        courseList = courseList + GridViewModal("C++", R.drawable.c)
        courseList = courseList + GridViewModal("Java", R.drawable.java)
        courseList = courseList + GridViewModal("Android", R.drawable.android)
        courseList = courseList + GridViewModal("Python", R.drawable.python)
        courseList = courseList + GridViewModal("Javascript", R.drawable.js)
 
        // on below line we are initializing our course adapter
        // and passing course list and context.
        val courseAdapter = GridRVAdapter(courseList = courseList, this@MainActivity)
        
        // on below line we are setting adapter to our grid view.
        courseGRV.adapter = courseAdapter
         
        // on below line we are adding on item
        // click listener for our grid view.
        courseGRV.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
            // inside on click method we are simply displaying
            // a toast message with course name.
            Toast.makeText(
                applicationContext, courseList[position].courseName + " selected",
                Toast.LENGTH_SHORT
            ).show()
        }
 
    }
}


Now run your application to see the output of it. 

Output: 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads