GridView Using Custom ArrayAdapter in Android with Example - GeeksforGeeks

11 Apr, 2022
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 the UI elements with the data source, It helps populate data with we taking care of it. e.g when the user is scrolling a gallery app the GridView is automatically populated without specifying anything. There are different Adapters naming a few. 
ArrayAdapter 
BaseAdapter 
Custom ArrayAdapter 
This article will be covering the Custom ArrayAdapter. 
Android already provides the implementation for an ArrayAdapter, which can be used with just a single line demonstrated below. They are used when Whenever we have a list of single items we can use ArrayAdapter. For instance, a list of phone contacts, countries, or names. Below is the syntax of the ArrayAdapter used for displaying text data.
Syntax:
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)
Parameters:
Context: is the application context being used 
resource: The second parameter is resource id used to set the layout(xml file). 
textViewResourceId: Id of the TextView element where the data will be displayed 
objects: are the data elements stored in an array. 
The problem with or limitation of this method we cannot use complex layouts eg. Imagine we were building an app like Netflix or prime where each element is made up of many elements eg an ImageView, TextView, etc. Such complex views are not possible with the simple implementation of the ArrayAdapter for this we need to create our custom Adapter by extending the ArrayAdapter class. The following code shows the structure of the Custom ArrayAdapter.
Java
public class CustomAdapter extends ArrayAdapter{     public CustomAdapter(Context context, int resource, List objects)    {        super(context, resource, objects);    }    @Override public int getCount()    {        return super.getCount();    }     @Override    public View getView(int position, View convertView, ViewGroup parent)    {        return super.getView(position, convertView, parent);    }}
The two important methods used are: 
getCount(): returns the number of data elements present in the List.getView(): this is the important method where will be initializing and returning out the custom view.
getCount(): returns the number of data elements present in the List.
getView(): this is the important method where will be initializing and returning out the custom view.
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. 
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. 
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: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"    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 custom_view.xml in the same folder as the activity_main.xml file. This Custom View will host an ImageView and a TextView. 
Below is the code for the custom_view.xml file.
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"        tools:srcCompat="@tools:sample/avatars" />     <TextView        android:id="@+id/textView"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="TextView"        android:textAlignment="center" />     </LinearLayout>
Step 4: Creating a new Java class
Now to hold the info of our custom view we need to create a getter setter class. We can do things without this just using two arrays one for images and the other for text but what if we want to modify your view to add a Button. Then will again need a third array. Hence a class that holds the custom view is a more flexible option. Create the class In the same folder as the MainActivity.java create a new class called items. Below is the code for the items.java file.
Java
public class items{    private int image_id;    private String text;     public int getImage_id()    {        return image_id;    }     public void setImage_id(int image_id)    {        this.image_id = image_id;    }     public String getText()    {        return text;    }     public void setText(String text)    {        this.text = text;    }     items(int img, String text)    {        image_id = img;        this.text = text;    }}
Note: For an image, we store the id of the image and not the image.
Step 5: Implementing the CustomAdapter class
Create a new class classed as CustomAdapter.java in the same folder as items.java. The main method of the Adapter is the getView(). 
Java
@NonNull@Overridepublic View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent){    View v = convertView;    if (v == null) {               // getting reference to the main layout and        // initializing        LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);        v = inflater.inflate(custom_layout_id, null);    }     // initializing the imageview and textview      // and setting data    ImageView imageView = v.findViewById(R.id.imageView);    TextView textView = v.findViewById(R.id.textView);     // get the item using the  position param    items item = items_list.get(position);     imageView.setImageResource(item.getImage_id());    textView.setText(item.getText());    return v;}
public View inflate (int resource,ViewGroup root)
Inflate a new view hierarchy from the specified xml resource. Throws InflateException if there is an error.
resource  int: ID for an XML layout resource to load (e.g., R.layout.main_page)
root  ViewGroup: Optional view to be the parent of the generated hierarchy. This value may be null.
This method first parses out the custom_view.xml file using the inflate() method. This method is quite computationally expensive and should be used only when needed eg. when the adapter has to populate new items when the user reaches the end of the screen. After getting the reference of the view we then initialize the image view and text view from the custom_view.xml file set the data and return the view. Below is the complete code for the CustomAdapter.java file. Comments are added inside the code to understand the code in more detail.
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;import java.util.List; public class CustomAdapter extends ArrayAdapter<items> {     List<items> items_list = new ArrayList<>();    int custom_layout_id;     public CustomAdapter(@NonNull Context context, int resource, @NonNull List<items> objects) {        super(context, resource, objects);        items_list = objects;        custom_layout_id = resource;    }     @Override    public int getCount() {        return items_list.size();    }     @NonNull    @Override    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {         View v = convertView;        if (v == null) {            // getting reference to the main layout and            // initializing            LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);            v = inflater.inflate(custom_layout_id, null);        }         // initializing the imageview and textview and        // setting data        ImageView imageView = v.findViewById(R.id.imageView);        TextView textView = v.findViewById(R.id.textView);         // get the item using the  position param        items item = items_list.get(position);         imageView.setImageResource(item.getImage_id());        textView.setText(item.getText());        return v;    }}
Step 6: Working with the MainActivity.java file
For the images, here we have used android studio icons. The images are present in the res/drawable folder. Should look like this 
In the MainActivity File:
1. Initialize the items list
Java
List<items> itemsList = new ArrayList<>();itemsList.add(new items(R.drawable.android_1, "image_1"));itemsList.add(new items(R.drawable.android_2, "image_2"));itemsList.add(new items(R.drawable.android_3, "image_3"));itemsList.add(new items(R.drawable.android_4, "image_4"));itemsList.add(new items(R.drawable.android_5, "image_5"));itemsList.add(new items(R.drawable.android_1, "image_6"));itemsList.add(new items(R.drawable.android_2, "image_7"));itemsList.add(new items(R.drawable.android_3, "image_8"));itemsList.add(new items(R.drawable.android_4, "image_9"));itemsList.add(new items(R.drawable.android_5, "image_10"));
2. Get the reference of the GridView and then set the custom adapter
Java
GridView gridView = findViewById(R.id.grid_view);CustomAdapter customAdapter = new CustomAdapter(this, R.layout.custom_view, itemsList);gridView.setAdapter(customAdapter);
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;import java.util.ArrayList;import java.util.List; public class MainActivity extends AppCompatActivity {     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);         List<items> itemsList = new ArrayList<>();        itemsList.add(new items(R.drawable.android_1, "image_1"));        itemsList.add(new items(R.drawable.android_2, "image_2"));        itemsList.add(new items(R.drawable.android_3, "image_3"));        itemsList.add(new items(R.drawable.android_4, "image_4"));        itemsList.add(new items(R.drawable.android_5, "image_5"));        itemsList.add(new items(R.drawable.android_1, "image_6"));        itemsList.add(new items(R.drawable.android_2, "image_7"));        itemsList.add(new items(R.drawable.android_3, "image_8"));        itemsList.add(new items(R.drawable.android_4, "image_9"));        itemsList.add(new items(R.drawable.android_5, "image_10"));         GridView gridView = findViewById(R.id.grid_view);        CustomAdapter customAdapter = new CustomAdapter(this, R.layout.custom_view, itemsList);        gridView.setAdapter(customAdapter);    }}
rkbhola5
android
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
GridView in Android with Example
Android Listview in Java with Example
How to Change the Background Color After Clicking the Button in Android?
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java