Android Studio
Added in API level 1

TableLayout


public class TableLayout
extends LinearLayout

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.LinearLayout
         ↳ android.widget.TableLayout


A layout that arranges its children into rows and columns. A TableLayout consists of a number of TableRow objects, each defining a row (actually, you can have other children, which will be explained below). TableLayout containers do not display border lines for their rows, columns, or cells. Each row has zero or more cells; each cell can hold one View object. The table has as many columns as the row with the most cells. A table can leave cells empty. Cells can span columns, as they can in HTML.

The width of a column is defined by the row with the widest cell in that column. However, a TableLayout can specify certain columns as shrinkable or stretchable by calling setColumnShrinkable() or setColumnStretchable(). If marked as shrinkable, the column width can be shrunk to fit the table into its parent object. If marked as stretchable, it can expand in width to fit any extra space. The total width of the table is defined by its parent container. It is important to remember that a column can be both shrinkable and stretchable. In such a situation, the column will change its size to always use up the available space, but never more. Finally, you can hide a column by calling setColumnCollapsed().

The children of a TableLayout cannot specify the layout_width attribute. Width is always MATCH_PARENT. However, the layout_height attribute can be defined by a child; default value is ViewGroup.LayoutParams.WRAP_CONTENT. If the child is a TableRow, then the height is always ViewGroup.LayoutParams.WRAP_CONTENT.

Cells must be added to a row in increasing column order, both in code and XML. Column numbers are zero-based. If you don't specify a column number for a child cell, it will autoincrement to the next available column. If you skip a column number, it will be considered an empty cell in that row. See the TableLayout examples in ApiDemos for examples of creating tables in XML.

Although the typical child of a TableLayout is a TableRow, you can actually use any View subclass as a direct child of TableLayout. The View will be displayed as a single row that spans all the table columns.

Summary

Nested classes

class TableLayout.LayoutParams

This set of layout parameters enforces the width of each child to be ViewGroup.LayoutParams.MATCH_PARENT and the height of each child to be ViewGroup.LayoutParams.WRAP_CONTENT, but only if the height is not specified. 

XML attributes

android:collapseColumns The zero-based index of the columns to collapse. 
android:shrinkColumns The zero-based index of the columns to shrink. 
android:stretchColumns The zero-based index of the columns to stretch. 

Inherited XML attributes

