Android Simple GridView Tutorial

In this tutorial, you will learn how to create a simple GridView in your Android application. GridView allows you to show images in a vertical grid form. We will create a GridView and on GridView item click will show the selected image on a new activity. So lets begin…

Create a new project in Eclipse, select File > New > Android Application Project. Fill in the details and name your project GridViewTutorial.

Application Name : GridViewTutorial

Project Name : GridViewTutorial

Package Name : com.androidbegin.gridviewtutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.gridviewtutorial;

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

public class MainActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from gridview_main.xml
		setContentView(R.layout.gridview_main);

		// Locate GridView in listview_main.xml
		GridView gridview = (GridView) findViewById(R.id.gridview);

		// Set the ImageAdapter into GridView Adapter
		gridview.setAdapter(new ImageAdapter(this));

		// Capture GridView item click
		gridview.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {

				// Launch ViewImage.java using intent
				Intent i = new Intent(MainActivity.this, ViewImage.class);

				// Show the item position using toast
				Toast.makeText(MainActivity.this, "Position " + position,
						Toast.LENGTH_SHORT).show();

				// Send captured position to ViewImage.java
				i.putExtra("id", position);

				// Start ViewImage.java
				startActivity(i);
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_grid_view, menu);
		return true;
	}
}

This activity retrieves images from ImageAdapter.java class and binds them into the GridView adapter. On GridView item click, the selected position is passed into a new activity called ViewImage.java class. A toast message will show the current position of the GridView item click.

Now lets create an XML file for the GridView Graphical Layout. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file gridview_main.xml and paste the following code.

gridview_main.xml 

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

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="90dp"
        android:gravity="center"
        android:horizontalSpacing="10dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="10dp" />

</RelativeLayout>

Output:

GridView Tutorial Main XML

We have prepared some sample images for this tutorial. Insert your downloaded sample images into your res > drawable-hdpi.

Sample Image

[wpfilebase tag=file id=25 tpl=download-button /]

Next, create a new class called ImageAdapter.java. Go to File > New > Class and name it ImageAdapter.java. Select your package named com.androidbegin.gridviewtutorial and click Finish.

Open your ImageAdapter.java and paste the following code.

ImageAdapter.java

package com.androidbegin.gridviewtutorial;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {
	private Context mContext;

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

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

	public Object getItem(int position) {
		return null;
	}

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

	// Create a new ImageView for each item referenced by the Adapter
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView;
		// if it's not recycled, initialize some attributes
		if (convertView == null) { 
			imageView = new ImageView(mContext);
			// Center crop image
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
		} else {
			imageView = (ImageView) convertView;
		}
		// Set images into ImageView
		imageView.setImageResource(mThumbIds[position]);
		return imageView;
	}

	// References to our images in res > drawable
	public Integer[] mThumbIds = { R.drawable.sample_0, R.drawable.sample_1,
			R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4,
			R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7,
			R.drawable.sample_8, R.drawable.sample_9, R.drawable.sample_10,
			R.drawable.sample_11, R.drawable.sample_12, R.drawable.sample_13,
			R.drawable.sample_14, R.drawable.sample_15, R.drawable.sample_16,
			R.drawable.sample_17, R.drawable.sample_18 };
}

In this activity, images are referenced by image id’s and stored into an Integer array. In the getView method, the images are set into the ImageViews followed by the positions.

Next, create a new activity in a new class called SingleItemView.java. Go to File > New > Class and name it SingleItemView.java. Select your package named com.androidbegin.gridviewtutorial and click Finish.

Open your SingleItemView.java and paste the following code.

SingleItemView.java

package com.androidbegin.gridviewtutorial;

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

public class SingleItemView extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from singleitemview.xml
		setContentView(R.layout.single_item_view);

		// Get position from intent passed from MainActivity.java
		Intent i = getIntent();

		int position = i.getExtras().getInt("id");

		// Open the Image adapter
		ImageAdapter imageAdapter = new ImageAdapter(this);

		// Locate the ImageView in single_item_view.xml
		ImageView imageView = (ImageView) findViewById(R.id.image);

		// Get image and position from ImageAdapter.java and set into ImageView
		imageView.setImageResource(imageAdapter.mThumbIds[position]);
	}
}

This activity retrieves the position from the GridView item click in MainActivity.java using intent. Then we use the setImageResource to get the image from ImageAdapter using the position as a reference and set the image into an ImageView.

Next, create an XML file for your SingleItemView Graphical Layout. Go to res > layout > Right Click on layout > New >Android XML File

Name your new XML file singleitemview.xml and paste the following code.

singleitemview.xml

<?xml version="1.0" encoding="utf-8"?>
<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" >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

</RelativeLayout>

Next, change the application name. Open your strings.xml in your res > values folder and paste the following code.
strings.xml

<resources>

    <string name="app_name">GridView Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>

</resources>

In your AndroidManifest.xml, we need to declare an activity for SingleItemView.java. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.gridviewtutorial"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

</manifest>

Output :

GridView Tutorial ScreenShot

Source Code

[purchase_link id=”7818″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

Please refer to this tutorial https://www.androidbegin.com/tutorial/android-gridview-zoom-images-animation-tutorial/

AndroidBegin

Android Simple GridView Tutorial

How can i add zoom to this project ?

Kutalp*DH

Android Simple GridView Tutorial

Hi thanks for making this tutorial available! How can I add more images?

Marcus Arylias

Android Simple GridView Tutorial