GridView is a ViewGroup that displays items in a two dimensional, scrollable grid. The grid items are automatically inserted to the layout using a ListAdapter.

In this article I am going to explain how to create GridView in an Android application. In GridView multiple images will display and when an image is selected, a toast message will display the position of the image.

Create a project

  •  Start a new project named GridViewDemo.
  • Save the image files (image0.jpg, image1.jpg, image2.jpg, image3.jpg, image4.jpg, image5.jpg, image6.jpg, image7.jpg) into the project's res/drawable/ directory.
  • Open the main.xml file inside the res/layout/. Insert the following:
<?xml  version="1.0" encoding="utf-8"?>

<GridView xmlns:android=""


·    Create a new class called ImageAdapter that extends BaseAdapter:

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;
        private Integer[] mThumbIds = {R.drawable.image0,R.drawable.image1,
        public ImageAdapter(Context c)
        public int getCount()
               return mThumbIds.length;
        public Object getItem(int position)
              return null;
        public long getItemId(int position)
               return 0;
        public View getView(int position, View convertView, ViewGroup parent)
              ImageView imageView;
                     imageView=new ImageView(mContext);
                     imageView.setLayoutParams(new GridView.LayoutParams(85,85));
                     imageView.setPadding(8, 8, 8, 8);
               return imageView;

·     Open and insert the following code:


import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

public class GridViewDemo extends Activity {

     public void onCreate(Bundle savedInstanceState)
        GridView gridview = (GridView) findViewById(;
        gridview.setAdapter(new ImageAdapter(this));
         gridview.setOnItemClickListener(new OnItemClickListener() {
         public void onItemClick(AdapterView<?> parent, View v, int position, long id)
               Toast.makeText(GridViewDemo.this, "" + (position+1),

·     Run the application.

Your grid layout should look something like this:

Using GridView in Android Application

When you select an image the toast message display the position of a selected image.

  Modified On Mar-23-2018 02:07:59 AM

Leave Comment