From class android.view.View android:accessibilityHeading Whether or not this view is a heading for accessibility purposes.  android:accessibilityLiveRegion Indicates to accessibility services whether the user should be notified when this view changes.  android:accessibilityPaneTitle The title this view should present to accessibility as a pane title.  android:accessibilityTraversalAfter Sets the id of a view that screen readers are requested to visit before this view.  android:accessibilityTraversalBefore Sets the id of a view that screen readers are requested to visit after this view.  android:allowClickWhenDisabled Whether or not allow clicks on disabled view.  android:alpha alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque).  android:autoHandwritingEnabled Whether or not the auto handwriting initiation is enabled in this View.  android:autofillHints Describes the content of a view so that a autofill service can fill in the appropriate data.  android:autofilledHighlight Drawable to be drawn over the view to mark it as autofilled May be a reference to another resource, in the form "@[+][package:]type/name" or a theme attribute in the form "?[package:]type/name".  android:background A drawable to use as the background.  android:backgroundTint Tint to apply to the background.  android:backgroundTintMode Blending mode used to apply the background tint.  android:clickable Defines whether this view reacts to click events.  android:clipToOutline Whether the View's Outline should be used to clip the contents of the View.  android:contentDescription Defines text that briefly describes content of the view.  android:contextClickable Defines whether this view reacts to context click events.  android:defaultFocusHighlightEnabled Whether this View should use a default focus highlight when it gets focused but doesn't have R.attr.state_focused defined in its background.  android:drawingCacheQuality Defines the quality of translucent drawing caches.  android:duplicateParentState When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself.  android:elevation base z depth of the view.  android:fadeScrollbars Defines whether to fade out scrollbars when they are not in use.  android:fadingEdgeLength Defines the length of the fading edges.  android:filterTouchesWhenObscured Specifies whether to filter touches when the view's window is obscured by another visible window.  android:fitsSystemWindows Boolean internal attribute to adjust view layout based on system windows such as the status bar.  android:focusable Controls whether a view can take focus.  android:focusableInTouchMode Boolean that controls whether a view can take focus while in touch mode.  android:focusedByDefault Whether this view is a default-focus view.  android:forceHasOverlappingRendering Whether this view has elements that may overlap when drawn.  android:foreground Defines the drawable to draw over the content.  android:foregroundGravity Defines the gravity to apply to the foreground drawable.  android:foregroundTint Tint to apply to the foreground.  android:foregroundTintMode Blending mode used to apply the foreground tint.  android:hapticFeedbackEnabled Boolean that controls whether a view should have haptic feedback enabled for events such as long presses.  android:id Supply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById()android:importantForAccessibility Describes whether or not this view is important for accessibility.  android:importantForAutofill Hints the Android System whether the view node associated with this View should be included in a view structure used for autofill purposes.  android:importantForContentCapture Hints the Android System whether the view node associated with this View should be use for content capture purposes.  android:isCredential This is deprecated. The isCredential attr is no longer needed. May be a boolean value, such as "true" or "false".  android:isScrollContainer Set this if the view will serve as a scrolling container, meaning that it can be resized to shrink its overall window so that there will be space for an input method.  android:keepScreenOn Controls whether the view's window should keep the screen on while visible.  android:keyboardNavigationCluster Whether this view is a root of a keyboard navigation cluster.  android:layerType Specifies the type of layer backing this view.  android:layoutDirection Defines the direction of layout drawing.  android:longClickable Defines whether this view reacts to long click events.  android:minHeight Defines the minimum height of the view.  android:minWidth Defines the minimum width of the view.  android:nextClusterForward Defines the next keyboard navigation cluster.  android:nextFocusDown Defines the next view to give focus to when the next focus is View.FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:nextFocusForward Defines the next view to give focus to when the next focus is View.FOCUS_FORWARD If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:nextFocusLeft Defines the next view to give focus to when the next focus is View.FOCUS_LEFTandroid:nextFocusRight Defines the next view to give focus to when the next focus is View.FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:nextFocusUp Defines the next view to give focus to when the next focus is View.FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a RuntimeException will result when the reference is accessed.  android:onClick This is deprecated. View actually traverses the Context hierarchy looking for the relevant method, which is fragile (an intermediate ContextWrapper adding a same-named method would change behavior) and restricts bytecode optimizers such as R8. Instead, use View.setOnClickListener.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;  android:outlineAmbientShadowColor Sets the color of the ambient shadow that is drawn when the view has a positive Z or elevation value.  android:outlineSpotShadowColor Sets the color of the spot shadow that is drawn when the view has a positive Z or elevation value.  android:padding Sets the padding, in pixels, of all four edges.  android:paddingBottom Sets the padding, in pixels, of the bottom edge; see R.attr.paddingandroid:paddingEnd Sets the padding, in pixels, of the end edge; see R.attr.paddingandroid:paddingHorizontal Sets the padding, in pixels, of the left and right edges; see R.attr.paddingandroid:paddingLeft Sets the padding, in pixels, of the left edge; see R.attr.paddingandroid:paddingRight Sets the padding, in pixels, of the right edge; see R.attr.paddingandroid:paddingStart Sets the padding, in pixels, of the start edge; see R.attr.paddingandroid:paddingTop Sets the padding, in pixels, of the top edge; see R.attr.paddingandroid:paddingVertical Sets the padding, in pixels, of the top and bottom edges; see R.attr.paddingandroid:preferKeepClear

