GridView in Android with Example

06 Sep, 2021
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 the adapter in GridView is to fetch data from a database or array and insert each piece of data in an appropriate item that will be displayed in GridView. This is how the GridView structure looks like. Note that we are going to implement this project using the Java language. 
android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid.
android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView.
android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView.
Now let us see an example in which we will implement a simple GridView in Android App. In the GridView, we are now displaying the list of courses available on GeeksforGeeks.  
Step 1: Creating a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Add google repository in the build.gradle file of the application project.
buildscript {
 repositories {
    google()
    mavenCentral()
}
All Jetpack components are available in the Google Maven repository, include them in the build.gradle file
allprojects {
 repositories {
    google()
   mavenCentral()
 }
}
Step 3: Modify the activity_main.xml file
Add GridView to the activity_main.xml file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout    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">     <!-- android:numColumns=2 is the number of columns for Grid View         android:horizontalSpacing is the space between horizontal         grid items.-->    <GridView        android:id="@+id/idGVcourses"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:horizontalSpacing="6dp"        android:numColumns="2"        android:verticalSpacing="6dp" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: 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 card_item. Below is the code for the card_item.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!--XML implementation of Card Layout--><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="120dp"    android:layout_gravity="center"    android:layout_margin="5dp"    app:cardCornerRadius="5dp"    app:cardElevation="5dp">     <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical">         <ImageView            android:id="@+id/idIVcourse"            android:layout_width="100dp"            android:layout_height="100dp"            android:layout_gravity="center"            android:src="@mipmap/ic_launcher" />         <TextView            android:id="@+id/idTVCourse"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:text="@string/app_name"            android:textAlignment="center" />     </LinearLayout> </androidx.cardview.widget.CardView>
Step 5: Create a Modal Class for storing Data
Modal Class is the JAVA Class that handles data to be added in each GridView item of GridView. For Creating Modal Class. 
Now click on app > java > apps package name > Right-Click on it.
Then Click on New > Java Class.
Name your Java Class file as CourseModel. Below is the code for the CourseModel.java file.
Java
public class CourseModel {     // string course_name for storing course_name    // and imgid for storing image id.    private String course_name;    private int imgid;     public CourseModel(String course_name, int imgid) {        this.course_name = course_name;        this.imgid = imgid;    }     public String getCourse_name() {        return course_name;    }     public void setCourse_name(String course_name) {        this.course_name = course_name;    }     public int getImgid() {        return imgid;    }     public void setImgid(int imgid) {        this.imgid = imgid;    }}
Step 6: Create an 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.
Now click on app > java > apps package name > Right-Click on it.
Then Click on New > Java Class.
Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter.java file. 
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ArrayAdapter;import android.widget.ImageView;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import java.util.ArrayList; public class CourseGVAdapter extends ArrayAdapter<CourseModel> {    public CourseGVAdapter(@NonNull Context context, ArrayList<CourseModel> courseModelArrayList) {        super(context, 0, courseModelArrayList);    }     @NonNull    @Override    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {        View listitemView = convertView;        if (listitemView == null) {            // Layout Inflater inflates each item to be displayed in GridView.            listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false);        }        CourseModel courseModel = getItem(position);        TextView courseTV = listitemView.findViewById(R.id.idTVCourse);        ImageView courseIV = listitemView.findViewById(R.id.idIVcourse);        courseTV.setText(courseModel.getCourse_name());        courseIV.setImageResource(courseModel.getImgid());        return listitemView;    }}
Step 7: Modify the MainActivity.java file 
Now in this file, we will perform all backend operations that will be adding data to GridView. Below is the code for the MainActivity.java file.
Java
import android.os.Bundle;import android.widget.GridView;import androidx.appcompat.app.AppCompatActivity;import java.util.ArrayList; public class MainActivity extends AppCompatActivity {     GridView coursesGV;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);               coursesGV = findViewById(R.id.idGVcourses);               ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>();        courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo));        courseModelArrayList.add(new CourseModel("JAVA", R.drawable.ic_gfglogo));        courseModelArrayList.add(new CourseModel("C++", R.drawable.ic_gfglogo));        courseModelArrayList.add(new CourseModel("Python", R.drawable.ic_gfglogo));        courseModelArrayList.add(new CourseModel("Javascript", R.drawable.ic_gfglogo));        courseModelArrayList.add(new CourseModel("DSA", R.drawable.ic_gfglogo));         CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList);        coursesGV.setAdapter(adapter);    }}
Output:
hemantjain99
android
Android-View
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android SDK and it's Components
Android RecyclerView in Kotlin
Android Project folder Structure
Broadcast Receiver in Android With Example
Navigation Drawer in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java