Android APIs
public class

GridView

extends AbsListView
java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.AdapterView<T extends android.widget.Adapter>
         ↳ android.widget.AbsListView
           ↳ android.widget.GridView

Class Overview

A view that shows items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

See the Grid View guide.

Summary

XML Attributes
Attribute Name Related Method Description
android:columnWidth setColumnWidth(int) Specifies the fixed width for each column. 
android:gravity setGravity(int) Specifies the gravity within each cell. 
android:horizontalSpacing setHorizontalSpacing(int) Defines the default horizontal spacing between columns. 
android:numColumns setNumColumns(int) Defines how many columns to show. 
android:stretchMode setStretchMode(int) Defines how columns should stretch to fill the available empty space, if any. 
android:verticalSpacing setVerticalSpacing(int) Defines the default vertical spacing between rows. 
[Expand]
Inherited XML Attributes
From class android.widget.AbsListView
From class android.view.ViewGroup
From class android.view.View
Constants
int AUTO_FIT Creates as many columns as can fit on screen.
int NO_STRETCH Disables stretching.
int STRETCH_COLUMN_WIDTH Stretches columns.
int STRETCH_SPACING Stretches the spacing between columns.
int STRETCH_SPACING_UNIFORM Stretches the spacing between columns.
[Expand]
Inherited Constants
From class android.widget.AbsListView
From class android.widget.AdapterView
From class android.view.ViewGroup
From class android.view.View
[Expand]
Inherited Fields
From class android.view.View
Public Constructors
GridView(Context context)
GridView(Context context, AttributeSet attrs)
GridView(Context context, AttributeSet attrs, int defStyleAttr)
GridView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Public Methods
ListAdapter getAdapter()
Returns the adapter currently associated with this widget.
int getColumnWidth()
Return the width of a column in the grid.
int getGravity()
Describes how the child views are horizontally aligned.
int getHorizontalSpacing()
Returns the amount of horizontal spacing currently used between each item in the grid.
int getNumColumns()
Get the number of columns in the grid.
int getRequestedColumnWidth()
Return the requested width of a column in the grid.
int getRequestedHorizontalSpacing()
Returns the requested amount of horizontal spacing between each item in the grid.
int getStretchMode()
int getVerticalSpacing()
Returns the amount of vertical spacing between each item in the grid.
void onInitializeAccessibilityEvent(AccessibilityEvent event)
Initializes an AccessibilityEvent with information about this View which is the event source.
void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info)
Initializes an AccessibilityNodeInfo with information about this view.
void onInitializeAccessibilityNodeInfoForItem(View view, int position, AccessibilityNodeInfo info)
Initializes an AccessibilityNodeInfo with information about a particular item in the list.
boolean onKeyDown(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.
boolean onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).
boolean onKeyUp(int keyCode, KeyEvent event)
Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.
void setAdapter(ListAdapter adapter)
Sets the data behind this GridView.
void setColumnWidth(int columnWidth)
Set the width of columns in the grid.
void setGravity(int gravity)
Set the gravity for this grid.
void setHorizontalSpacing(int horizontalSpacing)
Set the amount of horizontal (x) spacing to place between each item in the grid.
void setNumColumns(int numColumns)
Set the number of columns in the grid
void setRemoteViewsAdapter(Intent intent)
Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService through the specified intent.
void setSelection(int position)
Sets the currently selected item
void setStretchMode(int stretchMode)
Control how items are stretched to fill their space.
void setVerticalSpacing(int verticalSpacing)
Set the amount of vertical (y) spacing to place between each item in the grid.
void smoothScrollByOffset(int offset)
Smoothly scroll to the specified adapter position offset.
void smoothScrollToPosition(int position)
Smoothly scroll to the specified adapter position.
Protected Methods
void attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params, int index, int count)
Subclasses should override this method to set layout animation parameters on the supplied child.
int computeVerticalScrollExtent()

Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.

int computeVerticalScrollOffset()

Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range.

int computeVerticalScrollRange()

Compute the vertical range that the vertical scrollbar represents.

void layoutChildren()
Subclasses must override this method to layout their children.
void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect)
Called by the view system when the focus state of this view changes.
void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

Measure the view and its content to determine the measured width and the measured height.

