GridView


public class GridView
extends AbsListView

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.AdapterView<android.widget.ListAdapter>
         ↳ android.widget.AbsListView
           ↳ android.widget.GridView


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

android:columnWidth Specifies the fixed width for each column. 
android:gravity Specifies the gravity within each cell. 
android:horizontalSpacing Defines the default horizontal spacing between columns. 
android:numColumns Defines how many columns to show. 
android:stretchMode Defines how columns should stretch to fill the available empty space, if any. 
android:verticalSpacing Defines the default vertical spacing between rows. 

Inherited XML attributes

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.

Inherited constants

Inherited fields

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

CharSequence getAccessibilityClassName()

A TYPE_VIEW_SCROLLED event should be sent whenever a scroll happens, even if the mFirstPosition and the child count have not changed.

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 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 KeyEvent.KEYCODE_DPAD_CENTER or KeyEvent.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 KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER or KeyEvent.KEYCODE_SPACE 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.

Inherited methods

XML attributes

android:columnWidth

Specifies the fixed width for each column.

May 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), and mm (millimeters).

Related methods:

android:gravity

Specifies the gravity within each cell.

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

ConstantValueDescription
bottom50Push object to the bottom of its container, not changing its size.
center11Place the object in the center of its container in both the vertical and horizontal axis, not changing its size.
center_horizontal1Place object in the horizontal center of its container, not changing its size.
center_vertical10Place object in the vertical center of its container, not changing its size.
clip_horizontal8Additional 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.
clip_vertical80Additional 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.
end800005Push object to the end of its container, not changing its size.
fill77Grow the horizontal and vertical size of the object if needed so it completely fills its container.
fill_horizontal7Grow the horizontal size of the object if needed so it completely fills its container.
fill_vertical70Grow the vertical size of the object if needed so it completely fills its container.
left3Push object to the left of its container, not changing its size.
right5Push object to the right of its container, not changing its size.
start800003Push object to the beginning of its container, not changing its size.
top30Push object to the top of its container, not changing its size.

Related methods:

android:horizontalSpacing

Defines the default horizontal spacing between columns.

May 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), and mm (millimeters).

Related methods:

android:numColumns

Defines how many columns to show.

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

Must be one of the following constant values.

ConstantValueDescription
auto_fitffffffffDisplay as many columns as possible to fill the available space.

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
columnWidth2Each column is stretched equally.
none0Stretching is disabled.
spacingWidth1The spacing between each column is stretched.
spacingWidthUniform3The spacing between each column is uniformly stretched..

Related methods:

android:verticalSpacing

Defines the default vertical spacing between rows.

May 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), and mm (millimeters).

Related methods:

Constants

AUTO_FIT

Added in API level 1
public static final int AUTO_FIT

Creates as many columns as can fit on screen.

See also:

Constant Value: -1 (0xffffffff)

NO_STRETCH

Added in API level 1
public static final int NO_STRETCH

Disables stretching.

Constant Value: 0 (0x00000000)

STRETCH_COLUMN_WIDTH

Added in API level 1
public static final int STRETCH_COLUMN_WIDTH

Stretches columns.

Constant Value: 2 (0x00000002)

STRETCH_SPACING

Added in API level 1
public static final int STRETCH_SPACING

Stretches the spacing between columns.

Constant Value: 1 (0x00000001)

STRETCH_SPACING_UNIFORM

Added in API level 3
public static final int STRETCH_SPACING_UNIFORM

Stretches the spacing between columns. The spacing is uniform.

Constant Value: 3 (0x00000003)

Public constructors

GridView

Added in API level 1
public GridView (Context context)

Parameters
context Context

GridView

Added in API level 1
public GridView (Context context, 
                AttributeSet attrs)

Parameters
context Context

attrs AttributeSet

GridView

Added in API level 1
public GridView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

GridView

Added in API level 21
public GridView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr, 
                int defStyleRes)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

defStyleRes int

Public methods

getAccessibilityClassName

Added in API level 23
public CharSequence getAccessibilityClassName ()

A TYPE_VIEW_SCROLLED event should be sent whenever a scroll happens, even if the mFirstPosition and the child count have not changed.

Returns
CharSequence

getAdapter

Added in API level 1
public ListAdapter getAdapter ()

Returns the adapter currently associated with this widget.

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

getColumnWidth

Added in API level 16
public int getColumnWidth ()

Return the width of a column in the grid.

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

Related XML Attributes:

Returns
int The column width in pixels

getGravity

Added in API level 16
public int getGravity ()

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

Related XML Attributes:

Returns
int the gravity that will be applied to this grid's children

getHorizontalSpacing

Added in API level 16
public int getHorizontalSpacing ()

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
int Current horizontal spacing between each item in pixels

getNumColumns

Added in API level 11
public int getNumColumns ()

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

Related XML Attributes:

Returns
int

See also:

getRequestedColumnWidth

Added in API level 16
public int getRequestedColumnWidth ()

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
int The requested column width in pixels

getRequestedHorizontalSpacing

Added in API level 16
public int getRequestedHorizontalSpacing ()

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
int The currently requested horizontal spacing between items, in pixels

getStretchMode

Added in API level 1
public int getStretchMode ()

Returns
int Value is NO_STRETCH, STRETCH_SPACING, STRETCH_COLUMN_WIDTH, or STRETCH_SPACING_UNIFORM

getVerticalSpacing

Added in API level 16
public int getVerticalSpacing ()

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

