Example
Now that we have learned what a Grid View is. Let's learn how to code it in a program by building a basic Android application that uses Grid View.
First, we need to create a new project in Android Studio by selecting the empty activity option. Now add a Grid View to the activity_main.xml file.
activity_main.xml
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<GridView
android:id = "@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="150dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
</LinearLayout>
Create a new XML file named "card_item.xml" in the same directory as your activity_main.xml file. In a Grid View, multiple cards will be displayed, and the structure of each card is specified in the card_item.xml file.
card_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app = "http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="10dp"
app:cardPreventCornerOverlap="true"
app:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<ImageView
android:id="@+id/item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginLeft="25dp"
android:layout_marginTop="5dp"
app:srcCompat="@drawable/cn_website" >
</ImageView>
</RelativeLayout>
</androidx.cardview.widget.CardView>
Now create a new Kotlin file "Model.kt" in the same directory as the MainActivity.kt file.
Model.kt
class Model {
// Variable to store image ids
var img_id:Int ? = 0
// Constructor of the class
constructor(img_id: Int?) {
this.img_id = img_id
}
}
Create a new file ModelAdapter.kt in the same directory as the MainActivity.kt file and add an Adapter class to the file. This class will be used to add the data that will be displayed on the screen.
ModelAdapter.kt
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
// Model Adapter extends the BaseAdapter class
class ModelAdapter(var context: Context, var arrayList: ArrayList<Model>):BaseAdapter() {
// overriding getCount() method
override fun getCount(): Int {
return arrayList.size
}
// Function to fetch a particular item
override fun getItem(p0: Int): Any {
return arrayList.get(p0)
}
// Function to fetch the itemId
override fun getItemId(p0: Int): Long {
return p0.toLong()
}
// Overriding getView function
override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View {
var view: View = View.inflate(context, R.layout.card_item, null)
// Fetching the image view that was defined in the card_item.xml file
var image: ImageView = view.findViewById(R.id.item_image)
var listItem:Model = arrayList.get(p0)
image.setImageResource(listItem.img_id!!)
return view
}
}
Now, let's configure the functionalities of these widgets in the MainActivity.kt file.
MainActivity..kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.GridView
import java.util.*
import kotlin.collections.ArrayList
// Main Activity class Extending AppCompatActivity
class MainActivity : AppCompatActivity() {
// Initializing variables
private var arrayList: ArrayList<Model>? = null
private var gridView:GridView? = null
private var modelAdapter: ModelAdapter? = null
// Overriding the onCreate Function
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// fetching the gridView that was defined in the activity_main.xml file
gridView= findViewById(R.id.grid_view)
// Initialise arrayList
arrayList = ArrayList()
// Add 8 images to the arrayList
for (i in 1..8){
arrayList!!.add(Model(R.drawable.cn_website))
}
modelAdapter= ModelAdapter(applicationContext,arrayList!!)
gridView?.adapter= modelAdapter
}
}
Note: In this example, I have used an image file named "cn_website" as a parameter to the Model. To add an image to your application, you can add simply copy and paste your image file to the res/drawable directory.
Output:
This is the output you will get upon following the above instructions. As you can see, the grid has two columns, and there are a total of eight pictures in the application.

FAQs
1. What is the purpose of the Adapter in GridView?
Its primary role is to retrieve data from an array and insert each piece of data into the proper item for display in GridView.
2. What is the difference between a ListView and GridView?
The primary distinction between a ListView and a GridView is how the data is displayed. The children of a ListView are shown either horizontally or vertically. But the data of GridView is displayed in a two-dimensional grid.
3. What is the use of android:stretchMode in a GridView?
It specifies how columns should stretch to consume the free space.
Key Takeaways
In this article, we have extensively discussed the Grid View in Android and its implementation in Android Studio. We discussed how Grid View could be created and used in an android application.
We hope that this blog has helped you enhance your knowledge regarding Grid View. All the widgets are enclosed inside a UI layout and if you would like to learn more about layouts, check out our article on Android UI layouts. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website. Do upvote our blog to help other ninjas grow. Happy Coding!