Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
GridView Using BaseAdapter in Android with Example
Next article icon

GridView Using BaseAdapter in Android with Example

Last Updated : 07 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here, we are designing an Android app to demonstrate the use of GridView layout. The GridView layout is a ViewGroup that groups view in a two-dimensional scrolling grid of rows and columns. Items in the grid view are inserted using a ListAdapter. The layout by default is scrollable and we don't need to use ScrollView.

An example of GridView is your default Gallery.

Attributes of a GridView

Attributes

Description

idLike all other views, android uses the id element to uniquely identify an element.
numColumnsThe number of columns to display. It can be an integer or auto_fit which will display as many possible columns to fill the screen of the device. If they don't specify this attribute then the grid view will behave like a listview.
horizontalSpacinghorizontalSpacing property is used to define the default horizontal spacing between columns. This could be in pixel(px), density pixel(dp), or scale-independent pixel(sp).
verticalSpacingThe vertical spacing property is used to define the default vertical spacing between rows. This should be in px, dp or sp.

GridView Example Using Different Adapters in Android

An Adapter is a connection between the UI components(TextView, ImageView) and the data source. An adapter helps fill the UI element with the appropriate data. In Android commonly used adapters that fill data in GridView are:

  1. ArrayAdapter
  2. BaseAdapter
  3. Custom ArrayAdapter

This tutorial will be using the BaseAdapter, following is the structure of the class that extends the base adapter. 

Java
public class MyAdapter extends BaseAdapter {     @Override public int getCount() {       return 0;     }        @Override public Object getItem(int i) {       return null;     }        @Override public long getItemId(int i) {       return 0;     }        @Override     public View getView(int i, View view, ViewGroup viewGroup) {         return null;     } } 

Method Description: 

  • getCount(): this method returns the count of the total elements to be displayed.
  • getItem(int i): this method takes in an index and returns an object.
  • getItemId(int i): this method takes in an index and returns the id of the item being displayed in the GridView.
  • getView(int I, View view, ViewGroup group): this is the most important method which returns a view that is displayed in the grid view. The int i is the index, the view can be (ImageView or TextView), and the view group is the container that hosts the View e.g LinearLayout, RelativeLayout, etc.

Example

A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this application in both Java and Kotlin Programming Languages for Android.

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. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the activity_main.xml file

Open the activity_main.xml file and insert a GridView component in it. The Layout will look blank initially but will be inflated by the custom adapter class during runtime. 

gfg_screenshot1
Step 2


activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/ImageGrid"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity">      <GridView         android:id="@+id/grid_view"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:horizontalSpacing="10dp"         android:numColumns="auto_fit"         android:verticalSpacing="10dp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> 

Step 3: Creating a new layout XML file 

Creating a new file named grid_layout.xml in the same folder as the activity_main.xml file. This Custom View will host an ImageView. The main reason to use custom adapters is to display complex views in the GridView or ListView instead of some simple text. The custom view is named grid_layout.xml with the LinearLayout as its root and a simple ImageView.

gfg_screenshot2
Step 3


grid_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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"     android:orientation="vertical">      <ImageView         android:id="@+id/imageView"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:scaleType="center"         tools:srcCompat="@tools:sample/avatars" /> </LinearLayout> 

Step 4: Creating a Custom Adapter class 

Will name this class MyBaseAdapter which will extend BaseAdapter class and inherit the methods shown above. The main method we need to walk through is the getView method. 

@Override public View getView(int i, View view, ViewGroup viewGroup)  {     if (view == null) {         LayoutInflater inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);         view = inflater.inflate(R.layout.grid_layout, viewGroup);     }          ImageView imageView = view.findViewById(R.id.imageView);     imageView.setImageResource(items[i]);     return view; }


The LayoutInflator is what is responsible for parsing our custom grid_layout.xml file.  do note that this operation is expensive and should only be performed when needed. hence its place inside an if statement. Finally, we get a reference to the layout and store it in the view variable. then using that we can initialize the image view and set the image and return the view. In this example, the view shown is quite simple but we can have a more complete view like displaying the id of a person who can have a custom view of the Image, TextView, etc.

The entire code of the MyBaseAdapter is given below.

