GridView in Android With Example

GridView-in-Android-With-Example.png

27th February, 2024

Hi, today we are going to learn another view container which displays items in two dimensions.

1. What is GridView?

Android GridView is an android view container used to display items in the Grid. Android GridView is commonly used to display collections such as images, videos. Think of a gallery app on your phone that displays images/photos in a grid list. The Data for the GridView is provided by the adapter.

Android-GridView-Sample.png
Android GridView

We need learn two things: GridView Item and GridView Adapter

2. GridView Items

A GridView is made from collection of individual Grid Items. In other words, a GridView Item is a unit of a GridView. See the image below which shows a GridView Items from a GridView.

A GridView Item can be created with a single view like a TextView or with multiple views.

GridView-Item-Android-GridView.png

3. Android Adapters (GridView Adapters)

Android adapter is used to fill the data in the GridView. Android adapter acts as a bridge between the views (e.g. ListView, GridView) and data. We can use the adapter through the setAdapter() method. See the image below which shows the function of the Android Adapter.

Android-Adapter-for-ListView.png

3.1 Android Adapters used for GridView

Value Description
ArrayAdapter It is used to display ListView, GridView with simple Item element. Item can be created from TextView, CheckBox etc.
CursorAdapter CursorAdapter is used to display data by cursor instance when we have to display data from database.
SimpleAdapter SimpleAdapter is used to display static data defined in XML.
BaseAdapter BaseAdapter is common adapter used in ListView, GridView, Spinner, etc. It is a generic implementation of all the above adapters.

4. Create Android GridView using Android Studio

4.1 Create/Add GridView in XML layout file

Open the XML layout file in Android Studio, select GridView from the palette and add it to the layout.

Add-GridView-in-Android-App-using-android-Studio.gif

See the following code:

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Androidchunk!" />

    <GridView
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

4.2 Create GridView Programmatically in Android

Programmatically: You can also add GridView to your app programmatically by creating a new instance of the GridView class and setting its properties:

KotlinJava
content_copy light_mode remove
package com.androidchunk.hellogridview

import android.os.Bundle
import android.widget.GridView
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // create new GridView instance
        val gridView = GridView(this)
        //----set attributes---//
        // set number of columns
        gridView.numColumns = 4
        // set padding
        gridView.setPadding(16, 16, 16, 16)
        // set horizontal spacing between items
        gridView.horizontalSpacing = 8
        // set vertical spacing between items
        gridView.verticalSpacing = 8

        // create new adapter instance
        val adapter = MyAdapter(this, data)
        // set adapter on GridView
        gridView.adapter = adapter

        // get parent layout
        val parentLayout = findViewById<RelativeLayout>(R.id.parent)
        // add GridView to parent layout
        layout.addView(gridView)
    }
}
package com.androidchunk.hellogridview;

import android.os.Bundle;
import android.widget.GridView;
import android.widget.RelativeLayout;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // create new GridView instance
        GridView gridView = new GridView(this);
        //----set attributes---//
        // set number of columns
        gridView.setNumColumns(4);
        // set padding
        gridView.setPadding(16, 16, 16, 16);
        // set horizontal spacing between items
        gridView.setHorizontalSpacing(8);
        // set vertical spacing between items
        gridView.setVerticalSpacing(8);

        // create new adapter instance
        MyAdapter adapter = new MyAdapter(this, data);
        // set adapter on GridView
        gridView.setAdapter(adapter);

        // get parent layout
        RelativeLayout parentLayout = findViewById(R.id.parent);
        // add GridView to parent layout
        layout.addView(gridView);
    }
}

5. Android GridView Attributes

Attribute Description
android:verticalSpacing It is used to define the space between two rows of the GridView
android:horizontalSpacing It is used to define the space between two columns of the GridView
android:numColumns The number of columns of the gridview
android:stretchMode It is used to define how columns should stretch to fill the space if available. values: columnWidth, none, spacingWidth, spacingWidthUniform

6. Android GridView Examples

6.1 Simple Android GridView with ArrayAdapter Example

In this example we will create a simple Android GridView using ArrayAdapter.

Step 6.1.1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 6.1.2: Add GridView to the XML Layout (UI)

Open the xml layout file and add a GridView from the palette. See the code below.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myGridView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FFFFFF"
    android:horizontalSpacing="30dp"
    android:numColumns="auto_fit"
    android:padding="10dp"
    android:stretchMode="columnWidth"
    android:verticalSpacing="30dp"
    tools:context=".MainActivity" />

Step 6.1.3: Update Activity File

Open the activity file and create an instance of GridView. Create an instance of arrayAdapter and set it to the GridView.

KotlinJava
content_copy light_mode remove
package com.androidchunk.hellogridview