[Expand]
Inherited Methods
From class android.widget.AbsListView
From class android.widget.AdapterView
From class android.view.ViewGroup
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback
From interface android.text.TextWatcher
From interface android.view.KeyEvent.Callback
From interface android.view.ViewManager
From interface android.view.ViewParent
From interface android.view.ViewTreeObserver.OnGlobalLayoutListener
From interface android.view.ViewTreeObserver.OnTouchModeChangeListener
From interface android.view.accessibility.AccessibilityEventSource
From interface android.widget.Filter.FilterListener

XML Attributes

android:columnWidth

Specifies the fixed width for each column.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol columnWidth.

Related Methods

android:gravity

Specifies the gravity within each cell.

Must be one or more (separated by '|') of the following constant values.

ConstantValueDescription
top0x30 Push object to the top of its container, not changing its size.
bottom0x50 Push object to the bottom of its container, not changing its size.
left0x03 Push object to the left of its container, not changing its size.
right0x05 Push object to the right of its container, not changing its size.
center_vertical0x10 Place object in the vertical center of its container, not changing its size.
fill_vertical0x70 Grow the vertical size of the object if needed so it completely fills its container.
center_horizontal0x01 Place object in the horizontal center of its container, not changing its size.
fill_horizontal0x07 Grow the horizontal size of the object if needed so it completely fills its container.
center0x11 Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
fill0x77 Grow the horizontal and vertical size of the object if needed so it completely fills its container.
clip_vertical0x80 Additional option that can be set to have the top and/or bottom edges of the child clipped to its container's bounds. The clip will be based on the vertical gravity: a top gravity will clip the bottom edge, a bottom gravity will clip the top edge, and neither will clip both edges.
clip_horizontal0x08 Additional option that can be set to have the left and/or right edges of the child clipped to its container's bounds. The clip will be based on the horizontal gravity: a left gravity will clip the right edge, a right gravity will clip the left edge, and neither will clip both edges.
start0x00800003 Push object to the beginning of its container, not changing its size.
end0x00800005 Push object to the end of its container, not changing its size.

This corresponds to the global attribute resource symbol gravity.

Related Methods

android:horizontalSpacing

Defines the default horizontal spacing between columns.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol horizontalSpacing.

Related Methods

android:numColumns

Defines how many columns to show.

May be an integer value, such as "100".

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

May be one of the following constant values.

ConstantValueDescription
auto_fit-1 Display as many columns as possible to fill the available space.

This corresponds to the global attribute resource symbol numColumns.

Related Methods

android:stretchMode

Defines how columns should stretch to fill the available empty space, if any.

Must be one of the following constant values.

ConstantValueDescription
none0 Stretching is disabled.
spacingWidth1 The spacing between each column is stretched.
columnWidth2 Each column is stretched equally.
spacingWidthUniform3 The spacing between each column is uniformly stretched..

This corresponds to the global attribute resource symbol stretchMode.

Related Methods

android:verticalSpacing

Defines the default vertical spacing between rows.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol verticalSpacing.

Related Methods

Constants

public static final int AUTO_FIT

Added in API level 1

Creates as many columns as can fit on screen.

Constant Value: -1 (0xffffffff)

public static final int NO_STRETCH

Added in API level 1

Disables stretching.

Constant Value: 0 (0x00000000)

public static final int STRETCH_COLUMN_WIDTH

Added in API level 1

Stretches columns.

Constant Value: 2 (0x00000002)

public static final int STRETCH_SPACING

Added in API level 1

Stretches the spacing between columns.

Constant Value: 1 (0x00000001)

public static final int STRETCH_SPACING_UNIFORM

Added in API level 3

Stretches the spacing between columns. The spacing is uniform.

Constant Value: 3 (0x00000003)

Public Constructors

public GridView (Context context)

Added in API level 1

public GridView (Context context, AttributeSet attrs)

Added in API level 1

public GridView (Context context, AttributeSet attrs, int defStyleAttr)

Added in API level 1