Sets a preference to keep the bounds of this view clear from floating windows above this view's window.  android:requiresFadingEdge Defines which edges should be faded on scrolling.  android:rotation rotation of the view, in degrees.  android:rotationX rotation of the view around the x axis, in degrees.  android:rotationY rotation of the view around the y axis, in degrees.  android:saveEnabled If false, no state will be saved for this view when it is being frozen.  android:scaleX scale of the view in the x direction.  android:scaleY scale of the view in the y direction.  android:screenReaderFocusable Whether this view should be treated as a focusable unit by screen reader accessibility tools.  android:scrollIndicators Defines which scroll indicators should be displayed when the view can be scrolled.  android:scrollX The initial horizontal scroll offset, in pixels.  android:scrollY The initial vertical scroll offset, in pixels.  android:scrollbarAlwaysDrawHorizontalTrack Defines whether the horizontal scrollbar track should always be drawn.  android:scrollbarAlwaysDrawVerticalTrack Defines whether the vertical scrollbar track should always be drawn.  android:scrollbarDefaultDelayBeforeFade Defines the delay in milliseconds that a scrollbar waits before fade out.  android:scrollbarFadeDuration Defines the delay in milliseconds that a scrollbar takes to fade out.  android:scrollbarSize Sets the width of vertical scrollbars and height of horizontal scrollbars.  android:scrollbarStyle Controls the scrollbar style and position.  android:scrollbarThumbHorizontal Defines the horizontal scrollbar thumb drawable.  android:scrollbarThumbVertical Defines the vertical scrollbar thumb drawable.  android:scrollbarTrackHorizontal Defines the horizontal scrollbar track drawable.  android:scrollbarTrackVertical Defines the vertical scrollbar track drawable.  android:scrollbars Defines which scrollbars should be displayed on scrolling or not.  android:soundEffectsEnabled Boolean that controls whether a view should have sound effects enabled for events such as clicking and touching.  android:stateListAnimator Sets the state-based animator for the View.  android:supplementalDescription Provides brief supplemental information for the view, such as the purpose of the view when that purpose is not conveyed within its textual representation.  android:tag Supply a tag for this view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag()android:textAlignment Defines the alignment of the text.  android:textDirection Defines the direction of the text.  android:theme Specifies a theme override for a view.  android:tooltipText Defines text displayed in a small popup window on hover or long press.  android:transformPivotX x location of the pivot point around which the view will rotate and scale.  android:transformPivotY y location of the pivot point around which the view will rotate and scale.  android:transitionName Names a View such that it can be identified for Transitions.  android:translationX translation in x of the view.  android:translationY translation in y of the view.  android:translationZ translation in z of the view.  android:visibility Controls the initial visibility of the view. 

Inherited constants

Inherited fields

Public constructors

TableLayout(Context context)

Creates a new TableLayout for the given context.

TableLayout(Context context, AttributeSet attrs)

Creates a new TableLayout for the given context and with the specified set attributes.

Public methods

void addView(View child, int index)

Adds a child view.

