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.

Download Code

Basic GridView Layout

1. Create a new project by going to File ⇒ New Android Project and fill required details. (I named my main activity as AndroidGridLayoutActivity.java)
2. Prepare your images which you want to show in grid layout and place them in res ⇒ drawable-hdpi folder.
3. Create a new XML layout under layout and name it as grid_layout.xml (Right Click) layout ⇒ New ⇒ Android XML File

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

</GridView>

4. Create a new Class by right clicking on (Right Click) src ⇒ package folder ⇒ New ⇒ Class and name your class as ImageAdapter.java
5. Extend your ImageAdapter.java class from BaseAdapter and fill it with following code.

package com.example.androidhive;

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;

	// Keep all Images in array
	public Integer[] mThumbIds = {
			R.drawable.pic_1, R.drawable.pic_2,
			R.drawable.pic_3, R.drawable.pic_4,
			R.drawable.pic_5, R.drawable.pic_6,
			R.drawable.pic_7, R.drawable.pic_8,
			R.drawable.pic_9, R.drawable.pic_10,
			R.drawable.pic_11, R.drawable.pic_12,
			R.drawable.pic_13, R.drawable.pic_14,
			R.drawable.pic_15
	};

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

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

	@Override
	public Object getItem(int position) {
		return mThumbIds[position];
	}

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

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView = new ImageView(mContext);
        imageView.setImageResource(mThumbIds[position]);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
        return imageView;
	}

}

6. Open your main activity class as shown below.

package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class AndroidGridLayoutActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grid_layout);

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

		// Instance of ImageAdapter Class
		gridView.setAdapter(new ImageAdapter(this));
	}
}

Run your project

android grid view

Showing selected grid image in new Activity (Full Screen)

Until now we displayed all images in simple grid layout. To this we can add functionality like showing selected image in fullscreen. For this we need to pass image resource id from grid view to new activity.
7. Create new XML file under layout folder and name it as full_image.xml and fill it following code.

<?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/full_image_view"
        	android:layout_width="fill_parent"
        	android:layout_height="fill_parent"/>

</LinearLayout>

8. Create a new Activity by right clicking on (Right Click) src ⇒ package folder ⇒ New ⇒ Class and name your class as FullImageActivity.java and type following code.

package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

public class FullImageActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.full_image);

		// 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.full_image_view);
		imageView.setImageResource(imageAdapter.mThumbIds[position]);
	}

}

9. Modify your main activity class to following. I added click event for grid element.

package com.example.androidhive;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class AndroidGridLayoutActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.grid_layout);

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

		// Instance of ImageAdapter Class
		gridView.setAdapter(new ImageAdapter(this));

		/**
		 * On Click event for Single Gridview Item
		 * */
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				// Sending image id to FullScreenActivity
				Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
				// passing array index
				i.putExtra("id", position);
				startActivity(i);
			}
		});
	}
}

10. Open your AndroidManifest.xml and add entries of newly added activity.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".AndroidGridLayoutActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- FullImageActivity -->
        <activity android:name=".FullImageActivity"></activity>
    </application>

</manifest>

Finally run your project