public GridView (Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Public Methods

public ListAdapter getAdapter ()

Added in API level 1

Returns the adapter currently associated with this widget.

Returns
  • The adapter used to provide this view's content.

public int getColumnWidth ()

Added in API level 16

Return the width of a column in the grid.

This may not be valid yet if a layout is pending.

Related XML Attributes
Returns
  • The column width in pixels

public int getGravity ()

Added in API level 16

Describes how the child views are horizontally aligned. Defaults to Gravity.LEFT

Related XML Attributes
Returns
  • the gravity that will be applied to this grid's children

public int getHorizontalSpacing ()

Added in API level 16

Returns the amount of horizontal spacing currently used between each item in the grid.

This is only accurate for the current layout. If setHorizontalSpacing(int) has been called but layout is not yet complete, this method may return a stale value. To get the horizontal spacing that was explicitly requested use getRequestedHorizontalSpacing().

Related XML Attributes
Returns
  • Current horizontal spacing between each item in pixels

public int getNumColumns ()

Added in API level 11

Get the number of columns in the grid. Returns AUTO_FIT if the Grid has never been laid out.

Related XML Attributes

public int getRequestedColumnWidth ()

Added in API level 16

Return the requested width of a column in the grid.

This may not be the actual column width used. Use getColumnWidth() to retrieve the current real width of a column.

Related XML Attributes
Returns
  • The requested column width in pixels

public int getRequestedHorizontalSpacing ()

Added in API level 16

Returns the requested amount of horizontal spacing between each item in the grid.

The value returned may have been supplied during inflation as part of a style, the default GridView style, or by a call to setHorizontalSpacing(int). If layout is not yet complete or if GridView calculated a different horizontal spacing from what was requested, this may return a different value from getHorizontalSpacing().

Related XML Attributes
Returns
  • The currently requested horizontal spacing between items, in pixels

public int getStretchMode ()

Added in API level 1

public int getVerticalSpacing ()

Added in API level 16

Returns the amount of vertical spacing between each item in the grid.

Related XML Attributes
Returns
  • The vertical spacing between items in pixels

public void onInitializeAccessibilityEvent (AccessibilityEvent event)

Added in API level 14

Initializes an AccessibilityEvent with information about this View which is the event source. In other words, the source of an accessibility event is the view whose state change triggered firing the event.

Example: Setting the password property of an event in addition to properties set by the super implementation:

 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
     super.onInitializeAccessibilityEvent(event);
     event.setPassword(true);
 }

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its onInitializeAccessibilityEvent(View, AccessibilityEvent) is responsible for handling this call.

Note: Always call the super implementation before adding information to the event, in case the default implementation has basic information to add.

Parameters
event The event to initialize.

public void onInitializeAccessibilityNodeInfo (AccessibilityNodeInfo info)

Added in API level 14

Initializes an AccessibilityNodeInfo with information about this view. The base implementation sets:

Subclasses should override this method, call the super implementation, and set additional attributes.

If an View.AccessibilityDelegate has been specified via calling setAccessibilityDelegate(AccessibilityDelegate) its onInitializeAccessibilityNodeInfo(View, AccessibilityNodeInfo) is responsible for handling this call.

Parameters
info The instance to initialize.

public void onInitializeAccessibilityNodeInfoForItem (View view, int position, AccessibilityNodeInfo info)

Added in API level 19

Initializes an AccessibilityNodeInfo with information about a particular item in the list.

Parameters
view View representing the list item.
position Position of the list item within the adapter.
info Node info to populate.

public boolean onKeyDown (int keyCode, KeyEvent event)

Added in API level 1

Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released, if the view is enabled and clickable.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onKeyMultiple (int keyCode, int repeatCount, KeyEvent event)

