Skip to content
Related Articles

Related Articles

GridView Using BaseAdapter in Android with Example
  • Last Updated : 29 Oct, 2020

Here, we are designing an android app to demonstrate the use of GridView layout. The GridView layout is a ViewGroup that is group views 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.
numColumns

The 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.

horizontalSpacing

horizontalSpacing 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).

verticalSpacing

Vertical spacing property 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 eg (TextView, ImageView,) and data source. An adapter helps fill the UI element with the appropriate data. In android commonly used adapters which 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 which 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 project using the Java language. 

GridView Using Base Adapter in Android

Step by Step Implementation

Step 1: Create 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: 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. 

Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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:numColumns="auto_fit"
        android:horizontalSpacing="10dp"
        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 as grid_layout.xml with the LinearLayout as its root and a simple ImageView.

Below is the code for the grid_layout.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    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. 

Java




@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 completed 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.java 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;
    }
}

Step 5: Working with the MainActivity.java file

The data will use using are 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
};

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

Java




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.java 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);
    }
}

Output

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
My Personal Notes arrow_drop_up
Recommended Articles
Page :