Android Gridview Example- Building Image Gallery in android

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 an 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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. Creeating a custom GridView 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<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. Creating 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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 from java class

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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 Click event on GridView

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.

1
2
3
4
5
6
7
8
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.

1
2
3
4
5
6
7
8
<?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.
[sociallocker]


[/sociallocker]

About Nilanchala

A blogger, bit of a tech freak and a software developer. Follow him on Twitter, or like our official Facebook page or Google Plus.

  • 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?