Android GridView


Android GridView Tutorial

A gridview is an adapterview that shows items in a two-dimensional grid.

In this tutorial we cover GridView extensively then look at various usage examples.

Android GridView

These grids are scrollable. GridView is an adapterview because it works with adapters. Adapters can then bind data to the gridview.

This is important because then it means that the gridview is decoupled from it's data source. So you can customize the gridview as you like without interfering with the data source. You can also work on the data source without affecting the visual appearance of the gridview.

GridView derives from AbsListview.

public class GridView extends android.widget.AbsListView{}

Both reside in the android.widget packages.

AbsListview is an abstract class and you won't use in directly. You'll use it in case you want to implement your own custom view with unique properties.

Even the sister of GridView which is ListView also directly derives from AbsListview. So AbsListview is a base class. It's used to implement virtualized list of items. Given it's virtualized you can implement it to show lists in various forms:

  • Lists -vertical and horizontal
  • Grids
  • Carousel
  • Stack

And so on.

So in our case the gridview uses it to display items in a grid. And we call the implementation the Gridview.

Some of the typical uses of gridview include:

  • Showing image gallery.
  • Showing list of movies.
  • Showing list of products etc.

Like other views and widgets, gridview are first defined in the xml layout. This is because android views and widgets are normally defined using XML, a markup language. Though it's also possible to create the views and widgets using raw java. However, XML has several advanatges:

  1. It's easier compared to having to remember the various APIs for creating views programmatically.
  2. It's more flexible and customizable.
  3. It decouples the user interface from the application logic. This leads to maintenable code.
  4. It's more reusable. You can easily copy paste XML code from online and reuse as opposed to java code.
  5. We can use the designer to generate the XML code.

To work with XML, first we add the gridview xml definition inside our layout:

    <?xml version="1.0" encoding="utf-8"?>
    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:columnWidth="90dp"
        android:numColumns="auto_fit"
        android:verticalSpacing="10dp"
        android:horizontalSpacing="10dp"
        android:stretchMode="columnWidth"
        android:gravity="center"
    />

Then we can move to our java code and reference the gridview and set its adapter:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new MyAdapter(this));

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                Toast.makeText(HelloGridView.this, "" + position,
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

1. Populate GridView From String Array

Let's put a GridView into practice by filling it with an array of strings. We are using GridView as it is without applying a custom layout. This means that a default textview will be used to render the view items in a grid.

For that we just need an arrayadapter to allow us bind data to our gridview. Adapters are important because they act as the bridge to the data source. In our case that data source is a simple string array.

Project Structure

(a). activity_main.xml
  • This layout gets inflated to MainActivity user interface.

We add a GridView here. We've placed a header label using a TextView. We've wrapped them with a relativelayout.

Here's the full layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="info.tutorialsloop.hp.stringarraygridview.MainActivity">

    <TextView
        android:id="@+id/headerLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:fontFamily="casual"
        android:text="String[] GridView"
        android:textAllCaps="true"
        android:textSize="24sp"
        android:textStyle="bold" />

    <GridView
        android:id="@+id/myGridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:numColumns="auto_fit"
        android:layout_below="@+id/headerLabel"
        android:layout_marginTop="33dp" />

</RelativeLayout>

You can see we've assigned our GridView an id using the android:id attribute. All views require an id for identification purposes. Assigning our gridview an id as we've done above means that from our MainActivity.java we will be able to reference it via the findViewById() method.

We've also used the android:numColumns attribute, assigning it the value auto_fit. That will make our GridView flexible to adapt to the screen size and display the best number of columns based on the screen size.

4. MainActivity.java

In our MainActivity we start by adding several import statements:

Among them include:

  1. android.app.Activity - This is because our MainActivity class will inherit from the Activity class.
  2. android.widget.ArrayAdapter - This is because our gridview needs an adapter for it to work.Why? Well because it is the adapter that will supply it with data.
  3. android.widget.GridView - Our GridView. This is our adapterview. It will render our data.

We then prepared the data source, in this case our array of galaxies.

    private String[] galaxies={"Sombrero", "Cartwheel", "Pinwheel", "StarBust","Whirlpool","Ring Nebular", "Own Nebular","Centaurus A", "Virgo Stellar Stream", "Canis Majos Overdensity"
            , "Mayall's Object", "Leo","Small Magellonic Cloud", "Large Magellonic Cloud","Milky Way","Whirlpool","Black Eye Galaxy","IC 1011","Messier 81", "Andromeda", "Messier 87"};

How to Reference a GridView

We then reference our GridView, as we said, using the findViewById method.:

    GridView gv= findViewById(R.id.myGridView);

The myGridView is an id we had specified for the GridView in our XML Layout.

How to Set an Adapter to Our GridView

Well GridView itself as a class provides us the setAdapter() method. That method is supposed to take a ListAdapter object. That ListAdapter will be responsible for providing the grid's data.

void setAdapter (ListAdapter adapter)

It's role is to Set the data behind this GridView.

Here's an example:

gv.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,galaxies));

