Most visited

Recently visited

Added in API level 1

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

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.

Inherited constants

From class android.widget.AbsListView
From class android.widget.AdapterView
From class android.view.ViewGroup
From class android.view.View

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

CharSequence getAccessibilityClassName()

Return the class name of this object to be used for accessibility purposes.

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 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, KEYCODE_ENTER or 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

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.text.TextWatcher
From interface android.view.ViewTreeObserver.OnGlobalLayoutListener
From interface android.widget.Filter.FilterListener
From interface android.view.ViewTreeObserver.OnTouchModeChangeListener
From interface android.view.ViewParent
From interface android.view.ViewManager
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.accessibility.AccessibilityEventSource

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

AUTO_FIT

Added in API level 1
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
int NO_STRETCH

Disables stretching.

See also:

Constant Value: 0 (0x00000000)

STRETCH_COLUMN_WIDTH

Added in API level 1
int STRETCH_COLUMN_WIDTH

Stretches columns.

See also:

Constant Value: 2 (0x00000002)

STRETCH_SPACING

Added in API level 1
int STRETCH_SPACING

Stretches the spacing between columns.

See also:

Constant Value: 1 (0x00000001)

STRETCH_SPACING_UNIFORM

Added in API level 3
int STRETCH_SPACING_UNIFORM

Stretches the spacing between columns. The spacing is uniform.

See also:

Constant Value: 3 (0x00000003)

Public constructors

GridView

Added in API level 1
GridView (Context context)

Parameters
context Context

GridView

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

Parameters
context Context
attrs AttributeSet

GridView

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

Parameters
context Context
attrs AttributeSet
defStyleAttr int

GridView

Added in API level 21
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
CharSequence getAccessibilityClassName ()

Return the class name of this object to be used for accessibility purposes. Subclasses should only override this if they are implementing something that should be seen as a completely new class of view when used by accessibility, unrelated to the class it is deriving from. This is used to fill in AccessibilityNodeInfo.setClassName.

Returns
CharSequence

getAdapter

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

See also:

getGravity

Added in API level 16
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
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

See also:

getNumColumns

Added in API level 11
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
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

See also:

getRequestedHorizontalSpacing

Added in API level 16
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

See also:

getStretchMode

Added in API level 1
int getStretchMode ()

Returns
int

getVerticalSpacing

Added in API level 16
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

See also:

onInitializeAccessibilityNodeInfoForItem

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

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
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
boolean onKeyUp (int keyCode, 
                KeyEvent event)

Default implementation of KeyEvent.Callback.onKeyUp(): perform clicking of the view when KEYCODE_DPAD_CENTER, KEYCODE_ENTER or 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
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
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
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
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
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
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
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
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.

setVerticalSpacing

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

See also:

smoothScrollByOffset

Added in API level 11
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
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
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
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
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
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
void layoutChildren ()

Subclasses must override this method to layout their children.

onFocusChanged

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

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 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 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
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.

Hooray!