Android 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. The grid items are automatically added to the layout using a ListAdapter.

GridView Attributes

android:id – This is the ID which uniquely identifies the layout.

android:columnWidth – This specifies the fixed width for each column. This could be in px,  sp,dp, in, or mm.

android:gravity : Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_horizontal, center_vertical, etc.

android:numColumns : Defines how many columns to show. May be an integer value, such as “200” or auto_fit which means display as many columns as possible to fill the available space.

android:horizontalSpacing : Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or mm

android:stretchMode : Defines how columns should stretch to fill the available empty space, if any. This must be either of the values :

     none : Stretching is disabled

     columnWidth : Each column is stretched equally

     spacingWidth : The spacing between each column is stretched

     spacingWidthUniform : The spacing between each column is uniformly stretched

     android:verticalSpacing : Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm

Must see : Android UI Layouts

GridView examples :Normal way, just display text in GridView layout.

Android Layout file – res/layout/main.xml

<?xml version=”1.0″ encoding=”utf-8″?>

<GridView xmlns:android=””







android:layout_height=”fill_parent” >





import android.os.Bundle;

import android.widget.AdapterView;

import android.widget.ArrayAdapter;

import android.widget.GridView;

import android.widget.TextView;

import android.widget.Toast;

import android.view.View;

import android.widget.AdapterView.OnItemClickListener;

public class GridViewActivity extends Activity {

GridView gridView;

static final String[] numbers = new String[] {

“A”, “B”, “C”, “D”, “E”,

“F”, “G”, “H”, “I”, “J”,

“K”, “L”, “M”, “N”, “O”,

“P”, “Q”, “R”, “S”, “T”,

“U”, “V”, “W”, “X”, “Y”, “Z”};


public void onCreate(Bundle savedInstanceState) {



gridView = (GridView) findViewById(;

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,

android.R.layout.simple_list_item, numbers);


gridView.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View v,

int position, long id) {


((TextView) v).getText(), Toast.LENGTH_SHORT).show();








PDF Download – Latest Updated Android Training Topics