Added in API level 1

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false (doesn't handle the event).

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
repeatCount The number of times the action was made.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public boolean onKeyUp (int keyCode, KeyEvent event)

Added in API level 1

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER or KEYCODE_ENTER is released.

Key presses in software keyboards will generally NOT trigger this listener, although some may elect to do so in some situations. Do not rely on this to catch software key presses.

Parameters
keyCode A key code that represents the button pressed, from KeyEvent.
event The KeyEvent object that defines the button action.
Returns
  • If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

public void setAdapter (ListAdapter adapter)

Added in API level 1

Sets the data behind this GridView.

Parameters
adapter the adapter providing the grid's data

public void setColumnWidth (int columnWidth)

Added in API level 1

Set the width of columns in the grid.

Related XML Attributes
Parameters
columnWidth The column width, in pixels.

public void setGravity (int gravity)

Added in API level 1

Set the gravity for this grid. Gravity describes how the child views are horizontally aligned. Defaults to Gravity.LEFT

Related XML Attributes
Parameters
gravity the gravity to apply to this grid's children

public void setHorizontalSpacing (int horizontalSpacing)

Added in API level 1

Set the amount of horizontal (x) spacing to place between each item in the grid.

Related XML Attributes
Parameters
horizontalSpacing The amount of horizontal space between items, in pixels.

public void setNumColumns (int numColumns)

Added in API level 1

Set the number of columns in the grid

Related XML Attributes
Parameters
numColumns The desired number of columns.

public void setRemoteViewsAdapter (Intent intent)

Added in API level 11

Sets up this AbsListView to use a remote views adapter which connects to a RemoteViewsService through the specified intent.

Parameters
intent the intent used to identify the RemoteViewsService for the adapter to connect to.

public void setSelection (int position)

Added in API level 1

Sets the currently selected item

Parameters
position Index (starting at 0) of the data item to be selected. If in touch mode, the item will not be selected but it will still be positioned appropriately.

public void setStretchMode (int stretchMode)

Added in API level 1

Control how items are stretched to fill their space.

Related XML Attributes

public void setVerticalSpacing (int verticalSpacing)

Added in API level 1

Set the amount of vertical (y) spacing to place between each item in the grid.

Related XML Attributes
Parameters
verticalSpacing The amount of vertical space between items, in pixels.

public void smoothScrollByOffset (int offset)

Added in API level 11

Smoothly scroll to the specified adapter position offset. The view will scroll such that the indicated position is displayed.

Parameters
offset The amount to offset from the adapter position to scroll to.

public void smoothScrollToPosition (int position)

Added in API level 8

Smoothly scroll to the specified adapter position. The view will scroll such that the indicated position is displayed.

Parameters
position Scroll to this adapter position.

Protected Methods

protected void attachLayoutAnimationParameters (View child, ViewGroup.LayoutParams params, int index, int count)

Added in API level 1

Subclasses should override this method to set layout animation parameters on the supplied child.

Parameters
child the child to associate with animation parameters
params the child's layout parameters which hold the animation parameters
index the index of the child in the view group
count the number of children in the view group

protected int computeVerticalScrollExtent ()

Added in API level 1

Compute the vertical extent of the vertical scrollbar's thumb within the vertical range. This value is used to compute the length of the thumb within the scrollbar's track.

The range is expressed in arbitrary units that must be the same as the units used by computeVerticalScrollRange() and computeVerticalScrollOffset().

The default extent is the drawing height of this view.

Returns
  • the vertical extent of the scrollbar's thumb

protected int computeVerticalScrollOffset ()

Added in API level 1

Compute the vertical offset of the vertical scrollbar's thumb within the horizontal range. This value is used to compute the position of the thumb within the scrollbar's track.

The range is expressed in arbitrary units that must be the same as the units used by computeVerticalScrollRange() and computeVerticalScrollExtent().

The default offset is the scroll offset of this view.

Returns
  • the vertical offset of the scrollbar's thumb

protected int computeVerticalScrollRange ()

Added in API level 1

Compute the vertical range that the vertical scrollbar represents.

The range is expressed in arbitrary units that must be the same as the units used by computeVerticalScrollExtent() and computeVerticalScrollOffset().

Returns
  • the total vertical range represented by the vertical scrollbar

    The default range is the drawing height of this view.

protected void layoutChildren ()

Added in API level 1

Subclasses must override this method to layout their children.

protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect)

Added in API level 1

Called by the view system when the focus state of this view changes. When the focus change event is caused by directional navigation, direction and previouslyFocusedRect provide insight into where the focus is coming from. When overriding, be sure to call up through to the super class so that the standard focus handling will occur.

Parameters
gainFocus True if the View has focus; false otherwise.
direction The direction focus has moved when requestFocus() is called to give this view focus. Values are FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT, FOCUS_FORWARD, or FOCUS_BACKWARD. It may not always apply, in which case use the default.
previouslyFocusedRect The rectangle, in this view's coordinate system, of the previously focused view. If applicable, this will be passed in as finer grained information about where the focus is coming from (in addition to direction). Will be null otherwise.

protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

Added in API level 1

Measure the view and its content to determine the measured width and the measured height. This method is invoked by measure(int, int) and should be overriden by subclasses to provide accurate and efficient measurement of their contents.

CONTRACT: When overriding this method, you must call setMeasuredDimension(int, int) to store the measured width and height of this view. Failure to do so will trigger an IllegalStateException, thrown by measure(int, int). Calling the superclass' onMeasure(int, int) is a valid use.

The base class implementation of measure defaults to the background size, unless a larger size is allowed by the MeasureSpec. Subclasses should override onMeasure(int, int) to provide better measurements of their content.

If this method is overridden, it is the subclass's responsibility to make sure the measured height and width are at least the view's minimum height and width (getSuggestedMinimumHeight() and getSuggestedMinimumWidth()).

Parameters
widthMeasureSpec horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.
heightMeasureSpec vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.