Related XML Attributes:

Returns
int The vertical spacing between items in pixels

onInitializeAccessibilityNodeInfoForItem

Added in API level 19
public void onInitializeAccessibilityNodeInfoForItem (View view, 
                int position, 
                AccessibilityNodeInfo info)

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

Parameters
view View: View representing the list item.

position int: Position of the list item within the adapter.

info AccessibilityNodeInfo: Node info to populate.

onKeyDown

Added in API level 1
public boolean onKeyDown (int keyCode, 
                KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyDown(): perform press of the view when KeyEvent.KEYCODE_DPAD_CENTER or KeyEvent.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 int: a key code that represents the button pressed, from KeyEvent

event KeyEvent: the KeyEvent object that defines the button action

Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

onKeyMultiple

Added in API level 1
public boolean onKeyMultiple (int keyCode, 
                int repeatCount, 
                KeyEvent event)

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 int: A key code that represents the button pressed, from KeyEvent.

repeatCount int: The number of times the action was made.

event KeyEvent: The KeyEvent object that defines the button action.

Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

onKeyUp

Added in API level 1
public boolean onKeyUp (int keyCode, 
                KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER or KeyEvent.KEYCODE_SPACE 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 int: A key code that represents the button pressed, from KeyEvent.

event KeyEvent: The KeyEvent object that defines the button action.

Returns
boolean If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

setAdapter

Added in API level 1
public void setAdapter (ListAdapter adapter)

Sets the data behind this GridView.

Parameters
adapter ListAdapter: the adapter providing the grid's data

setColumnWidth

Added in API level 1
public void setColumnWidth (int columnWidth)

Set the width of columns in the grid.

Related XML Attributes:

Parameters
columnWidth int: The column width, in pixels.

setGravity

Added in API level 1
public void setGravity (int gravity)

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

Related XML Attributes:

Parameters
gravity int: the gravity to apply to this grid's children

setHorizontalSpacing

Added in API level 1
public void setHorizontalSpacing (int horizontalSpacing)

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

Related XML Attributes:

Parameters
horizontalSpacing int: The amount of horizontal space between items, in pixels.

setNumColumns

Added in API level 1
public void setNumColumns (int numColumns)

Set the number of columns in the grid

Related XML Attributes:

Parameters
numColumns int: The desired number of columns.

setRemoteViewsAdapter

Added in API level 11
public void setRemoteViewsAdapter (Intent intent)

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

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

setSelection

Added in API level 1
public void setSelection (int position)

Sets the currently selected item

Parameters
position int: 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.

setStretchMode

Added in API level 1
public void setStretchMode (int stretchMode)

Control how items are stretched to fill their space.

Related XML Attributes:

Parameters
stretchMode int: Either NO_STRETCH, STRETCH_SPACING, STRETCH_SPACING_UNIFORM, or STRETCH_COLUMN_WIDTH. Value is NO_STRETCH, STRETCH_SPACING, STRETCH_COLUMN_WIDTH, or STRETCH_SPACING_UNIFORM

setVerticalSpacing

Added in API level 1
public void setVerticalSpacing (int verticalSpacing)

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

Related XML Attributes:

Parameters
verticalSpacing int: The amount of vertical space between items, in pixels.

smoothScrollByOffset

Added in API level 11
public void smoothScrollByOffset (int offset)

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

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

smoothScrollToPosition

Added in API level 8
public void smoothScrollToPosition (int position)

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

Parameters
position int: Scroll to this adapter position.

Protected methods

attachLayoutAnimationParameters

Added in API level 1
protected 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.

Parameters
child View: the child to associate with animation parameters

params ViewGroup.LayoutParams: the child's layout parameters which hold the animation parameters

index int: the index of the child in the view group

count int: the number of children in the view group

computeVerticalScrollExtent

Added in API level 1
protected int computeVerticalScrollExtent ()

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
int the vertical extent of the scrollbar's thumb

computeVerticalScrollOffset

Added in API level 1
protected int computeVerticalScrollOffset ()

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
int the vertical offset of the scrollbar's thumb

computeVerticalScrollRange

Added in API level 1
protected int computeVerticalScrollRange ()

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
int the total vertical range represented by the vertical scrollbar

The default range is the drawing height of this view.

layoutChildren

Added in API level 1
protected void layoutChildren ()

Subclasses must override this method to layout their children.

onFocusChanged

Added in API level 1
protected void onFocusChanged (boolean gainFocus, 
                int direction, 
                Rect previouslyFocusedRect)

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.
If you override this method you must call through to the superclass implementation.

Parameters
gainFocus boolean: True if the View has focus; false otherwise.

direction int: The direction focus has moved when requestFocus() is called to give this view focus. Values are View.FOCUS_UP, View.FOCUS_DOWN, View.FOCUS_LEFT, View.FOCUS_RIGHT, View.FOCUS_FORWARD, or View.FOCUS_BACKWARD. It may not always apply, in which case use the default. Value is View.FOCUS_BACKWARD, View.FOCUS_FORWARD, View.FOCUS_LEFT, View.FOCUS_UP, View.FOCUS_RIGHT, or View.FOCUS_DOWN

previouslyFocusedRect Rect: 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.

onMeasure

Added in API level 1
protected void onMeasure (int widthMeasureSpec, 
                int heightMeasureSpec)

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 overridden 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 int: horizontal space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.

heightMeasureSpec int: vertical space requirements as imposed by the parent. The requirements are encoded with View.MeasureSpec.