void addView(View child, ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

void addView(View child)

Adds a child view.

void addView(View child, int index, ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

TableLayout.LayoutParams generateLayoutParams(AttributeSet attrs)

Returns a new set of layout parameters based on the supplied attributes set.

CharSequence getAccessibilityClassName()

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

boolean isColumnCollapsed(int columnIndex)

Returns the collapsed state of the specified column.

boolean isColumnShrinkable(int columnIndex)

Returns whether the specified column is shrinkable or not.

boolean isColumnStretchable(int columnIndex)

Returns whether the specified column is stretchable or not.

boolean isShrinkAllColumns()

Indicates whether all columns are shrinkable or not.

boolean isStretchAllColumns()

Indicates whether all columns are stretchable or not.

void requestLayout()

Call this when something has changed which has invalidated the layout of this view.

void setColumnCollapsed(int columnIndex, boolean isCollapsed)

Collapses or restores a given column.

void setColumnShrinkable(int columnIndex, boolean isShrinkable)

Makes the given column shrinkable or not.

void setColumnStretchable(int columnIndex, boolean isStretchable)

Makes the given column stretchable or not.

void setOnHierarchyChangeListener(ViewGroup.OnHierarchyChangeListener listener)

Register a callback to be invoked when a child is added to or removed from this view.

void setShrinkAllColumns(boolean shrinkAllColumns)

Convenience method to mark all columns as shrinkable.

void setStretchAllColumns(boolean stretchAllColumns)

Convenience method to mark all columns as stretchable.

Protected methods

boolean checkLayoutParams(ViewGroup.LayoutParams p)

LinearLayout.LayoutParams generateDefaultLayoutParams()

Returns a set of layout parameters with a width of ViewGroup.LayoutParams.MATCH_PARENT, and a height of ViewGroup.LayoutParams.WRAP_CONTENT.

LinearLayout.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p)

Returns a safe set of layout parameters based on the supplied layout params.

void onLayout(boolean changed, int l, int t, int r, int b)

Called from layout when this view should assign a size and position to each of its children.

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:collapseColumns

The zero-based index of the columns to collapse. The column indices must be separated by a comma: 1, 2, 5. Illegal and duplicate indices are ignored.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

android:shrinkColumns

The zero-based index of the columns to shrink. The column indices must be separated by a comma: 1, 2, 5. Illegal and duplicate indices are ignored. You can shrink all columns by using the value "*" instead. Note that a column can be marked stretchable and shrinkable at the same time.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

android:stretchColumns

The zero-based index of the columns to stretch. The column indices must be separated by a comma: 1, 2, 5. Illegal and duplicate indices are ignored. You can stretch all columns by using the value "*" instead. Note that a column can be marked stretchable and shrinkable at the same time.

May be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character;

Related methods:

Public constructors

TableLayout

Added in API level 1
public TableLayout (Context context)

Creates a new TableLayout for the given context.

Parameters
context Context: the application environment

TableLayout

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

Creates a new TableLayout for the given context and with the specified set attributes.

Parameters
context Context: the application environment
attrs AttributeSet: a collection of attributes

Public methods

addView

Added in API level 1
public void addView (View child, 
                int index)

Adds a child view. If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child.

Note: do not invoke this method from View.draw(android.graphics.Canvas), View.onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child View: the child view to add
index int: the position at which to add the child

addView

Added in API level 1
public void addView (View child, 
                ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

Note: do not invoke this method from View.draw(android.graphics.Canvas), View.onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child View: the child view to add
params ViewGroup.LayoutParams: the layout parameters to set on the child

addView

Added in API level 1
public void addView (View child)

Adds a child view. If no layout parameters are already set on the child, the default parameters for this ViewGroup are set on the child.

Note: do not invoke this method from View.draw(android.graphics.Canvas), View.onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child View: the child view to add

addView

Added in API level 1
public void addView (View child, 
                int index, 
                ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

Note: do not invoke this method from View.draw(android.graphics.Canvas), View.onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child View: the child view to add
index int: the position at which to add the child or -1 to add last
params ViewGroup.LayoutParams: the layout parameters to set on the child

generateLayoutParams

Added in API level 1
public TableLayout.LayoutParams generateLayoutParams (AttributeSet attrs)

Returns a new set of layout parameters based on the supplied attributes set.

Parameters
attrs AttributeSet: the attributes to build the layout parameters from
Returns
TableLayout.LayoutParams an instance of ViewGroup.LayoutParams or one of its descendants

getAccessibilityClassName

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

isColumnCollapsed

Added in API level 1
public boolean isColumnCollapsed (int columnIndex)

Returns the collapsed state of the specified column.

Parameters
columnIndex int: the index of the column
Returns
boolean true if the column is collapsed, false otherwise

isColumnShrinkable

Added in API level 1
public boolean isColumnShrinkable (int columnIndex)

Returns whether the specified column is shrinkable or not.

Parameters
columnIndex int: the index of the column
Returns
boolean true if the column is shrinkable, false otherwise. Default is false.

isColumnStretchable

Added in API level 1
public boolean isColumnStretchable (int columnIndex)

Returns whether the specified column is stretchable or not.

Parameters
columnIndex int: the index of the column
Returns
boolean true if the column is stretchable, false otherwise

isShrinkAllColumns

Added in API level 1
public boolean isShrinkAllColumns ()

Indicates whether all columns are shrinkable or not.

Related XML Attributes:

Returns
boolean true if all columns are shrinkable, false otherwise

isStretchAllColumns

Added in API level 1
public boolean isStretchAllColumns ()

Indicates whether all columns are stretchable or not.

Related XML Attributes:

Returns
boolean true if all columns are stretchable, false otherwise

requestLayout

Added in API level 1
public void requestLayout ()

Call this when something has changed which has invalidated the layout of this view. This will schedule a layout pass of the view tree. This should not be called while the view hierarchy is currently in a layout pass (isInLayout(). If layout is happening, the request may be honored at the end of the current layout pass (and then layout will run again) or after the current frame is drawn and the next layout occurs.

Subclasses which override this method should call the superclass method to handle possible request-during-layout errors correctly.

.
If you override this method you must call through to the superclass implementation.

setColumnCollapsed

Added in API level 1
public void setColumnCollapsed (int columnIndex, 
                boolean isCollapsed)

Collapses or restores a given column. When collapsed, a column does not appear on screen and the extra space is reclaimed by the other columns. A column is collapsed/restored only when it belongs to a TableRow.

Calling this method requests a layout operation.

Related XML Attributes:

Parameters
columnIndex int: the index of the column
isCollapsed boolean: true if the column must be collapsed, false otherwise

setColumnShrinkable

Added in API level 1
public void setColumnShrinkable (int columnIndex, 
                boolean isShrinkable)

Makes the given column shrinkable or not. When a row is too wide, the table can reclaim extra space from shrinkable columns.

Calling this method requests a layout operation.

Related XML Attributes:

Parameters
columnIndex int: the index of the column
isShrinkable boolean: true if the column must be shrinkable, false otherwise. Default is false.

setColumnStretchable

Added in API level 1
public void setColumnStretchable (int columnIndex, 
                boolean isStretchable)

Makes the given column stretchable or not. When stretchable, a column takes up as much as available space as possible in its row.

Calling this method requests a layout operation.

Related XML Attributes:

Parameters
columnIndex int: the index of the column
isStretchable boolean: true if the column must be stretchable, false otherwise. Default is false.

setOnHierarchyChangeListener

Added in API level 1
public void setOnHierarchyChangeListener (ViewGroup.OnHierarchyChangeListener listener)

Register a callback to be invoked when a child is added to or removed from this view.

Parameters
listener ViewGroup.OnHierarchyChangeListener: the callback to invoke on hierarchy change

setShrinkAllColumns

Added in API level 1
public void setShrinkAllColumns (boolean shrinkAllColumns)

Convenience method to mark all columns as shrinkable.

Related XML Attributes:

Parameters
shrinkAllColumns boolean: true to mark all columns shrinkable

setStretchAllColumns

Added in API level 1
public void setStretchAllColumns (boolean stretchAllColumns)

Convenience method to mark all columns as stretchable.

Related XML Attributes:

Parameters
stretchAllColumns boolean: true to mark all columns stretchable

Protected methods

checkLayoutParams

Added in API level 1
protected boolean checkLayoutParams (ViewGroup.LayoutParams p)

Parameters
p ViewGroup.LayoutParams
Returns
boolean

generateDefaultLayoutParams

Added in API level 1
protected LinearLayout.LayoutParams generateDefaultLayoutParams ()

Returns a set of layout parameters with a width of ViewGroup.LayoutParams.MATCH_PARENT, and a height of ViewGroup.LayoutParams.WRAP_CONTENT.

Returns
LinearLayout.LayoutParams a set of default layout parameters or null

generateLayoutParams

Added in API level 1
protected LinearLayout.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p)

Returns a safe set of layout parameters based on the supplied layout params. When a ViewGroup is passed a View whose layout params do not pass the test of checkLayoutParams(android.view.ViewGroup.LayoutParams), this method is invoked. This method should return a new set of layout params suitable for this ViewGroup, possibly by copying the appropriate attributes from the specified set of layout params.

Parameters
p ViewGroup.LayoutParams: The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.
Returns
LinearLayout.LayoutParams an instance of ViewGroup.LayoutParams or one of its descendants

onLayout

Added in API level 1
protected void onLayout (boolean changed, 
                int l, 
                int t, 
                int r, 
                int b)

Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.

Parameters
changed boolean: This is a new size or position for this view
l int: Left position, relative to parent
t int: Top position, relative to parent
r int: Right position, relative to parent
b int: Bottom position, relative to parent

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.