import android.os.Bundle
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    //data
    private val countries = arrayOf(
        "Switzerland", "Canada", "India", "United States", "Germany",
        "Sweden", "Japan", "Australia", "United Kingdom", "New Zealand", "Sweden",
        "China", "France", "Brazil", "Russia", "Spain", "United Arab Emirates"
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Array adapter
        val arrayAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, countries)

        //instance of GridView
        val aGridView = findViewById<GridView>(R.id.myGridView)

        //set the arrayAdapter to the GridView
        aGridView.adapter = arrayAdapter

        //GridView click listener
        aGridView.onItemClickListener =
            OnItemClickListener { adapterView, view, position, id ->
                Toast.makeText(this@MainActivity, countries[position], Toast.LENGTH_SHORT).show()
            }
    }
}
package com.androidchunk.hellogridview;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

class MainActivity extends AppCompatActivity {
    //data
    private String[] countries = new String[]
            {"Switzerland", "Canada", "India", "United States", "Germany",
                    "Sweden", "Japan", "Australia", "United Kingdom", "New Zealand", "Sweden",
                    "China", "France", "Brazil", "Russia", "Spain", "United Arab Emirates"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Array adapter
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countries);

        //instance of GridView
        GridView aListView = findViewById(R.id.myGridView);

        //set the arrayAdapter to the GridView
        aListView.setAdapter(arrayAdapter);

        //ListView click listener
        aListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Toast.makeText(MainActivity.this, countries[position], Toast.LENGTH_SHORT).show();
            }
        });
    }
}

The parameters of the ArrayAdapter constructor that we used to create an instance of ArrayAdapter are explained below.

Android-GridView-ArrayAdapter-constructor-parameter.png

Run the application and check the output.

Step 6.1.4: Output

6.2 Simple Android GridView Example using BaseAdapter

In this example we will create a simple Android GridView using BaseAdapter. We will display the list of countries with their name, flag, currency etc. Let’s start.

Step 6.2.1: Create New Project

Create a new project in Android Studio from File ⇒ New Project and select Empty Activity from the templates.

Step 6.2.2: Add GridView Item Layout

A GridView Item is a unit of the GridView, So first we will create a XML layout file for the GridView item.

We have taken three TextViews Country name, currency, calling code respectively . We also want an ImageView to display the flag. Check the code below.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FFFFFF"
    android:orientation="vertical"
    android:padding="8dp">

    <ImageView
        android:id="@+id/flagImageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:src="@android:drawable/ic_menu_gallery" />

    <TextView
        android:id="@+id/nameTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name"
        android:textColor="#FF2C6F"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/currencyTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="currency" />

    <TextView
        android:id="@+id/callingCodeTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="calling code" />
</LinearLayout>

Step 6.2.3: Copy Image Resources (optional)

Now download the following images and add them to the drawable folder of the project.

Add-flags-to-drawable-folder.png

Step 6.2.4: Add GridView to the XML Layout (UI)

Open the Activity’s xml layout file and add a GridView from the palette.

XML
content_copy light_mode remove
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myGridView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F5F5F5"
    android:horizontalSpacing="30dp"
    android:numColumns="auto_fit"
    android:padding="10dp"
    android:stretchMode="columnWidth"
    android:verticalSpacing="30dp"
    tools:context=".MainActivity" />

Step 6.2.5: Create a Model Class

To display data in the GridView we have created a simple model class that helps in setting and getting country data. Model class make it easy to manage data. Let’s create one.

Open the project tool window by clicking on the project option from the Tool window bar. After that select the Android option from the drop-down and open the app → java hierarchy.

Right click on the package name and select New → Kotlin or Java class.

KotlinJava
content_copy light_mode remove
package com.androidchunk.hellogridview

data class Country(val name: String, val flag: Int, val currency: String, val callingCode: String)
package com.androidchunk.hellogridview;

class Country {
   private String name;
   private int flag;
   private String currency;
   private String callingCode;

   public Country(String name, int flag, String currency, String callingCode) {
      this.name = name;
      this.flag = flag;
      this.currency = currency;
      this.callingCode = callingCode;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getFlag() {
      return flag;
   }
   public void setFlag(int flag) {
      this.flag = flag;
   }
   public String getCurrency() {
      return currency;
   }
   public void setCurrency(String currency) {
      this.currency = currency;
   }
   public String getCallingCode() {
      return callingCode;
   }
   public void setCallingCode(String callingCode) {
      this.callingCode = callingCode;
   }
}

Step 6.2.6: Create a Custom Adapter Class

We learned above that the Android Adapter is the bridge between the views (e.g. ListView, GridView) and data. Let’s create one.

Right click on the package name and select New → Kotlin or Java class.
Add the following code.

KotlinJava
content_copy light_mode remove
package com.androidchunk.hellogridview

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView


class MyBaseAdapter(val context: Context, val data: ArrayList<Country>?) : BaseAdapter() {

    override fun getCount(): Int {
        return data?.size ?: 0
    }

