Android GridView Example

Filed Under: Android

Android GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. In this tutorial, we will build an image gallery using Android GridView.

Android GridView

Android GridView layout in one of the most useful layouts in android. GridView is mainly useful when we want show data in grid layout like displaying images or icons. This layout can be used to build applications like image viewer, audio or video players in order to show elements in grid manner.

GridView elements are not generally predefined and the data can be inserted into the layout using Adapters like ListAdapter etc. We can control the number of columns, their width, and relevant spacing.

Android GridView Attributes

  • android:id : This is the ID which uniquely identifies the layout
  • android:columnWidth : This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm
  • android:gravity : Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc.
  • android:horizontalSpacing : Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or mm
  • android:numColumns : Defines how many columns to show. May be an integer value, such as “100” or auto_fit which means display as many columns as possible to fill the available space
  • android:stretchMode : Defines how columns should stretch to fill the available empty space, if any. This must be either of the values :
    • none : Stretching is disabled
    • spacingWidth : The spacing between each column is stretched
    • columnWidth : Each column is stretched equally
    • spacingWidthUniform : The spacing between each column is uniformly stretched
  • android:verticalSpacing : Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm

Android GridView Layout

The layout for GridView is defined as follows:
layout_grid.xml


<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="50dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

</GridView>

Android GridView Example Project Structure

android GridView example

This activity consists of two Activities and their layouts, an Adapter class and a list of drawables taken from here.

Android GridView Example Code

The Application launches into the GridViewActivity class given below :


package com.journaldev.gridlayout;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class GridViewActivity extends AppCompatActivity {

    GridView gridView;

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

        gridView = (GridView) findViewById(R.id.gridView);

        gridView.setAdapter(new ImageAdapter(this));

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id){
                // Send intent to SingleViewActivity
                Intent i = new Intent(getApplicationContext(), FullViewActivity.class);

                // Pass image index
                i.putExtra("id", position);
                startActivity(i);
            }
        });
    }

}

The FullViewActivity is passed the respective positions of the ImageView clicked.

The ImageAdapter class is used to a implement the functionality of an Adapter to fill the view from the drawable resources as shown below.


package com.journaldev.gridlayout;

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

public class ImageAdapter extends BaseAdapter {
    private Context mContext;

    // Constructor
    public ImageAdapter(Context c) {
        mContext = c;
    }

    public int getCount() {
        return mThumbIds.length;
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;

        if (convertView == null) {
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        }
        else
        {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    // Keep all Images in array
    public Integer[] mThumbIds = {
            R.drawable.rotation_3d, R.drawable.alarm,
            R.drawable.classed, R.drawable.explore,
            R.drawable.giftcard, R.drawable.http,
            R.drawable.thumbs_up, R.drawable.account, R.drawable.language,
            R.drawable.lock, R.drawable.print,
            R.drawable.redeem, R.drawable.spellcheck,
            R.drawable.settings
    };
}

In the above code the layout of the ImageView is set programmatically using setLayoutParams(). The drawable resource ids are stored in an Integer array which is set to the respective position using setImageResource().


package com.journaldev.gridlayout;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

public class FullViewActivity extends AppCompatActivity {

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

        // Get intent data
        Intent i = getIntent();

        // Selected image id
        int position = i.getExtras().getInt("id");
        ImageAdapter imageAdapter = new ImageAdapter(this);

        ImageView imageView = (ImageView) findViewById(R.id.SingleView);
        imageView.setImageResource(imageAdapter.mThumbIds[position]);
    }

}

The layout of FullViewActivity is defined as follows:

full_view.xml


<?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="match_parent"
    android:orientation="vertical" >

    <ImageView android:id="@+id/SingleView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout>

Here is the final app in full action.
android gridview example, android grid layout example

This brings an end to android GridView tutorial. You can download the final android GridView example project from the below link.

Comments

  1. David Choi says:

    Hi, it was very helpful for me to know a grid view and I have a question to you.

    Could you show me how to get all images in ‘drawable’ folder?

    I mean, I avoid to write all image file names in array.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages