Android Gridview Example- Building Image Gallery in android

Share on Google+694Tweet about this on Twitter137Share on Facebook408Share on LinkedIn2

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid. In this tutorial, we’ll build an Image Gallery using a GridView in android. Each grid to display an image thumbnails and a text. While an item is selected, a toast message will display the position of the grid selected.

custom grid view example

1. Creating GridView Layout

To begin with, let us add an GridView in our main layout. If you look at the code sample below, I have added GridView with id gridView, and applied the layout attributes. Most of the android attributes are self explanatory.

MainActivity.java

<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:background="#f0f0f0"
    tools:context=".MainActivity" >

    <GridView
        android:id="@+id/gridView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:columnWidth="100dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:verticalSpacing="5dp"
        android:drawSelectorOnTop="true"
        android:stretchMode="columnWidth" >
    </GridView>

</RelativeLayout>

2. Creating Custom Grid layout

If you look at the image below, my GridView is consists of an ImageView and an TextView. Here let us define the layout for one row. This layout will be intern used by the GridView adapter. Create row_grid.xml inside your project layout folder.

row_grid.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:orientation="vertical"
    android:padding="5dp" 
    android:clickable="true"
    android:background="@drawable/grid_color_selector"
    android:focusable="true">

    <ImageView
        android:id="@+id/image"
        android:layout_width="100dp"
        android:layout_height="100dp" >
    </ImageView>

    <TextView
        android:id="@+id/text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:textSize="12sp" >
    </TextView>

</LinearLayout>

3. Custom GridView Adapter

Create a new class called GridViewAdapter that extends ArrayAdapter. This adapter will be used by GridView in order to render its contents. The getView() method implementation is necessary is. This method creates a new View for each image added to the GridViewAdapter. When this is called, a View is passed in, which is normally a recycled object, so there’s a check to see if the object is null. If it is null, an ViewHolder is instantiated and configured for holding an ImageView and a TextView. ViewHolder design patterns are efficient while using composite layouts.

GridViewAdapter.java

import java.util.ArrayList;
import android.app.Activity;
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;
/**
 * 
 * @author javatechig {@link http://javatechig.com}
 * 
 */
public class GridViewAdapter extends ArrayAdapter {
	private Context context;
	private int layoutResourceId;
	private ArrayList data = new ArrayList();

	public GridViewAdapter(Context context, int layoutResourceId,
			ArrayList data) {
		super(context, layoutResourceId, data);
		this.layoutResourceId = layoutResourceId;
		this.context = context;
		this.data = data;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		ViewHolder holder = null;

		if (row == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			row = inflater.inflate(layoutResourceId, parent, false);
			holder = new ViewHolder();
			holder.imageTitle = (TextView) row.findViewById(R.id.text);
			holder.image = (ImageView) row.findViewById(R.id.image);
			row.setTag(holder);
		} else {
			holder = (ViewHolder) row.getTag();
		}

		ImageItem item = data.get(position);
		holder.imageTitle.setText(item.getTitle());
		holder.image.setImageBitmap(item.getImage());
		return row;
	}

	static class ViewHolder {
		TextView imageTitle;
		ImageView image;
	}
}

The above adapter is working on a Pojo Class.

ImageItem.java

package com.javatechig.gridview;

import android.graphics.Bitmap;

/**
 * @author javatechig {@link http://javatechig.com}
 * 
 */
public class ImageItem {
	private Bitmap image;
	private String title;

	public ImageItem(Bitmap image, String title) {
		super();
		this.image = image;
		this.title = title;
	}

	public Bitmap getImage() {
		return image;
	}

	public void setImage(Bitmap image) {
		this.image = image;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}
}

4. Using GridView Adapter in Activity

Instantiate the GridView by using findViewById(int) method. This method takes the same id as provided in the layout xml file. The setAdapter() method then sets a custom adapter (GridViewAdapter) as the source for all items to be displayed in the grid.

MainActivity.java

import java.util.ArrayList;
import android.app.Activity;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.GridView;

/**
 * 
 * @author javatechig {@link http://javatechig.com}
 * 
 */
public class MainActivity extends Activity {
	private GridView gridView;
	private GridViewAdapter customGridAdapter;

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

