Android Gridview Example- Building Image Gallery in android

1. Introduction

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

2. Define 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.

<RelativeLayout xmlns:android=""
    tools:context=".MainActivity" >

        android:stretchMode="columnWidth" >


3. Define Grid Item 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.


<LinearLayout xmlns:android=""

        android:layout_height="100dp" >

        android:textSize="12sp" >


4. Custom GridView Adapter

  1. Create a new class called GridViewAdapter that extends ArrayAdapter. This class will be used by GridView in order to render its contents.
  2. The getView() method implementation is necessary is. This method creates a new View for each image added to the GridViewAdapter.
  3. 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.
  4. ViewHolder design patterns are efficient while using composite layouts.

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; = data;

	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(;
			holder.image = (ImageView) row.findViewById(;
		} else {
			holder = (ViewHolder) row.getTag();

		ImageItem item = data.get(position);
		return row;

	static class ViewHolder {
		TextView imageTitle;
		ImageView image;

The above adapter is working on a Pojo Class.

public class ImageItem {
	private Bitmap image;
	private String title;

	public ImageItem(Bitmap image, String title) {
		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;

5. 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.

public class MainActivity extends Activity {
	private GridView gridView;
	private GridViewAdapter customGridAdapter;

	protected void onCreate(Bundle savedInstanceState) {

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

	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;



6. 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",


7. 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="">
    <item android:drawable="@color/blue" android:state_pressed="true"/>
    <item android:drawable="@color/blue" android:state_selected="true"/>
    <item android:drawable="@color/white"/>

8. 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.

  • Ana Fernandez Ruiz

    thanks a lot, very useful

  • JavaTechig

    Check out the below code snippets to create array adapter and set it to listview. You can do the requirement adjustments.

    // context – The current context.
    // resource – The resource ID for a layout file containing a layout
    // to use when instantiating views.
    // From the third parameter, you plugged the data set to adapter
    arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, monthsArray);

    // By using setAdapter method, you plugged the ListView with adapter

  • kads

    how i remove the errors ?

    • JavaTechig

      import the following packages. Put after package declaration.

      import java.util.ArrayList;
      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;

  • Manish

    How to set image to another activity’s imageview when any clicked from GridView

  • javatechig

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

    You may use below example

  • Junior Vansuita

    For highlight the item on selected inside the grid view.

    It’s do the magic:

    public void onItemClick(AdapterView parent, View view, int position, long id) {

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

    • javatechig

      Thanks for sharing the solution Justin.

  • shivam

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

    • javatechig

      You probably extend this example for your requirement.

    • Rokhsareh

      Have you found how to do this?! could you please help me with it?
      Many thanks

  • 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.insert(i, position);


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

  • 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


    on grid view and true on grid row …

    any help ??????

  • atomnet

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


  • Don Tharaka

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


    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?