Android GridView in Kotlin
Last Updated :
04 Apr, 2025
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.
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.
activity_main.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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=".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.
gridview_item.xml:
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
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="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 Kotlin Class that handles data to be added to each GridView item of GridView. For Creating Modal Class. Navigate to app > java/kotlin > 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.
Modal.kt:
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 theMainActivity.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.
MainActivity.kt:
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.
To access the git repository for the topic – Click Here
Output:
Similar Reads
Android EditText in Kotlin
EditText is a widget in Android, that is used to get input from the user. EditText is commonly used in forms and login or registration screens. EditText extends the TextView class and provides more functionalities including handing text inputs such as cursor control, keyboard display and text valida
3 min read
Android Fade In/Out in Kotlin
In Android Animations are the visuals that are added to make the user interface more interactive, clear and good looking. Fade In and Fade out animations are used to modify the appearance of any view over a set interval of time so that user can be notified about the changes that are occurring in our
3 min read
GridView in Android with Example
A GridView is a type of AdapterView that displays items in a two-dimensional scrolling grid. Items are inserted into this grid layout from a database or from an array. The adapter is used for displaying this data, setAdapter() method is used to join the adapter with GridView. The main function of th
6 min read
Kotlin Android Extensions
If youâve been developing Android Apps for some time, youâre probably already tired of working with findViewById in your day-to-day life to recover views. Or maybe you gave up and started using the famous Butterknife library. If thatâs your case, then youâll love Kotlin Android Extensions. Kotlin ha
2 min read
Android Toast in Kotlin
A Toast is a short alert message shown on the Android screen for a short interval of time. Android Toast is a short popup notification which is used to display information when we perform any operation in our app. In this tutorial, we shall not just limit ourselves by creating a lame toast but also
3 min read
How to Disable GridView Scrolling in Android?
A GridView is a ViewGroup that can display data from a list of objects or databases in a grid-like structure consisting of rows and columns. Grid view requires an adapter to fetch data from the resources. This view can be scrolled both horizontally and vertically. The scrolling ability of the GridVi
4 min read
Dynamic ImageView in Kotlin
An ImageView as the name suggests is used to display images in Android Applications. In this article, we will be discussing how to create an ImageView programmatically in Kotlin. Step by Step ImplementationStep 1: Create a new projectTo create a new project in Android Studio please refer to How to C
2 min read
Android SQLite Database in Kotlin
Android comes with an inbuilt implementation of a database package, which is SQLite, an open-source SQL database that stores data in form of text in devices. In this article, we will look at the implementation of Android SQLite in Kotlin. SQLite is a self-contained, high-reliability, embedded, full-
5 min read
Horizontal CalendarView in Android
If we are making an application that provides services such as booking flights, movie tickets, or others we generally have to implement a calendar in our application. We have to align the calendar in such a way so that it will look better and will take less amount of space in the mobile app. Most of
3 min read
CountDownTimer in Android using Kotlin
CountDownTimer app is about setting a time that moves in reverse order as it shows the time left in the upcoming event. A CountDownTimer is an accurate timer that can be used for a website or blog to display the count down to any special event, such as a birthday or anniversary. Likewise, here letâs
2 min read