Android GridView Example


In this article, we will see an example of a GridView with some of our favorite cartoon characters. We use grid view to display items in a two dimensional array (grid).
So let’s start!

Main Layout

GridView is the element that represents a grid view layout. Let’s add it to our layout XML.


<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android=""

Main Activity

GridViewExampleActivity is our main activity. We will set the content view to our grid view. We will also add a listener so that when an item is clicked, you see the name of the character.
Few points to note about:

  1. Override onCreate to set the content view to the grid view layout setContentView(R.layout.welcome)
  2. Create a simple ArrayAdapter. Each element of the array is a string field and contains the character name.
  3. We need to pass the item layout and the array to the ArrayAdapter
  4. We will use existing android’s layout for each item so set it to android.R.layout.simple_list_item_1
  5. Set an item listener using setOnItemClickListener. This accepts an OnItemClickListener object.
  6. The item listener will simply show the character’s name.

DON’T set the item listener using setOnClickListener, app will fail to launch.



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

public class GridViewExampleActivity extends Activity {
	private static String[] cartoon_names = new String[] {
		"Tintin", "Captain Haddock", "Professor Calculus", "Snowy",
		"Thomspon", "Thomson", "Nestor", "Bianca Castafiore"
	private GridView gridView;
	public void onCreate(Bundle savedInstanceState) {
		gridView = (GridView) findViewById(;
		gridView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, cartoon_names));
		gridView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				Toast.makeText(view.getContext(), ((TextView)view).getText(), Toast.LENGTH_SHORT).show();				

Run the application

The items show up just like a list. What went wrong? I was expecting a grid.

Single Column Grid View

Single Column Grid View

Let’s fix the layout. We have missed an important attribute.


<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android=""

Let’s rerun the application.

Grid View

Grid View

After setting numColumns to “auto_fit”, this looks fine now.

Download source code

This was an example of android GridView. You can download the source code here:


Comments are closed.