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
Subscribe
Notify of
guest
213 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Digvijay
Digvijay
7 years ago

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
Ashish
7 years ago

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
Douglas
7 years ago

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

Ashok
Ashok
7 years ago

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

Ankush
Ankush
7 years ago

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

Osama Mursleen
Osama Mursleen
7 years ago

Really cool tutorial….

srvSud
srvSud
7 years ago

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
sagar joshi
7 years ago
Reply to  srvSud

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

Jai
Jai
7 years ago
Reply to  sagar joshi

same problem with me

Thiago Borges
Thiago Borges
7 years ago

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

Vishal
Vishal
7 years ago

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
satish kumar
7 years ago

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
Wael
7 years ago

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
Noize
5 years ago
Reply to  Wael

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

mehmet
mehmet
7 years ago

excellent tutorial thanks!

Guest
Guest
7 years ago

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
Nissrine
7 years ago

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
abcdefgh
7 years ago

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
jai
7 years ago

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
jai
7 years ago

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
KP Ranjith
7 years ago

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

Ravi Tamada
7 years ago
Reply to  KP Ranjith

You are welcome Ranjith Bro 🙂

Urvi Jasani
Urvi Jasani
5 years ago
Reply to  Ravi Tamada

Really its amazingggggg…!

Srivatsa Haridas
Srivatsa Haridas
7 years ago

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

ankit
ankit
7 years ago

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

Pankaj Kumar
Pankaj Kumar
6 years ago
Reply to  ankit

Get the Uri of those images in ArrayList

Malik
Malik
7 years ago

Good Example

PRAVIN KUMAR
PRAVIN KUMAR
6 years ago

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
Joel
6 years ago
Reply to  PRAVIN KUMAR

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

Mithun
Mithun
6 years ago

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
android
6 years ago

thanks for the article.

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

Soheil Afshari
Soheil Afshari
6 years ago

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

mav
mav
6 years ago
Reply to  Soheil Afshari

Could someone please answer this question?

Z.A Khan
Z.A Khan
6 years ago
Reply to  mav

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
etking
6 years ago
Reply to  Soheil Afshari

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

“setOnItemClickListener”

george
george
6 years ago

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
Pankaj Kumar
6 years ago

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
Sereen Shalby
6 years ago

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
JNR
6 years ago

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
Surabhi Sugandha
6 years ago

really heplful site..thanx a ton 🙂 🙂

Rakhi Dhavale
6 years ago

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

Dheeraj Vashist
Dheeraj Vashist
5 years ago
Reply to  Rakhi Dhavale

this is GridView, not GridLayout lol

Rakhi Dhavale
5 years ago

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

Milad
Milad
6 years ago

good 😀 tnx

Dhaval
Dhaval
6 years ago

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
mv
6 years ago

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
Rahul Srivastava
6 years ago
Reply to  mv

check naming criteria for drawable folder.

denniswanjama
denniswanjama
6 years ago

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
Mohammed
6 years ago

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

@Omor
@Omor
6 years ago

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

pratik
pratik
6 years ago

very nice and simple 🙂

sachindra
sachindra
6 years ago

good

Sarath
Sarath
5 years ago

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
Edmhar
5 years ago
Reply to  Sarath

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
Hafiz Abdure rehman
5 years ago

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

bhavika
bhavika
5 years ago

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

刘文月
刘文月
5 years ago

OOM

shan
shan
5 years ago

Also get OOM…

Lwkkazz
Lwkkazz
5 years ago

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

vinit
vinit
5 years ago

run this code after that blanck screen show.

Trung Do
Trung Do
5 years ago

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
vidya jejurkar
5 years ago

can we use Multiple gridview with 2 textview for each gridview

like

Mee Na
Mee Na
4 years ago

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
ashok reddy
4 years ago

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

what is the use of Context..

213
0
Would love your thoughts, please comment.x
()
x