    override fun getItem(position: Int): Any? {
        if (data != null)
            return data[position]
        else
            return null
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, viewGroup: ViewGroup?): View? {
        var convertView = convertView
        val holder: MyBaseAdapter.MyViewHolder
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_layout, null, false)
            holder = MyBaseAdapter.MyViewHolder()
            holder.flagIV = convertView!!.findViewById(R.id.flagImageView)
            holder.nameTV = convertView.findViewById(R.id.nameTextView)
            holder.currencyTV = convertView.findViewById(R.id.currencyTextView)
            holder.callingCodeTV = convertView.findViewById(R.id.callingCodeTextView)
            convertView.setTag(holder)
        } else {
            holder = convertView.tag as MyBaseAdapter.MyViewHolder
        }
        holder.flagIV!!.setImageResource(data!![position].flag)
        holder.nameTV!!.text = data[position].name
        val currencyStr = "Currency: " + data[position].currency
        holder.currencyTV!!.text = currencyStr
        val callingCodeStr = "Calling code: " + data[position].callingCode
        holder.callingCodeTV!!.text = callingCodeStr
        return convertView
    }

    private class MyViewHolder {
        var flagIV: ImageView? = null
        var nameTV: TextView? = null
        var currencyTV: TextView? = null
        var callingCodeTV: TextView? = null
    }
}
package com.androidchunk.hellogridview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

class MyBaseAdapter extends BaseAdapter {
    private final Context context;
    private final ArrayList<Country> data;

    public MyBaseAdapter(Context context, ArrayList<Country> countryData) {
        this.context = context;
        this.data = countryData;
    }

    @Override
    public int getCount() {
        if (data != null) {
            return data.size();
        }
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (data != null) {
            return data.get(position);
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup viewGroup) {
        MyViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_layout, null, false);

            holder = new MyViewHolder();

            holder.flagIV = convertView.findViewById(R.id.flagImageView);
            holder.nameTV = convertView.findViewById(R.id.nameTextView);
            holder.currencyTV = convertView.findViewById(R.id.currencyTextView);
            holder.callingCodeTV = convertView.findViewById(R.id.callingCodeTextView);

            convertView.setTag(holder);
        } else {
            holder = (MyViewHolder) convertView.getTag();
        }

        holder.flagIV.setImageResource(data.get(position).getFlag());

        holder.nameTV.setText(data.get(position).getName());

        String currencyStr = "Currency: " + data.get(position).getCurrency();
        holder.currencyTV.setText(currencyStr);

        String callingCodeStr = "Calling code: " + data.get(position).getCallingCode();
        holder.callingCodeTV.setText(callingCodeStr);

        return convertView;
    }

    private static class MyViewHolder {
        ImageView flagIV;
        TextView nameTV;
        TextView currencyTV;
        TextView callingCodeTV;
    }
}

Step 6.2.7: Update Activity File

Open the Activity Kotlin/Java file and modify it as follows.

KotlinJava
content_copy light_mode remove
package com.androidchunk.hellogridview

import android.os.Bundle
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //create a list
        val countryData = ArrayList<Country>()
        //add data to the list
        countryData.add(Country("Australia", R.drawable.au, "Australian Dollar", "+61"))
        countryData.add(Country("Germany", R.drawable.de, "Euro", "+49"))
        countryData.add(Country("India", R.drawable.`in`, "Indian Rupee", "+91"))
        countryData.add(Country("United States", R.drawable.us, "United States Dollar", "+1"))
        countryData.add(Country("New Zealand", R.drawable.nz, "New Zealand Dollar", "+64"))
        countryData.add(Country("Russia", R.drawable.ru, "Russian Ruble", "+7"))

        //instance of custom adapter
        val arrayAdapter = MyBaseAdapter(this, countryData)

        //instance of gridView
        val gridView = findViewById<GridView>(R.id.myGridView)

        //set the adapter to the gridView
        gridView.adapter = arrayAdapter


        //gridView click listener
        gridView.onItemClickListener =
            OnItemClickListener { adapterView, view, position, id ->
                val obj = gridView.getItemAtPosition(position)
                if (obj != null) {
                    val (name) = obj as Country
                    Toast.makeText(this@MainActivity, name, Toast.LENGTH_SHORT).show()
                }
            }
    }
}
package com.androidchunk.hellogridview;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //create a list
        ArrayList<Country> countryData = new ArrayList<>();
        //add data to the list
        countryData.add(new Country("Australia", R.drawable.au, "Australian Dollar", "+61"));
        countryData.add(new Country("Germany", R.drawable.de, "Euro", "+49"));
        countryData.add(new Country("India", R.drawable.in, "Indian Rupee", "+91"));
        countryData.add(new Country("United States", R.drawable.us, "United States Dollar", "+1"));
        countryData.add(new Country("New Zealand", R.drawable.nz, "New Zealand Dollar", "+64"));
        countryData.add(new Country("Russia", R.drawable.ru, "Russian Ruble", "+7"));

        //instance of custom adapter
        MyBaseAdapter arrayAdapter = new MyBaseAdapter(this, countryData);

        //instance of gridView
        GridView gridView = findViewById(R.id.myGridView);

        //set the adapter to the gridView
        gridView.setAdapter(arrayAdapter);

        //gridView click listener
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Object obj = gridView.getItemAtPosition(position);
                if (obj != null) {
                    Country country = (Country) obj;
                    Toast.makeText(MainActivity.this, country.getName(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Run the application and check the output.

Step 6.2.8: Output

Happy coding!

Leave a Reply