In our case we've passed our string array of galaxies as our data source. Moreover we've passed a Context object as well as the type of layout to use. android.R.layout.simple_list_item_1 will be used, which basically as a simple textview.

How to Listen To GridView Click Events.

Listening to grid click events is very important as it allows users to react to individual items in our gridview. For example user can click a gridview item then navigate to a different activity or show a Toast message.

To handle click events we use the setOnItemClickListener method.


        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, galaxies[i], Toast.LENGTH_SHORT).show();
            }
        });
package info.tutorialsloop.hp.stringarraygridview;

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

public class MainActivity extends Activity {

    GridView gv;
    private String[] galaxies={"Sombrero", "Cartwheel", "Pinwheel", "StarBust","Whirlpool","Ring Nebular", "Own Nebular","Centaurus A", "Virgo Stellar Stream", "Canis Majos Overdensity"
            , "Mayall's Object", "Leo","Small Magellonic Cloud", "Large Magellonic Cloud","Milky Way","Whirlpool","Black Eye Galaxy","IC 1011","Messier 81", "Andromeda", "Messier 87"};

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

        initializeGridView();

    }
    private void initializeGridView()
    {
        gv= findViewById(R.id.myGridView);
        gv.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,galaxies));

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, galaxies[i], Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Download

Resource Link
GitHub Browse Browse
GitHub Download Link Download

2. Android Simple GridView - Fill With List of Objects

Hello friends.Today we see how to work with a simple gridview and objects.In short here is what we do:

  1. Fill list of objects to an arraylist.
  2. Bind the list to gridview via arrayadapter.
  3. Handle ItemClick events.

Demo

Project Demo

SECTION 1 : OUR MODEL CLASS

  • Represents a single "person" object.
package com.tutorials.hp.gridviewandobjects;

public class Person {

    int id;
    String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

OUR MainActivity

package com.tutorials.hp.gridviewandobjects;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List<String> people=new ArrayList<>();

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

        //GRIDVIEW
        GridView gv= (GridView) findViewById(R.id.gv);

        //FILL LIST
        fillPeople();

        //ADAPTER
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,people);
        gv.setAdapter(adapter);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Toast.makeText(MainActivity.this, people.get(i), Toast.LENGTH_SHORT).show();

            }
        });
    }

    private void fillPeople()
    {
        people.clear();

        Person p=new Person();
        p.setName("Mike");
        people.add(p.getName());

        p=new Person();
        p.setName("John");
        people.add(p.getName());

        p=new Person();
        p.setName("Lucy");
        people.add(p.getName());

        p=new Person();
        p.setName("Rebecca");
        people.add(p.getName());

        p=new Person();
        p.setName("Kris");
        people.add(p.getName());

        p=new Person();
        p.setName("Kurt");
        people.add(p.getName());

        p=new Person();
        p.setName("Vin");
        people.add(p.getName());
    }
}

OUR LAYOUT

We add our GridView here.

<?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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.tutorials.hp.gridviewandobjects.MainActivity">

    <GridView
        android:id="@+id/gv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:numColumns="3" />
</RelativeLayout>

Download

You can download the full project here.

No. Resource Direct Links
1. GitHub Source Code Browse
2. Source Code Download
3. YouTube Channel

Top Android GridView Examples

Let's look at some examples.

Android Custom GridView - CardView With Images and Text Tutrial

How to create a custom gridview containing CardViews with text and images in android studio and listen to each CardView's Click event. We do this for both Java and Kotlin.

Android GridView CRUD tutorial.

Hello.We see how to perform basic CRUD operations against GridView.

  • We add,update and delete.
  • Our basic data source is an arraylist.
  • Our adapter is ArrayAdapter.

Android GridView - Sort - Ascending and Descending Tutorial

Lets see how to sort data in android java using Collections class.We shall sort ascending and descending in GridView when button is clicked.

Android Simple GridView pagination. How to apply next/previous type of pagination to a simple GridView.

This tutorial explores how to apply a next/previous type of pagination to a simple GridView The gridview comprises autogenerated data. Please watch the video tutorial below.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post