Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Android Grid View

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In this blog, we will look into the Grid View of Android. GridView allows you to display items in a two-dimensional grid. We will discuss how Grid View is created and used in an android application. 

In this article, we will be using the CardView widget to display the items, so in case you are not familiar with CardView, you can check out this article.

Also, see Attributes in DBMS

Grid View

A GridView is a subclass of AdapterView that shows things in a two-dimensional scrolling grid. Grid items are not always predetermined, but using the adapter, they are automatically put into the layout. The adapter is used to display the data.

The GridView tag is used to create a Grid View in an android application.

For example,

<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"
/>

Attributes of GridView

Following are some of the important attributes of a GridView widget:

  • android:numColumns: It defines the number of columns that will be displayed in the Grid
  • android:columnWidth: Specifies the width of each column of the Grid
  • android:horizontalSpacing: It defines the amount of horizontal spacing that will be applied between neighboring elements in the Grid
  • android:verticalSpacing: It defines the amount of vertical spacing that will be applied between neighboring elements in the Grid
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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!

Topics covered
1.
Introduction
2.
Grid View
2.1.
Attributes of GridView
3.
Example
4.
FAQs
5.
Key Takeaways