		gridView = (GridView) findViewById(R.id.gridView);
		customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
		gridView.setAdapter(customGridAdapter);
	}

	private ArrayList getData() {
		final ArrayList imageItems = new ArrayList();
		// retrieve String drawable array
		TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
		for (int i = 0; i < imgs.length(); i++) {
			Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
					imgs.getResourceId(i, -1));
			imageItems.add(new ImageItem(bitmap, "Image#" + i));
		}

		return imageItems;

	}

}

5. Handling GridView Click Event

To do something when an item in the grid is clicked, the setOnItemClickListener() method is passed a new AdapterView.OnItemClickListener. This anonymous instance defines the onItemClick() callback method to show a Toast that displays the index position (zero-based) of the selected item. In a real world scenario, the position could be used to get the full sized image for some other task.

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

});

6. Customizing GridView Style

Now, we are preitty much good with the GridView galelry. But what if we want to change the background color of a grid item while user is pressing?.

Let us define a color selector grid_color_selector.xml (code provided below) and place it inside drawable folder. We can use a selector with grid_row.xml layout file by using android:background attribute.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/blue" android:state_pressed="true"/>
    <item android:drawable="@color/blue" android:state_selected="true"/>
    <item android:drawable="@color/white"/>

</selector>

7. Download Complete Example

Here you can download complete eclipse project source code from GitHub.

Download Complete Source Code from GitHub

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. Follow him on Twitter or Google plus.

-- Advertisement --
  • http://javatechig.com/ javatechig

    GridView doesn’t support header and footer by default. You have to make your own workaround.

    You may use below example

    https://github.com/munix/GridViewHeader

  • Junior Vansuita

    For highlight the item on selected inside the grid view.

    It’s do the magic:

    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
    view.setSelected(true);
    //mainFrag.getFittingViewFragment().addNewProductImage(adapter.getItem(position));
    }

    Set the item view selected programmatically in onItemClick event of grid view.

    No android:clickable=”true” and android:focusable=”true” is nedded.

  • abg macho

    i have question if i already put tab navigation so how put slide image on certain tab when user finger on it either left or right

  • Justin McMurray

    Great example, thank you! I downloaded the source from GitHub today and only had the one issue described below – onItemClick in MainActivity.java wasn’t working for me. When I clicked on an item, I would not get the floating window (Toast) on my android 4.4 device. Here is the fix that worked for me:

    in row_grid.xml change:
    android:clickable=”true”
    android:focusable=”true”
    to:
    android:clickable=”false”
    android:focusable=”false”

    • http://javatechig.com/ javatechig

      Thanks for sharing the solution Justin.

  • shivam

    can u guys please help , how to make image bigger when touched

    • http://javatechig.com/ javatechig

      You probably extend this example for your requirement.

  • shivam

    hello , how to add more images , i have tried adding images in drawable folder, but the problem is only few images that i added can be seen , not all the images, plus when i click on images nothing happened how to make them big like as in our android phones, please help i am a beginner

  • Raviteja Nandula

    I used this inside onclick listener this might help

    Object o = gridView.getItemAtPosition(position);

    ImageItem i = (ImageItem)o;

    customGridAdapter.remove(i);

    i.setTitle(“selected”);

    customGridAdapter.insert(i, position);

    customGridAdapter.notifyDataSetChanged();

  • Raviteja Nandula

    Hi there

    I have tried every thing but i tried this for color

    But when i click the image i am able to see toast message but unable to set the value as selected

    How to make it as selected using onclicklistener

  • usman

    Solution for me ……just add these in row_grid.xml.
    android:clickable=”false”
    android:focusable=”false”
    android:focusableInTouchMode=”false”>

  • Mischa Brammer

    Same probleme here. Nothing in the logs. Please give some help.

  • Matrix Sourcing

    Hi .. onclicklistener is not working for me .. no error/warning .. have also tried using

    android:focusable=”false”
    android:focusableInTouchMode=”false”

    on grid view and true on grid row …

    any help ??????

  • atomnet

    Hello,
    can i use this tutorial for loading image from my site? How?

    Thanks.

  • Don Tharaka

    Thanks for the great tutorial, the solution for click is adding these two lines in the :

    android:focusable=”false”
    android:focusableInTouchMode=”false”

    in row_grid.xml

  • Sasa

    I have the same problem and i don’t solve yet…

  • Nilanchala Panigrahy

    Anything you see in the logs? or any crashes?