android grid view
This image for thumbnail purpose
Android Gridview layout
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: ravi@androidhive.info
  • Digvijay

    Hi,
    Can you please tell me, If I want to add header in Gridview then, how I will add. I don’t want to use another listview.

  • Ashish

    nice tutorial.
    i have a simple question.
    after the image is full size how can i add swipe effect to change next image.
    for eg : if a swipe right then next image from the grid should be loaded and if i swipe left then previous image from the grid should be loaded.
    thanx and reply soon.

  • Douglas

    is to take the image of the sd card, mount for display in grid view?

  • Ashok

    Thank u for ur tutorial 🙂 Can u pls write a tutorial for a simple horizontal List view?? Pls….. 🙂

  • Ankush

    Excellent tutorial! Clean and simple. Keep up the good work! 🙂

  • Osama Mursleen

    Really cool tutorial….

  • srvSud

    collect some images you want to show in the grid view and place them in res ⇒ drawable-hdpi or res ⇒ drawable-mdpi folder.

    • sagar joshi

      i am also having the same problem…
      even though i have placed some images in hdpi folder

      • Jai

        same problem with me

  • Thiago Borges

    who calls getView()?? I’m having trouble understanding how this application works

  • Vishal

    hey vary nice tutorial
    i have added text view in grid instead of image view
    things which you are doing on on click i want to perform on on touch listener
    i want want when my finger is moving on particular item at that item height and width get enlarge how do i do this please help

  • satish kumar

    thanks a lot….if i want to make one img as a background then how to give an option on that image in fullscreenActivity pls suggested to me or send code to my mail pls…

  • Wael

    Hi dude, following this tutorial i’m trying to pick the images from internet using this array:

    public String[] mThumbIds = {
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”,
    “http://www.stendhalrugbypr.it/…”
    };

    Eclipse found me an error here:

    imageView.setImageResource(imageAdapter.mThumbIds[position]);

    how to fix it ? Thank You

    • Noize

      I’m also having this error, because it spends and int not a String

  • mehmet

    excellent tutorial thanks!

  • Guest

    This is what I want to do:

    1) Click on image and it brings up an image from the grid, in fullscreen view – this is what this code already does.
    2) Click again on the full-screened image to play a sound.
    3) It must play the sound as many times as I click on the full-screened image.

    4) Further developing, how would I be able to kinda of “select” an array of sounds for a selected image. Like a loop that will choose a specified file depending on what array it matches, inserted in the Media Player event.

  • Nissrine

    very nice tutorial, thaanks so much !

    I have a little problem with this code, when i add an activity before AndroidGridLayoutActivity.class, the app doesnt work 🙁 !! the first activity work, but when the AndroidGridLayoutActivity have to word the app stop ! can you help me plz !!

  • abcdefgh

    Hi Ravi, this is really a very good tutorial. I am trying to learn how to display images in grid view. I have a doubt, in the class “ImageAdapter.java”, you have given some images paths, which are integer variables. In my application, I am trying to display the images whose paths are retrieved from SQLite and are in string format. What are the changes to be done, in order to get my task done? Sorry that the question may be too straight forward, but as I am a newbie to android, please help me.

    Thanks in advance.

  • jai

    hey please help ***
    i am having a problem with grid view
    that is –

    // Keep all Images in array

    public Integer[] mThumbIds = {

    R.drawable.pic_1,

    i want to attach more then 15 images but if i do so
    the applications stops after emulating with a FORCE CLOSE message
    if anyone able to help please respond ASAP

  • jai

    hey please help ***
    i am having a problem with grid view
    that is –

    // Keep all Images in array

    public Integer[] mThumbIds = {

    R.drawable.pic_1,

    i want to attach more then 15 images but if i do so
    the applications stops after emulating with a FORCE CLOSE message
    if anyone able to help please respond

  • KP Ranjith

    hi ravi bro, your tutorial site is outstanding! i’m learning from it. thank you so much for ur effort to create this site, it is more helpful to many of the beginners and thaks again. 🙂

    • You are welcome Ranjith Bro 🙂

      • Urvi Jasani

        Really its amazingggggg…!

  • Srivatsa Haridas

    Your tutorials are very insightful and helps a lot for beginners. Thanks again for sharing across your knowledge on Android OS.

  • ankit

    Excellent Ravi , Great Work, could you please also explain how to do read images in sdcard and show it in gridview

    • Pankaj Kumar

      Get the Uri of those images in ArrayList

  • Malik

    Good Example

  • PRAVIN KUMAR

    hello ravi

    i need your help i want to develop application,i want to take photo in my app and save into an specific folder on sd card as same time i want to show my images which was already saved in folder as grid view and adding select,delete function to that images showing in grid view

    • Joel

      hi i have the same question as you so just want to ask if you currently know how to do it?

  • Mithun

    Hello Ravi.. in my application i want to group the images to different categories.

    Group1

    Image1 Image2 Image3

    Image4 Image5 Image6

    Group2

    Image7 Image8 Image9

    Image10 Image11 Image12

    Could you please let me know how to achieve this. This will really help me..
    Thanks in advance..

  • android

    thanks for the article.

    is it possible to do set higlighted on selected item then show delete/show buttons on actionbar?

  • Soheil Afshari

    hi tnx for tutorial how can i add a toast so i know which item is clicked ?

    • mav

      Could someone please answer this question?

      • Z.A Khan

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position, long id) {
        Toast.makeText(MainActivity.this, “” + position, Toast.LENGTH_SHORT).show();
        }
        });

        but you have to write an Adapter for it.

    • etking

      Just add listener to grid view control to listen for item clicked event.

      “setOnItemClickListener”

  • george

    Hi all. I am a novice in developing app and thanks to
    Ravi for all good work that is doing . I’m working at a simple app and I get
    stuck . if you have knowledge of
    building android apps, and make team
    with me please replay to george.celsie@gmail.com . Thanks ang
    good luck for all your projects..

  • Pankaj Kumar

    for the second part to view the full image in next activity,when I select the single image it throws an error with ArrayIndexOutOfBounds

  • Sereen Shalby

    hello , please can you help me? every time i try to run this code .. on galaxy s3 .. the full image activity // and it tells me its memory issue .. and i have checked the internal and external storage and both have space .. what is the problem and how can i fix it?

  • JNR

    is it possible to make the images in the gridview unresponsive for some time and make them responsive again on a button click. this button is not a gridview element.

  • Surabhi Sugandha

    really heplful site..thanx a ton 🙂 🙂

  • This is the best gridLayout example that i have seen so far from all android blogs! Thanks !

    • Dheeraj Vashist

      this is GridView, not GridLayout lol

      • I’m aware of the fact that its a gridView ,it was my typo mistake !!

  • Milad

    good 😀 tnx

  • Dhaval

    when I set numColumns = 2 it shows only 10 items perfect after all items are repeated from previous images and name….. but if I set numColumns = 3 it works perfectly…

  • mv

    even though i have added the images in res ->drawable-hdpi i still get “R.drawable.imagename” as “cannot be resolved or is not a field”. i have tried cleaning the project as well.
    plz help!!!!

    • Rahul Srivastava

      check naming criteria for drawable folder.

  • denniswanjama

    Hi im making a grid view and i want to click on image to take me to different activity how do i do that. Every image will take me to different activity class

  • Mohammed

    Hi.. Thanks for sharing such an informative tutorial. Could you please tell me how to increase the icon size in the grid.

  • @Omor

    Nice! you are great! it is help to clear understanding grid view.

  • pratik

    very nice and simple 🙂

  • sachindra

    good

  • Sarath

    hi, i just encounter an error in imageAdapter java file. it shows “pic cannot be resolved or not a field”. i hav copied image files to drawable hdpi in png format but still it shows error. pls help

    • Edmhar

      You should import first the Resources
      maybe try to import this

      Example my package name was com.androidapp.edmhar
      import com.androidapp.edmhar.R;

      if still does not fix and you are using Android Studio you should Clean your Project first

      Build > Clean Project.

  • Hafiz Abdure rehman

    accept my id “arrehman18@live.com”
    after subscribtion no email found in my inbox doing this for weeks ago.

  • bhavika

    Hello,
    I am trying to develop a picture gallery app. It all works fine except that when i test it on my phone the images are very small sized where as when i test the same thing on an emulator the image size is big enough. If you could help me solve that issue.
    Thank you

  • 刘文月

    OOM

  • shan

    Also get OOM…

  • Lwkkazz

    For those who is getting an OOM error, try putting your images in xhdpi folder

  • vinit

    run this code after that blanck screen show.

  • Trung Do

    I tried to run on both genymotion and the native emulator of Eclispe but the app kept crashing every single time. Does anyone know how to fix this issue?
    Thanks so much in advance.

  • vidya jejurkar

    can we use Multiple gridview with 2 textview for each gridview

    like

  • Mee Na

    Hi, Thank you so much for this tutorial, the full image activity java and xml is not what I would have thought of, saved me a lot of time.

  • ashok reddy

    Hi Ravi Thank you for Your tutorial i have Doubt Why Here public ImageAdapter(Context c){
    mContext = c;

    what is the use of Context..

  • Rajes

    want to swipe images in same tutorials

  • sriram veeraghanta

    Can u update this tutorial with new material design grid view with images and text on it.

    • Yes, I’ll update. Meanwhile you can search for “RecyclerView as Grid Layout”.

  • Danish

    i am getting this error : Out of memory on a 17448972-byte allocation.

    on this line : imageView.setImageResource(mThumbIds[position]);

    when i am trying to run my app it crashes .

  • I got the image grid working, but I want to write text under each image and style them. And also want to insert button below the text and style them. Plz help me out to do that. I am a very new to Android app development. Thanks

  • Biswajit Rout

    I am getting NullPointerException on the line-

    imageView.setImageResource(imageAdapter.mThumbIds[position]);

  • Joy Basak

    hello sir i have put 21 pic in my grid view bt it seems very small in size in grid while my image dimension is 117*124 in jpg format.. how to solve this .? please reply as soon as possible .

  • Ivanco Pavlov

    How can i make in full image activity switch images with left/right?

  • vishal Halani

    Can I make grid with card view??can you post example of it?

  • Prakash Rai

    when i click on image it takes 4 to 5 second to open . is there any way to make it fast

  • ali

    hii… can i ave a box there is one title and two images /… i also dont this work with adopter now i have a issue i have to create anotherboxe so i create new adopter ????

  • I want to gesture swipe left right in this project . anyone plx help me

  • José Luis Jiménez Cevallos

    Hey Ravi! Can you tell me how to play videos using the gridView layout? Can’t find any solution for this!

    • Sham Kishor Sharma

      any solution ??

  • VITHIKA GUPTA

    Running the above code gives me run time error ..my app closes off as soon after opening it.
    please suggest me the appropriate solution.

  • stevekam

    This is the same tutorial that is in many other places. It shows the same old grid view where all cells are evenly sized.

    • Abdul Rehman

      where is this type of place of tutorials of grid views cells or card views that when we click on an item so that its full images or full data is shown to us reply with some useful links both offline and online apps development tutorials
      thanks

  • Abdul Rehman

    Sir plz update seems easy but this tutorial its having many bugs and errors
    thanks in advance

  • Vicky Lynn

    I’m getting java.lang runtime exception attempted to read from null array how do I fix this

  • Vempati Satya Suryanarayana

    Very nice tutorial.
    Can we not use a scroll view for displaying full image? Is it not a better option?

  • Mitchell Chen

    Very much appreciated for your wonderful GridView example which I have learned a lot

  • Kaustuv Samanta

    sir how i delete one grid view item