Java
import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView;  public class MyBaseAdapter extends BaseAdapter {     Context c;     int items[];      MyBaseAdapter(Context c, int arr[]) {         this.c = c;         items = arr;     }      @Override public int getCount() { return items.length; }      @Override public Object getItem(int i) { return null; }      @Override public long getItemId(int i) { return 0; }      @Override     public View getView(int i, View view,ViewGroup viewGroup) {         if (view == null) {             LayoutInflater inflater = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);             view = inflater.inflate(R.layout.grid_layout, null);         }         ImageView imageView = view.findViewById(R.id.imageView);         imageView.setImageResource(items[i]);         return view;     } } 
Kotlin
import android.content.Context import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView  class MyBaseAdapter internal constructor(var c: Context, var items: IntArray) :     BaseAdapter() {     override fun getCount(): Int {         return items.size     }      override fun getItem(i: Int): Any? {         return null     }      override fun getItemId(i: Int): Long {         return 0     }      override fun getView(i: Int, view: View, viewGroup: ViewGroup): View {         val view = view         val imageView = view.findViewById<ImageView>(R.id.imageView)         imageView.setImageResource(items[i])         return view     } } 

Step 5: Working with the MainActivity file

The data will use using images of different android studio logos saved in the drawable folder. 


To use these images we need to store them in an array and pass it to the custom adapter.

Java: int[] itemsarray = new int[] {     R.drawable.android_1, R.drawable.android_2,     R.drawable.android_3, R.drawable.android_4,     R.drawable.android_5, R.drawable.android_1,     R.drawable.android_2, R.drawable.android_3,     R.drawable.android_4, R.drawable.android_5 };  Kotlin: var itemsarray = intArrayOf(     R.drawable.android_1, R.drawable.android_2,     R.drawable.android_3, R.drawable.android_4,     R.drawable.android_5, R.drawable.android_1,     R.drawable.android_2, R.drawable.android_3,     R.drawable.android_4, R.drawable.android_5 )

Notice that the same 5 images are repeated. Now setting up the custom base adapter in the MainActivity file.

GridView gridView = findViewById(R.id.grid_view);  // create a object of myBaseAdapter MyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray); gridView.setAdapter(baseAdapter);

First, we get a reference of the grid layout from the XML file using the fineViewById() method, then we create the object of myBaseAdapter which takes two arguments Context, and the items array. Finally, we set the adapter. Below is the complete code for the MainActivity file. Comments are added inside the code to understand the code in more detail.

Java
import android.os.Bundle; import android.widget.GridView; import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {      int[] itemsarray = new int[] {         R.drawable.android_1, R.drawable.android_2,         R.drawable.android_3, R.drawable.android_4,         R.drawable.android_5, R.drawable.android_1,         R.drawable.android_2, R.drawable.android_3,         R.drawable.android_4, R.drawable.android_5     };      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          GridView gridView = findViewById(R.id.grid_view);          // create a object of myBaseAdapter         MyBaseAdapter baseAdapter = new MyBaseAdapter(this, itemsarray);         gridView.setAdapter(baseAdapter);     } } 
Kotlin
import android.os.Bundle import android.widget.GridView import androidx.appcompat.app.AppCompatActivity  class MainActivity : AppCompatActivity() {     var itemsarray = intArrayOf(         R.drawable.android_1, R.drawable.android_2,         R.drawable.android_3, R.drawable.android_4,         R.drawable.android_5, R.drawable.android_1,         R.drawable.android_2, R.drawable.android_3,         R.drawable.android_4, R.drawable.android_5     )      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)         val gridView = findViewById<GridView>(R.id.grid_view)          // create a object of myBaseAdapter         val baseAdapter = MyBaseAdapter(this, itemsarray)         gridView.adapter = baseAdapter     } } 

Output:


Next Article
GridView Using BaseAdapter in Android with Example

C

clivefernandes777
Improve
Article Tags :
  • Java
  • Kotlin
  • Android
  • Android-View
Practice Tags :
  • Java

Similar Reads

    GridView Using Custom ArrayAdapter in Android with Example
    This article will be building an application to demonstrate the use of CustomArrayAdapters in GridView. GridViews are view containers that display views in two-dimensional (rows and columns) they are used in my android applications one simple example would be the gallery app. The adapter connects th
    8 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
    5 min read
    Staggered GridView in Android with Example
    StaggeredGridLayout is a LayoutManager in the Android studio similar to GridView, but in StaggeredGridLayout each grid has its own height and width.Difference Between GridView and Staggered GridViewStaggeredGridlayoutThe children are in a staggered grid format.It supports horizontal and vertical lay
    4 min read
    ArrayAdapter in Android with Example
    The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is
    3 min read
    BaseExpandableListAdapter in Android with Example
    The BaseExpandableListAdapter in Android is an abstract class used to create custom adapters for ExpandableListView, which displays a list of grouped items that can be expanded or collapsed. It provides methods to manage group and child views, define the count of groups and their children, and bind
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences