Android APIs
public abstract class

ViewGroup

extends View
implements ViewManager ViewParent
java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
Known Direct Subclasses
Known Indirect Subclasses

Class Overview

A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.LayoutParams class which serves as the base class for layouts parameters.

Also see ViewGroup.LayoutParams for layout attributes.

Developer Guides

For more information about creating user interface layouts, read the XML Layouts developer guide.

Here is a complete implementation of a custom ViewGroup that implements a simple FrameLayout along with the ability to stack children in left and right gutters.

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RemoteViews;

/**
 * Example of writing a custom layout manager.  This is a fairly full-featured
 * layout manager that is relatively general, handling all layout cases.  You
 * can simplify it for more specific cases.
 */
@RemoteViews.RemoteView
public class CustomLayout extends ViewGroup {
    /** The amount of space used by children in the left gutter. */
    private int mLeftWidth;

    /** The amount of space used by children in the right gutter. */
    private int mRightWidth;

    /** These are used for computing child frames based on their gravity. */
    private final Rect mTmpContainerRect = new Rect();
    private final Rect mTmpChildRect = new Rect();

    public CustomLayout(Context context) {
        super(context);
    }

    public CustomLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * Any layout manager that doesn't scroll will want this.
     */
    @Override
    public boolean shouldDelayChildPressedState() {
        return false;
    }

    /**
     * Ask all children to measure themselves and compute the measurement of this
     * layout based on the children.
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();

        // These keep track of the space we are using on the left and right for
        // views positioned there; we need member variables so we can also use
        // these for layout later.
        mLeftWidth = 0;
        mRightWidth = 0;

        // Measurement will ultimately be computing these values.
        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        // Iterate through all children, measuring them and computing our dimensions
        // from their size.
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                // Measure the child.
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);

                // Update our size information based on the layout params.  Children
                // that asked to be positioned on the left or right go in those gutters.
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                if (lp.position == LayoutParams.POSITION_LEFT) {
                    mLeftWidth += Math.max(maxWidth,
                            child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                } else if (lp.position == LayoutParams.POSITION_RIGHT) {
                    mRightWidth += Math.max(maxWidth,
                            child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                } else {
                    maxWidth = Math.max(maxWidth,
                            child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                }
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
            }
        }

        // Total width is the maximum width of all inner children plus the gutters.
        maxWidth += mLeftWidth + mRightWidth;

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Report our final dimensions.
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));
    }

    /**
     * Position all children within this layout.
     */
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        final int count = getChildCount();

        // These are the far left and right edges in which we are performing layout.
        int leftPos = getPaddingLeft();
        int rightPos = right - left - getPaddingRight();

        // This is the middle region inside of the gutter.
        final int middleLeft = leftPos + mLeftWidth;
        final int middleRight = rightPos - mRightWidth;

        // These are the top and bottom edges in which we are performing layout.
        final int parentTop = getPaddingTop();
        final int parentBottom = bottom - top - getPaddingBottom();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                // Compute the frame in which we are placing this child.
                if (lp.position == LayoutParams.POSITION_LEFT) {
                    mTmpContainerRect.left = leftPos + lp.leftMargin;
                    mTmpContainerRect.right = leftPos + width + lp.rightMargin;
                    leftPos = mTmpContainerRect.right;
                } else if (lp.position == LayoutParams.POSITION_RIGHT) {
                    mTmpContainerRect.right = rightPos - lp.rightMargin;
                    mTmpContainerRect.left = rightPos - width - lp.leftMargin;
                    rightPos = mTmpContainerRect.left;
                } else {
                    mTmpContainerRect.left = middleLeft + lp.leftMargin;
                    mTmpContainerRect.right = middleRight - lp.rightMargin;
                }
                mTmpContainerRect.top = parentTop + lp.topMargin;
                mTmpContainerRect.bottom = parentBottom - lp.bottomMargin;

                // Use the child's gravity and size to determine its final
                // frame within its container.
                Gravity.apply(lp.gravity, width, height, mTmpContainerRect, mTmpChildRect);

                // Place the child.
                child.layout(mTmpChildRect.left, mTmpChildRect.top,
                        mTmpChildRect.right, mTmpChildRect.bottom);
            }
        }
    }

    // ----------------------------------------------------------------------
    // The rest of the implementation is for custom per-child layout parameters.
    // If you do not need these (for example you are writing a layout manager
    // that does fixed positioning of its children), you can drop all of this.

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new CustomLayout.LayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }

    @Override
    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
        return new LayoutParams(p);
    }

    @Override
    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
        return p instanceof LayoutParams;
    }

    /**
     * Custom per-child layout information.
     */
    public static class LayoutParams extends MarginLayoutParams {
        /**
         * The gravity to apply with the View to which these layout parameters
         * are associated.
         */
        public int gravity = Gravity.TOP | Gravity.START;

        public static int POSITION_MIDDLE = 0;
        public static int POSITION_LEFT = 1;
        public static int POSITION_RIGHT = 2;

        public int position = POSITION_MIDDLE;

        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);

            // Pull the layout param values from the layout XML during
            // inflation.  This is not needed if you don't care about
            // changing the layout behavior in XML.
            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.CustomLayoutLP);
            gravity = a.getInt(R.styleable.CustomLayoutLP_android_layout_gravity, gravity);
            position = a.getInt(R.styleable.CustomLayoutLP_layout_position, position);
            a.recycle();
        }

        public LayoutParams(int width, int height) {
            super(width, height);
        }

        public LayoutParams(ViewGroup.LayoutParams source) {
            super(source);
        }
    }
}

If you are implementing XML layout attributes as shown in the example, this is the corresponding definition for them that would go in res/values/attrs.xml:

<declare-styleable name="CustomLayoutLP">
    <attr name="android:layout_gravity" />
    <attr name="layout_position">
        <enum name="middle" value="0" />
        <enum name="left" value="1" />
        <enum name="right" value="2" />
    </attr>
</declare-styleable>

Finally the layout manager can be used in an XML layout like so:

<com.example.android.apis.view.CustomLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.android.apis"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <!-- put first view to left. -->
    <TextView
            android:background="@drawable/filled_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_position="left"
            android:layout_gravity="fill_vertical|center_horizontal"
            android:text="l1"/>

    <!-- stack second view to left. -->
    <TextView
            android:background="@drawable/filled_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_position="left"
            android:layout_gravity="fill_vertical|center_horizontal"
            android:text="l2"/>

    <!-- also put a view on the right. -->
    <TextView
            android:background="@drawable/filled_box"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_position="right"
            android:layout_gravity="fill_vertical|center_horizontal"
            android:text="r1"/>

    <!-- by default views go in the middle; use fill vertical gravity -->
    <TextView
            android:background="@drawable/green"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="fill_vertical|center_horizontal"
            android:text="fill-vert"/>

    <!-- by default views go in the middle; use fill horizontal gravity -->
    <TextView
            android:background="@drawable/green"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical|fill_horizontal"
            android:text="fill-horiz"/>

    <!-- by default views go in the middle; use top-left gravity -->
    <TextView
            android:background="@drawable/blue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="top|left"
            android:text="top-left"/>

    <!-- by default views go in the middle; use center gravity -->
    <TextView
            android:background="@drawable/blue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="center"/>

    <!-- by default views go in the middle; use bottom-right -->
    <TextView
            android:background="@drawable/blue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|right"
            android:text="bottom-right"/>

</com.example.android.apis.view.CustomLayout>

Summary

Nested Classes
class ViewGroup.LayoutParams LayoutParams are used by views to tell their parents how they want to be laid out. 
class ViewGroup.MarginLayoutParams Per-child layout information for layouts that support margins. 
interface ViewGroup.OnHierarchyChangeListener Interface definition for a callback to be invoked when the hierarchy within this view changed. 
XML Attributes
Attribute Name Related Method Description
android:addStatesFromChildren Sets whether this ViewGroup's drawable states also include its children's drawable states. 
android:alwaysDrawnWithCache Defines whether the ViewGroup should always draw its children using their drawing cache or not. 
android:animateLayoutChanges setLayoutTransition(LayoutTransition) Defines whether changes in layout (caused by adding and removing items) should cause a LayoutTransition to run. 
android:animationCache Defines whether layout animations should create a drawing cache for their children. 
android:clipChildren setClipChildren(boolean) Defines whether a child is limited to draw inside of its bounds or not. 
android:clipToPadding setClipToPadding(boolean) Defines whether the ViewGroup will clip its drawing surface so as to exclude the padding area. 
android:descendantFocusability Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus. 
android:layoutAnimation Defines the layout animation to use the first time the ViewGroup is laid out. 
android:layoutMode setLayoutMode(int) Defines the layout mode of this ViewGroup. 
android:persistentDrawingCache Defines the persistence of the drawing cache. 
android:splitMotionEvents setMotionEventSplittingEnabled(boolean) Sets whether this ViewGroup should split MotionEvents to separate child views during touch event dispatch. 
[Expand]
Inherited XML Attributes
From class android.view.View
Constants
int CLIP_TO_PADDING_MASK We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL are set at the same time.
int FOCUS_AFTER_DESCENDANTS This view will get focus only if none of its descendants want it.
int FOCUS_BEFORE_DESCENDANTS This view will get focus before any of its descendants.
int FOCUS_BLOCK_DESCENDANTS This view will block any of its descendants from getting focus, even if they are focusable.
int LAYOUT_MODE_CLIP_BOUNDS This constant is a layoutMode.
int LAYOUT_MODE_OPTICAL_BOUNDS This constant is a layoutMode.
int PERSISTENT_ALL_CACHES Used to indicate that all drawing caches should be kept in memory.
int PERSISTENT_ANIMATION_CACHE Used to indicate that the animation drawing cache should be kept in memory.
int PERSISTENT_NO_CACHE Used to indicate that no drawing cache should be kept in memory.
int PERSISTENT_SCROLLING_CACHE Used to indicate that the scrolling drawing cache should be kept in memory.
[Expand]
Inherited Constants
From class android.view.View
[Expand]
Inherited Fields
From class android.view.View
Public Constructors
ViewGroup(Context context)
ViewGroup(Context context, AttributeSet attrs)
ViewGroup(Context context, AttributeSet attrs, int defStyleAttr)
ViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
Public Methods
void addChildrenForAccessibility(ArrayList<View> childrenForAccessibility)
Adds the children of a given View for accessibility.
void addFocusables(ArrayList<View> views, int direction, int focusableMode)
Adds any focusable views that are descendants of this view (possibly including this view if it is focusable itself) to views.
boolean addStatesFromChildren()
Returns whether this ViewGroup's drawable states also include its children's drawable states.
void addTouchables(ArrayList<View> views)
Add any touchable views that are descendants of this view (possibly including this view if it is touchable itself) to views.
void addView(View child, int index, ViewGroup.LayoutParams params)
Adds a child view with the specified layout parameters.
void addView(View child, ViewGroup.LayoutParams params)
Adds a child view with the specified layout parameters.
void addView(View child, int index)
Adds a child view.
void addView(View child)

Adds a child view.

void addView(View child, int width, int height)
Adds a child view with this ViewGroup's default layout parameters and the specified width and height.
void bringChildToFront(View child)
Change the z order of the child so it's on top of all other children.
void childDrawableStateChanged(View child)
If addStatesFromChildren() is true, refreshes this group's drawable state (to include the states from its children).
void childHasTransientStateChanged(View child, boolean childHasTransientState)
Called when a child view has changed whether or not it is tracking transient state.
void clearChildFocus(View child)
Called when a child of this parent is giving up focus
void clearDisappearingChildren()
Removes any pending animations for views that have been removed.
void clearFocus()
Called when this view wants to give up focus.
WindowInsets dispatchApplyWindowInsets(WindowInsets insets)
Request to apply the given window insets to this view or another view in its subtree.
void dispatchConfigurationChanged(Configuration newConfig)
Dispatch a notification about a resource configuration change down the view hierarchy.
void dispatchDisplayHint(int hint)
Dispatch a hint about whether this view is displayed.
boolean dispatchDragEvent(DragEvent event)
Detects if this View is enabled and has a drag event listener.
boolean dispatchKeyEvent(KeyEvent event)
Dispatch a key event to the next view on the focus path.
boolean dispatchKeyEventPreIme(KeyEvent event)
Dispatch a key event before it is processed by any input method associated with the view hierarchy.
boolean dispatchKeyShortcutEvent(KeyEvent event)
Dispatches a key shortcut event.
void dispatchSetActivated(boolean activated)
Dispatch setActivated to all of this View's children.
void dispatchSetSelected(boolean selected)
Dispatch setSelected to all of this View's children.
void dispatchSystemUiVisibilityChanged(int visible)
boolean dispatchTouchEvent(MotionEvent ev)
Pass the touch screen motion event down to the target view, or this view if it is the target.
boolean dispatchTrackballEvent(MotionEvent event)
Pass a trackball motion event down to the focused view.
boolean dispatchUnhandledMove(View focused, int direction)
This method is the last chance for the focused view and its ancestors to respond to an arrow key.
void dispatchWindowFocusChanged(boolean hasFocus)
Called when the window containing this view gains or loses window focus.
void dispatchWindowSystemUiVisiblityChanged(int visible)
Dispatch callbacks to onWindowSystemUiVisibilityChanged(int) down the view hierarchy.
void dispatchWindowVisibilityChanged(int visibility)
Dispatch a window visibility change down the view hierarchy.
void endViewTransition(View view)
This method should always be called following an earlier call to startViewTransition(View).
View findFocus()
Find the view in the hierarchy rooted at this view that currently has focus.
void findViewsWithText(ArrayList<View> outViews, CharSequence text, int flags)
Finds the Views that contain given text.
View focusSearch(View focused, int direction)
Find the nearest view in the specified direction that wants to take focus.
void focusableViewAvailable(View v)
Tells the parent that a new focusable view has become available.
boolean gatherTransparentRegion(Region region)
This is used by the RootView to perform an optimization when the view hierarchy contains one or several SurfaceView.
ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
Returns a new set of layout parameters based on the supplied attributes set.
View getChildAt(int index)
Returns the view at the specified position in the group.
int getChildCount()
Returns the number of children in the group.
static int getChildMeasureSpec(int spec, int padding, int childDimension)
Does the hard part of measureChildren: figuring out the MeasureSpec to pass to a particular child.
boolean getChildVisibleRect(View child, Rect r, Point offset)
Compute the visible part of a rectangular region defined in terms of a child view's coordinates.
boolean getClipChildren()
Returns whether this group's children are clipped to their bounds before drawing.
int getDescendantFocusability()
Gets the descendant focusability of this view group.
View getFocusedChild()
Returns the focused child of this view, if any.
LayoutAnimationController getLayoutAnimation()
Returns the layout animation controller used to animate the group's children.
Animation.AnimationListener getLayoutAnimationListener()
Returns the animation listener to which layout animation events are sent.
int getLayoutMode()
Returns the basis of alignment during layout operations on this ViewGroup: either LAYOUT_MODE_CLIP_BOUNDS or LAYOUT_MODE_OPTICAL_BOUNDS.
LayoutTransition getLayoutTransition()
Gets the LayoutTransition object for this ViewGroup.
int getNestedScrollAxes()
Return the current axes of nested scrolling for this ViewGroup.
ViewGroupOverlay getOverlay()
Returns the ViewGroupOverlay for this view group, creating it if it does not yet exist.
int getPersistentDrawingCache()
Returns an integer indicating what types of drawing caches are kept in memory.
boolean hasFocus()
Returns true if this view has or contains focus
boolean hasFocusable()
Returns true if this view is focusable or if it contains a reachable View for which hasFocusable() returns true.
boolean hasTransientState()
Indicates whether the view is currently tracking transient state that the app should not need to concern itself with saving and restoring, but that the framework should take special note to preserve when possible.
int indexOfChild(View child)
Returns the position in the group of the specified child view.
final void invalidateChild(View child, Rect dirty)
Don't call or override this method.
ViewParent invalidateChildInParent(int[] location, Rect dirty)
Don't call or override this method.
boolean isAlwaysDrawnWithCacheEnabled()
Indicates whether this ViewGroup will always try to draw its children using their drawing cache.
boolean isAnimationCacheEnabled()
Indicates whether the children's drawing cache is used during a layout animation.
boolean isMotionEventSplittingEnabled()
Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
boolean isTransitionGroup()
Returns true if this ViewGroup should be considered as a single entity for removal when executing an Activity transition.
void jumpDrawablesToCurrentState()
Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.
final void layout(int l, int t, int r, int b)
Assign a size and position to a view and all of its descendants

This is the second phase of the layout mechanism.

void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType)
Notifies a view parent that the accessibility state of one of its descendants has changed and that the structure of the subtree is different.
final void offsetDescendantRectToMyCoords(View descendant, Rect rect)
Offset a rectangle that is in a descendant's coordinate space into our coordinate space.
final void offsetRectIntoDescendantCoords(View descendant, Rect rect)
Offset a rectangle that is in our coordinate space into an ancestor's coordinate space.
boolean onInterceptHoverEvent(MotionEvent event)
Implement this method to intercept hover events before they are handled by child views.
boolean onInterceptTouchEvent(MotionEvent ev)
Implement this method to intercept all touch screen motion events.
boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed)
Request a fling from a nested scroll.
void onNestedPreScroll(View target, int dx, int dy, int[] consumed)
React to a nested scroll in progress before the target view consumes a portion of the scroll.
void onNestedScroll(View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed)
React to a nested scroll in progress.
void onNestedScrollAccepted(View child, View target, int axes)
React to the successful claiming of a nested scroll operation.
boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event)
Called when a child has requested sending an AccessibilityEvent and gives an opportunity to its parent to augment the event.
boolean onStartNestedScroll(View child, View target, int nestedScrollAxes)
React to a descendant view initiating a nestable scroll operation, claiming the nested scroll operation if appropriate.
void onStopNestedScroll(View child)
React to a nested scroll operation ending.
void recomputeViewAttributes(View child)
Tell view hierarchy that the global view attributes need to be re-evaluated.
void removeAllViews()
Call this method to remove all child views from the ViewGroup.
void removeAllViewsInLayout()
Called by a ViewGroup subclass to remove child views from itself, when it must first know its size on screen before it can calculate how many child views it will render.
void removeView(View view)

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

void removeViewAt(int index)
Removes the view at the specified position in the group.
void removeViewInLayout(View view)
Removes a view during layout.
void removeViews(int start, int count)
Removes the specified range of views from the group.
void removeViewsInLayout(int start, int count)
Removes a range of views during layout.
void requestChildFocus(View child, View focused)
Called when a child of this parent wants focus
boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate)
Called when a child of this group wants a particular rectangle to be positioned onto the screen.
void requestDisallowInterceptTouchEvent(boolean disallowIntercept)
Called when a child does not want this parent and its ancestors to intercept touch events with onInterceptTouchEvent(MotionEvent).
boolean requestFocus(int direction, Rect previouslyFocusedRect)
Call this to try to give focus to a specific view or to one of its descendants and give it hints about the direction and a specific rectangle that the focus is coming from. Looks for a view to give focus to respecting the setting specified by getDescendantFocusability().
boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event)
Called by a child to request from its parent to send an AccessibilityEvent.
void requestTransparentRegion(View child)
Called when a child wants the view hierarchy to gather and report transparent regions to the window compositor.
void scheduleLayoutAnimation()
Schedules the layout animation to be played after the next layout pass of this view group.
void setAddStatesFromChildren(boolean addsStates)
Sets whether this ViewGroup's drawable states also include its children's drawable states.
void setAlwaysDrawnWithCacheEnabled(boolean always)
Indicates whether this ViewGroup will always try to draw its children using their drawing cache.
void setAnimationCacheEnabled(boolean enabled)
Enables or disables the children's drawing cache during a layout animation.
void setClipChildren(boolean clipChildren)
By default, children are clipped to their bounds before drawing.
void setClipToPadding(boolean clipToPadding)
By default, children are clipped to the padding of the ViewGroup.
void setDescendantFocusability(int focusability)
Set the descendant focusability of this view group.
void setLayoutAnimation(LayoutAnimationController controller)
Sets the layout animation controller used to animate the group's children after the first layout.
void setLayoutAnimationListener(Animation.AnimationListener animationListener)
Specifies the animation listener to which layout animation events must be sent.
void setLayoutMode(int layoutMode)
Sets the basis of alignment during the layout of this ViewGroup.
void setLayoutTransition(LayoutTransition transition)
Sets the LayoutTransition object for this ViewGroup.
void setMotionEventSplittingEnabled(boolean split)
Enable or disable the splitting of MotionEvents to multiple children during touch event dispatch.
void setOnHierarchyChangeListener(ViewGroup.OnHierarchyChangeListener listener)
Register a callback to be invoked when a child is added to or removed from this view.
void setPersistentDrawingCache(int drawingCacheToKeep)
Indicates what types of drawing caches should be kept in memory after they have been created.
void setTransitionGroup(boolean isTransitionGroup)
Changes whether or not this ViewGroup should be treated as a single entity during Activity Transitions.
boolean shouldDelayChildPressedState()
Return true if the pressed state should be delayed for children or descendants of this ViewGroup.
boolean showContextMenuForChild(View originalView)
Bring up a context menu for the specified view or its ancestors.
ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback)
Start an action mode for the specified view.
void startLayoutAnimation()
Runs the layout animation.
void startViewTransition(View view)
This method tells the ViewGroup that the given View object, which should have this ViewGroup as its parent, should be kept around (re-displayed when the ViewGroup draws its children) even if it is removed from its parent.
void updateViewLayout(View view, ViewGroup.LayoutParams params)
Protected Methods
boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout)
Adds a view during layout.
boolean addViewInLayout(View child, int index, ViewGroup.LayoutParams params)
Adds a view during layout.
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.
void attachViewToParent(View child, int index, ViewGroup.LayoutParams params)
Attaches a view to this view group.
boolean canAnimate()
Indicates whether the view group has the ability to animate its children after the first layout.
boolean checkLayoutParams(ViewGroup.LayoutParams p)
void cleanupLayoutState(View child)
Prevents the specified child to be laid out during the next layout pass.
void debug(int depth)
Prints information about this view in the log output, with the tag VIEW_LOG_TAG.
void detachAllViewsFromParent()
Detaches all views from the parent.
void detachViewFromParent(View child)
Detaches a view from its parent.
void detachViewFromParent(int index)
Detaches a view from its parent.
void detachViewsFromParent(int start, int count)
Detaches a range of views from their parents.
void dispatchDraw(Canvas canvas)
Called by draw to draw the child views.
void dispatchFreezeSelfOnly(SparseArray<Parcelable> container)
Perform dispatching of a saveHierarchyState(android.util.SparseArray) freeze()} to only this view, not to its children.
boolean dispatchGenericFocusedEvent(MotionEvent event)
Dispatch a generic motion event to the currently focused view.
boolean dispatchGenericPointerEvent(MotionEvent event)
Dispatch a generic motion event to the view under the first pointer.
boolean dispatchHoverEvent(MotionEvent event)
Dispatch a hover event.
void dispatchRestoreInstanceState(SparseArray<Parcelable> container)
Called by restoreHierarchyState(android.util.SparseArray) to retrieve the state for this view and its children.
void dispatchSaveInstanceState(SparseArray<Parcelable> container)
Called by saveHierarchyState(android.util.SparseArray) to store the state for this view and its children.
void dispatchSetPressed(boolean pressed)
Dispatch setPressed to all of this View's children.
void dispatchThawSelfOnly(SparseArray<Parcelable> container)
Perform dispatching of a restoreHierarchyState(android.util.SparseArray) to only this view, not to its children.
void dispatchVisibilityChanged(View changedView, int visibility)
Dispatch a view visibility change down the view hierarchy.
boolean drawChild(Canvas canvas, View child, long drawingTime)
Draw one child of this View Group.
void drawableStateChanged()
This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.
ViewGroup.LayoutParams generateDefaultLayoutParams()
Returns a set of default layout parameters.
ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p)
Returns a safe set of layout parameters based on the supplied layout params.
int getChildDrawingOrder(int childCount, int i)
Returns the index of the child to draw for this iteration.
boolean getChildStaticTransformation(View child, Transformation t)
Sets t to be the static transformation of the child, if set, returning a boolean to indicate whether a static transform was set.
boolean isChildrenDrawingOrderEnabled()
Indicates whether the ViewGroup is drawing its children in the order defined by getChildDrawingOrder(int, int).
boolean isChildrenDrawnWithCacheEnabled()
Indicates whether the ViewGroup is currently drawing its children using their drawing cache.
void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)
Ask one of the children of this view to measure itself, taking into account both the MeasureSpec requirements for this view and its padding.
void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)
Ask one of the children of this view to measure itself, taking into account both the MeasureSpec requirements for this view and its padding and margins.
void measureChildren(int widthMeasureSpec, int heightMeasureSpec)
Ask all of the children of this view to measure themselves, taking into account both the MeasureSpec requirements for this view and its padding.
void onAnimationEnd()
Invoked by a parent ViewGroup to notify the end of the animation currently associated with this view.
void onAnimationStart()
Invoked by a parent ViewGroup to notify the start of the animation currently associated with this view.
void onAttachedToWindow()
This is called when the view is attached to a window.
int[] onCreateDrawableState(int extraSpace)
Generate the new Drawable state for this view.
void onDetachedFromWindow()
This is called when the view is detached from a window.
abstract 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.
boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect)
Look for a descendant to call requestFocus() on.
void removeDetachedView(View child, boolean animate)
Finishes the removal of a detached view.
void setChildrenDrawingCacheEnabled(boolean enabled)
Enables or disables the drawing cache for each child of this view group.
void setChildrenDrawingOrderEnabled(boolean enabled)
Tells the ViewGroup whether to draw its children in the order defined by the method getChildDrawingOrder(int, int).
void setChildrenDrawnWithCacheEnabled(boolean enabled)
Tells the ViewGroup to draw its children using their drawing cache.
void setStaticTransformationsEnabled(boolean enabled)
When this property is set to true, this ViewGroup supports static transformations on children; this causes getChildStaticTransformation(View, android.view.animation.Transformation) to be invoked when a child is drawn.
[Expand]
Inherited Methods
From class android.view.View
From class java.lang.Object
From interface android.graphics.drawable.Drawable.Callback
From interface android.view.KeyEvent.Callback
From interface android.view.ViewManager
From interface android.view.ViewParent
From interface android.view.accessibility.AccessibilityEventSource

XML Attributes

android:addStatesFromChildren

Sets whether this ViewGroup's drawable states also include its children's drawable states. This is used, for example, to make a group appear to be focused when its child EditText or button is focused.

Must be a boolean value, either "true" or "false".

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

Related Methods

android:alwaysDrawnWithCache

Defines whether the ViewGroup should always draw its children using their drawing cache or not. The default value is true.

Must be a boolean value, either "true" or "false".

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

Related Methods

android:animateLayoutChanges

Defines whether changes in layout (caused by adding and removing items) should cause a LayoutTransition to run. When this flag is set to true, a default LayoutTransition object will be set on the ViewGroup container and default animations will run when these layout changes occur.

Must be a boolean value, either "true" or "false".

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

android:animationCache

Defines whether layout animations should create a drawing cache for their children. Enabling the animation cache consumes more memory and requires a longer initialization but provides better performance. The animation cache is enabled by default.

Must be a boolean value, either "true" or "false".

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

Related Methods

android:clipChildren

Defines whether a child is limited to draw inside of its bounds or not. This is useful with animations that scale the size of the children to more than 100% for instance. In such a case, this property should be set to false to allow the children to draw outside of their bounds. The default value of this property is true.

Must be a boolean value, either "true" or "false".

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

Related Methods

android:clipToPadding

Defines whether the ViewGroup will clip its drawing surface so as to exclude the padding area. This property is set to true by default.

Must be a boolean value, either "true" or "false".

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

Related Methods

android:descendantFocusability

Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.

Must be one of the following constant values.

ConstantValueDescription
beforeDescendants0 The ViewGroup will get focus before any of its descendants.
afterDescendants1 The ViewGroup will get focus only if none of its descendants want it.
blocksDescendants2 The ViewGroup will block its descendants from receiving focus.

This corresponds to the global attribute resource symbol descendantFocusability.

Related Methods

android:layoutAnimation

Defines the layout animation to use the first time the ViewGroup is laid out. Layout animations can also be started manually after the first layout.

Must be a reference to another resource, in the form "@[+][package:]type:name" or to a theme attribute in the form "?[package:][type:]name".

This corresponds to the global attribute resource symbol layoutAnimation.

Related Methods

android:layoutMode

Defines the layout mode of this ViewGroup.

Must be one of the following constant values.

ConstantValueDescription
clipBounds0 Use the children's clip bounds when laying out this container.
opticalBounds1 Use the children's optical bounds when laying out this container.

This corresponds to the global attribute resource symbol layoutMode.

Related Methods

android:persistentDrawingCache

Defines the persistence of the drawing cache. The drawing cache might be enabled by a ViewGroup for all its children in specific situations (for instance during a scrolling.) This property lets you persist the cache in memory after its initial usage. Persisting the cache consumes more memory but may prevent frequent garbage collection is the cache is created over and over again. By default the persistence is set to scrolling.

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

ConstantValueDescription
none0x0 The drawing cache is not persisted after use.
animation0x1 The drawing cache is persisted after a layout animation.
scrolling0x2 The drawing cache is persisted after a scroll.
all0x3 The drawing cache is always persisted.

This corresponds to the global attribute resource symbol persistentDrawingCache.

Related Methods

android:splitMotionEvents

Sets whether this ViewGroup should split MotionEvents to separate child views during touch event dispatch. If false (default), touch events will be dispatched to the child view where the first pointer went down until the last pointer goes up. If true, touch events may be dispatched to multiple children. MotionEvents for each pointer will be dispatched to the child view where the initial ACTION_DOWN event happened. See setMotionEventSplittingEnabled(boolean) for more information.

Must be a boolean value, either "true" or "false".

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

Constants

protected static final int CLIP_TO_PADDING_MASK

Added in API level 1

We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL are set at the same time.

Constant Value: 34 (0x00000022)

public static final int FOCUS_AFTER_DESCENDANTS

Added in API level 1

This view will get focus only if none of its descendants want it.

Constant Value: 262144 (0x00040000)

public static final int FOCUS_BEFORE_DESCENDANTS

Added in API level 1

This view will get focus before any of its descendants.

Constant Value: 131072 (0x00020000)

public static final int FOCUS_BLOCK_DESCENDANTS

Added in API level 1

This view will block any of its descendants from getting focus, even if they are focusable.

Constant Value: 393216 (0x00060000)

public static final int LAYOUT_MODE_CLIP_BOUNDS

Added in API level 18

This constant is a layoutMode. Clip bounds are the raw values of left, top, right and bottom.

Constant Value: 0 (0x00000000)

public static final int LAYOUT_MODE_OPTICAL_BOUNDS

Added in API level 18

This constant is a layoutMode. Optical bounds describe where a widget appears to be. They sit inside the clip bounds which need to cover a larger area to allow other effects, such as shadows and glows, to be drawn.

Constant Value: 1 (0x00000001)

public static final int PERSISTENT_ALL_CACHES

Added in API level 1

Used to indicate that all drawing caches should be kept in memory.

Constant Value: 3 (0x00000003)

public static final int PERSISTENT_ANIMATION_CACHE

Added in API level 1

Used to indicate that the animation drawing cache should be kept in memory.

Constant Value: 1 (0x00000001)

public static final int PERSISTENT_NO_CACHE

Added in API level 1

Used to indicate that no drawing cache should be kept in memory.

Constant Value: 0 (0x00000000)

public static final int PERSISTENT_SCROLLING_CACHE

Added in API level 1

Used to indicate that the scrolling drawing cache should be kept in memory.

Constant Value: 2 (0x00000002)

Public Constructors

public ViewGroup (Context context)

Added in API level 1

public ViewGroup (Context context, AttributeSet attrs)

Added in API level 1

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

Added in API level 1

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

Public Methods

public void addChildrenForAccessibility (ArrayList<View> childrenForAccessibility)

Added in API level 16

Adds the children of a given View for accessibility. Since some Views are not important for accessibility the children for accessibility are not necessarily direct children of the view, rather they are the first level of descendants important for accessibility.

Parameters
childrenForAccessibility The list of children for accessibility.

public void addFocusables (ArrayList<View> views, int direction, int focusableMode)

Added in API level 4

Adds any focusable views that are descendants of this view (possibly including this view if it is focusable itself) to views. This method adds all focusable views regardless if we are in touch mode or only views focusable in touch mode if we are in touch mode or only views that can take accessibility focus if accessibility is enabeld depending on the focusable mode paramater.

Parameters
views Focusable views found so far or null if all we are interested is the number of focusables.
direction The direction of the focus.
focusableMode The type of focusables to be added.

public boolean addStatesFromChildren ()

Added in API level 1

Returns whether this ViewGroup's drawable states also include its children's drawable states. This is used, for example, to make a group appear to be focused when its child EditText or button is focused.

public void addTouchables (ArrayList<View> views)

Added in API level 1

Add any touchable views that are descendants of this view (possibly including this view if it is touchable itself) to views.

Parameters
views Touchable views found so far

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

Added in API level 1

Adds a child view with the specified layout parameters.

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

Parameters
child the child view to add
index the position at which to add the child
params the layout parameters to set on the child

public void addView (View child, ViewGroup.LayoutParams params)

Added in API level 1

Adds a child view with the specified layout parameters.

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

Parameters
child the child view to add
params the layout parameters to set on the child

public void addView (View child, int index)

Added in API level 1

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 draw(android.graphics.Canvas), onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child the child view to add
index the position at which to add the child

public void addView (View child)

Added in API level 1

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 draw(android.graphics.Canvas), onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child the child view to add

public void addView (View child, int width, int height)

Added in API level 1

Adds a child view with this ViewGroup's default layout parameters and the specified width and height.

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

Parameters
child the child view to add

public void bringChildToFront (View child)

Added in API level 1

Change the z order of the child so it's on top of all other children. This ordering change may affect layout, if this container uses an order-dependent layout scheme (e.g., LinearLayout). Prior to KITKAT this method should be followed by calls to requestLayout() and invalidate() on this parent to force the parent to redraw with the new child ordering.

Parameters
child The child to bring to the top of the z order

public void childDrawableStateChanged (View child)

Added in API level 1

If addStatesFromChildren() is true, refreshes this group's drawable state (to include the states from its children).

Parameters
child The child whose drawable state has changed.

public void childHasTransientStateChanged (View child, boolean childHasTransientState)

Added in API level 19

Called when a child view has changed whether or not it is tracking transient state.

Parameters
child Child view whose state has changed
childHasTransientState true if this child has transient state

public void clearChildFocus (View child)

Added in API level 1

Called when a child of this parent is giving up focus

Parameters
child The view that is giving up focus

public void clearDisappearingChildren ()

Added in API level 1

Removes any pending animations for views that have been removed. Call this if you don't want animations for exiting views to stack up.

public void clearFocus ()

Added in API level 1

Called when this view wants to give up focus. If focus is cleared onFocusChanged(boolean, int, android.graphics.Rect) is called.

Note: When a View clears focus the framework is trying to give focus to the first focusable View from the top. Hence, if this View is the first from the top that can take focus, then all callbacks related to clearing focus will be invoked after wich the framework will give focus to this view.

public WindowInsets dispatchApplyWindowInsets (WindowInsets insets)

Request to apply the given window insets to this view or another view in its subtree.

This method should be called by clients wishing to apply insets corresponding to areas obscured by window decorations or overlays. This can include the status and navigation bars, action bars, input methods and more. New inset categories may be added in the future. The method returns the insets provided minus any that were applied by this view or its children.

Clients wishing to provide custom behavior should override the onApplyWindowInsets(WindowInsets) method or alternatively provide a View.OnApplyWindowInsetsListener via the setOnApplyWindowInsetsListener method.

This method replaces the older fitSystemWindows method.

Parameters
insets Insets to apply
Returns
  • The provided insets minus the insets that were consumed

public void dispatchConfigurationChanged (Configuration newConfig)

Added in API level 8

Dispatch a notification about a resource configuration change down the view hierarchy. ViewGroups should override to route to their children.

Parameters
newConfig The new resource configuration.

public void dispatchDisplayHint (int hint)

Added in API level 8

Dispatch a hint about whether this view is displayed. For instance, when a View moves out of the screen, it might receives a display hint indicating the view is not displayed. Applications should not rely on this hint as there is no guarantee that they will receive one.

Parameters
hint A hint about whether or not this view is displayed: VISIBLE or INVISIBLE.

public boolean dispatchDragEvent (DragEvent event)

Added in API level 11

Detects if this View is enabled and has a drag event listener. If both are true, then it calls the drag event listener with the DragEvent it received. If the drag event listener returns true, then dispatchDragEvent() returns true.

For all other cases, the method calls the onDragEvent() drag event handler method and returns its result.

This ensures that a drag event is always consumed, even if the View does not have a drag event listener. However, if the View has a listener and the listener returns true, then onDragEvent() is not called.

public boolean dispatchKeyEvent (KeyEvent event)

Added in API level 1

Dispatch a key event to the next view on the focus path. This path runs from the top of the view tree down to the currently focused view. If this view has focus, it will dispatch to itself. Otherwise it will dispatch the next node down the focus path. This method also fires any key listeners.

Parameters
event The key event to be dispatched.
Returns
  • True if the event was handled, false otherwise.

public boolean dispatchKeyEventPreIme (KeyEvent event)

Added in API level 3

Dispatch a key event before it is processed by any input method associated with the view hierarchy. This can be used to intercept key events in special situations before the IME consumes them; a typical example would be handling the BACK key to update the application's UI instead of allowing the IME to see it and close itself.

Parameters
event The key event to be dispatched.
Returns
  • True if the event was handled, false otherwise.

public boolean dispatchKeyShortcutEvent (KeyEvent event)

Added in API level 1

Dispatches a key shortcut event.

Parameters
event The key event to be dispatched.
Returns
  • True if the event was handled by the view, false otherwise.

public void dispatchSetActivated (boolean activated)

Added in API level 11

Dispatch setActivated to all of this View's children.

Parameters
activated The new activated state

public void dispatchSetSelected (boolean selected)

Added in API level 1

Dispatch setSelected to all of this View's children.

Parameters
selected The new selected state

public void dispatchSystemUiVisibilityChanged (int visible)

Added in API level 11

public boolean dispatchTouchEvent (MotionEvent ev)

Added in API level 1

Pass the touch screen motion event down to the target view, or this view if it is the target.

Parameters
ev The motion event to be dispatched.
Returns
  • True if the event was handled by the view, false otherwise.

public boolean dispatchTrackballEvent (MotionEvent event)

Added in API level 1

Pass a trackball motion event down to the focused view.

Parameters
event The motion event to be dispatched.
Returns
  • True if the event was handled by the view, false otherwise.

public boolean dispatchUnhandledMove (View focused, int direction)

Added in API level 1

This method is the last chance for the focused view and its ancestors to respond to an arrow key. This is called when the focused view did not consume the key internally, nor could the view system find a new view in the requested direction to give focus to.

Parameters
focused The currently focused view.
direction The direction focus wants to move. One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
Returns
  • True if the this view consumed this unhandled move.

public void dispatchWindowFocusChanged (boolean hasFocus)

Added in API level 1

Called when the window containing this view gains or loses window focus. ViewGroups should override to route to their children.

Parameters
hasFocus True if the window containing this view now has focus, false otherwise.

public void dispatchWindowSystemUiVisiblityChanged (int visible)

Added in API level 16

Dispatch callbacks to onWindowSystemUiVisibilityChanged(int) down the view hierarchy.

public void dispatchWindowVisibilityChanged (int visibility)

Added in API level 1

Dispatch a window visibility change down the view hierarchy. ViewGroups should override to route to their children.

Parameters
visibility The new visibility of the window.

public void endViewTransition (View view)

Added in API level 11

This method should always be called following an earlier call to startViewTransition(View). The given View is finally removed from its parent and will no longer be displayed. Note that this method does not perform the functionality of removing a view from its parent; it just discontinues the display of a View that has previously been removed.

Returns
  • view The View object that has been removed but is being kept around in the visible hierarchy by an earlier call to startViewTransition(View).

public View findFocus ()

Added in API level 1

Find the view in the hierarchy rooted at this view that currently has focus.

Returns
  • The view that currently has focus, or null if no focused view can be found.

public void findViewsWithText (ArrayList<View> outViews, CharSequence text, int flags)

Added in API level 14

Finds the Views that contain given text. The containment is case insensitive. The search is performed by either the text that the View renders or the content description that describes the view for accessibility purposes and the view does not render or both. Clients can specify how the search is to be performed via passing the FIND_VIEWS_WITH_TEXT and FIND_VIEWS_WITH_CONTENT_DESCRIPTION flags.

Parameters
outViews The output list of matching Views.
text The text to match against.

public View focusSearch (View focused, int direction)

Added in API level 1

Find the nearest view in the specified direction that wants to take focus.

Parameters
focused The view that currently has focus
direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT, or 0 for not applicable.

public void focusableViewAvailable (View v)

Added in API level 1

Tells the parent that a new focusable view has become available. This is to handle transitions from the case where there are no focusable views to the case where the first focusable view appears.

Parameters
v The view that has become newly focusable

public boolean gatherTransparentRegion (Region region)

Added in API level 1

This is used by the RootView to perform an optimization when the view hierarchy contains one or several SurfaceView. SurfaceView is always considered transparent, but its children are not, therefore all View objects remove themselves from the global transparent region (passed as a parameter to this function).

Parameters
region The transparent region for this ViewAncestor (window).
Returns
  • Returns true if the effective visibility of the view at this point is opaque, regardless of the transparent region; returns false if it is possible for underlying windows to be seen behind the view.

public ViewGroup.LayoutParams generateLayoutParams (AttributeSet attrs)

Added in API level 1

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

Parameters
attrs the attributes to build the layout parameters from
Returns

public View getChildAt (int index)

Added in API level 1

Returns the view at the specified position in the group.

Parameters
index the position at which to get the view from
Returns
  • the view at the specified position or null if the position does not exist within the group

public int getChildCount ()

Added in API level 1

Returns the number of children in the group.

Returns
  • a positive integer representing the number of children in the group

public static int getChildMeasureSpec (int spec, int padding, int childDimension)

Added in API level 1

Does the hard part of measureChildren: figuring out the MeasureSpec to pass to a particular child. This method figures out the right MeasureSpec for one dimension (height or width) of one child view. The goal is to combine information from our MeasureSpec with the LayoutParams of the child to get the best possible results. For example, if the this view knows its size (because its MeasureSpec has a mode of EXACTLY), and the child has indicated in its LayoutParams that it wants to be the same size as the parent, the parent should ask the child to layout given an exact size.

Parameters
spec The requirements for this view
padding The padding of this view for the current dimension and margins, if applicable
childDimension How big the child wants to be in the current dimension
Returns
  • a MeasureSpec integer for the child

public boolean getChildVisibleRect (View child, Rect r, Point offset)

Added in API level 1

Compute the visible part of a rectangular region defined in terms of a child view's coordinates.

Returns the clipped visible part of the rectangle r, defined in the child's local coordinate system. r is modified by this method to contain the result, expressed in the global (root) coordinate system.

The resulting rectangle is always axis aligned. If a rotation is applied to a node in the View hierarchy, the result is the axis-aligned bounding box of the visible rectangle.

Parameters
child A child View, whose rectangular visible region we want to compute
r The input rectangle, defined in the child coordinate system. Will be overwritten to contain the resulting visible rectangle, expressed in global (root) coordinates
offset The input coordinates of a point, defined in the child coordinate system. As with the r parameter, this will be overwritten to contain the global (root) coordinates of that point. A null value is valid (in case you are not interested in this result)
Returns
  • true if the resulting rectangle is not empty, false otherwise

public boolean getClipChildren ()

Added in API level 18

Returns whether this group's children are clipped to their bounds before drawing. The default value is true.

Returns
  • True if the group's children will be clipped to their bounds, false otherwise.

public int getDescendantFocusability ()

Added in API level 1

Gets the descendant focusability of this view group. The descendant focusability defines the relationship between this view group and its descendants when looking for a view to take focus in requestFocus(int, android.graphics.Rect).

public View getFocusedChild ()

Added in API level 1

Returns the focused child of this view, if any. The child may have focus or contain focus.

Returns
  • the focused child or null.

public LayoutAnimationController getLayoutAnimation ()

Added in API level 1

Returns the layout animation controller used to animate the group's children.

Returns
  • the current animation controller

public Animation.AnimationListener getLayoutAnimationListener ()

Added in API level 1

Returns the animation listener to which layout animation events are sent.

public int getLayoutMode ()

Added in API level 18

Returns the basis of alignment during layout operations on this ViewGroup: either LAYOUT_MODE_CLIP_BOUNDS or LAYOUT_MODE_OPTICAL_BOUNDS.

If no layoutMode was explicitly set, either programmatically or in an XML resource, the method returns the layoutMode of the view's parent ViewGroup if such a parent exists, otherwise the method returns a default value of LAYOUT_MODE_CLIP_BOUNDS.

Returns
  • the layout mode to use during layout operations

public LayoutTransition getLayoutTransition ()

Added in API level 11

Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is not null, changes in layout which occur because of children being added to or removed from the ViewGroup will be animated according to the animations defined in that LayoutTransition object. By default, the transition object is null (so layout changes are not animated).

Returns
  • LayoutTranstion The LayoutTransition object that will animated changes in layout. A value of null means no transition will run on layout changes.

public int getNestedScrollAxes ()

Return the current axes of nested scrolling for this ViewGroup.

A ViewGroup returning something other than SCROLL_AXIS_NONE is currently acting as a nested scrolling parent for one or more descendant views in the hierarchy.

Returns
  • Flags indicating the current axes of nested scrolling

public ViewGroupOverlay getOverlay ()

Added in API level 18

Returns the ViewGroupOverlay for this view group, creating it if it does not yet exist. In addition to ViewOverlay's support for drawables, ViewGroupOverlay allows views to be added to the overlay. These views, like overlay drawables, are visual-only; they do not receive input events and should not be used as anything other than a temporary representation of a view in a parent container, such as might be used by an animation effect.

Note: Overlays do not currently work correctly with SurfaceView or TextureView; contents in overlays for these types of views may not display correctly.

Returns
  • The ViewGroupOverlay object for this view.
See Also

public int getPersistentDrawingCache ()

Added in API level 1

Returns an integer indicating what types of drawing caches are kept in memory.

public boolean hasFocus ()

Added in API level 1

Returns true if this view has or contains focus

Returns
  • true if this view has or contains focus

public boolean hasFocusable ()

Added in API level 1

Returns true if this view is focusable or if it contains a reachable View for which hasFocusable() returns true. A "reachable hasFocusable()" is a View whose parents do not block descendants focus. Only VISIBLE views are considered focusable.

Returns
  • True if the view is focusable or if the view contains a focusable View, false otherwise.

public boolean hasTransientState ()

Added in API level 16

Indicates whether the view is currently tracking transient state that the app should not need to concern itself with saving and restoring, but that the framework should take special note to preserve when possible.

A view with transient state cannot be trivially rebound from an external data source, such as an adapter binding item views in a list. This may be because the view is performing an animation, tracking user selection of content, or similar.

Returns
  • true if the view has transient state

public int indexOfChild (View child)

Added in API level 1

Returns the position in the group of the specified child view.

Parameters
child the view for which to get the position
Returns
  • a positive integer representing the position of the view in the group, or -1 if the view does not exist in the group

public final void invalidateChild (View child, Rect dirty)

Added in API level 1

Don't call or override this method. It is used for the implementation of the view hierarchy.

Parameters
child The child which is dirty
dirty The area within the child that is invalid

public ViewParent invalidateChildInParent (int[] location, Rect dirty)

Added in API level 1

Don't call or override this method. It is used for the implementation of the view hierarchy. This implementation returns null if this ViewGroup does not have a parent, if this ViewGroup is already fully invalidated or if the dirty rectangle does not intersect with this ViewGroup's bounds.

Parameters
location An array of 2 ints containing the left and top coordinates of the child to invalidate
dirty The area within the child that is invalid
Returns
  • the parent of this ViewParent or null

public boolean isAlwaysDrawnWithCacheEnabled ()

Added in API level 1

Indicates whether this ViewGroup will always try to draw its children using their drawing cache. By default this property is enabled.

Returns
  • true if the animation cache is enabled, false otherwise

public boolean isAnimationCacheEnabled ()

Added in API level 1

Indicates whether the children's drawing cache is used during a layout animation. By default, the drawing cache is enabled but this will prevent nested layout animations from working. To nest animations, you must disable the cache.

Returns
  • true if the animation cache is enabled, false otherwise

public boolean isMotionEventSplittingEnabled ()

Added in API level 11

Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children.

Returns
  • true if MotionEvents dispatched to this ViewGroup can be split to multiple children.

public boolean isTransitionGroup ()

Returns true if this ViewGroup should be considered as a single entity for removal when executing an Activity transition. If this is false, child elements will move individually during the transition.

Returns
  • True if the ViewGroup should be acted on together during an Activity transition. The default value is false when the background is null and true when the background is not null or if getViewName() is not null.

public void jumpDrawablesToCurrentState ()

Added in API level 11

Call Drawable.jumpToCurrentState() on all Drawable objects associated with this view.

Also calls jumpToCurrentState() if there is a StateListAnimator attached to this view.

public final void layout (int l, int t, int r, int b)

Added in API level 1

Assign a size and position to a view and all of its descendants

This is the second phase of the layout mechanism. (The first is measuring). In this phase, each parent calls layout on all of its children to position them. This is typically done using the child measurements that were stored in the measure pass().

Derived classes should not override this method. Derived classes with children should override onLayout. In that method, they should call layout on each of their children.

Parameters
l Left position, relative to parent
t Top position, relative to parent
r Right position, relative to parent
b Bottom position, relative to parent

public void notifySubtreeAccessibilityStateChanged (View child, View source, int changeType)

Added in API level 19

Notifies a view parent that the accessibility state of one of its descendants has changed and that the structure of the subtree is different.

Parameters
child The direct child whose subtree has changed.
source The descendant view that changed.
changeType A bit mask of the types of changes that occurred. One or more of:

public final void offsetDescendantRectToMyCoords (View descendant, Rect rect)

Added in API level 1

Offset a rectangle that is in a descendant's coordinate space into our coordinate space.

Parameters
descendant A descendant of this view
rect A rectangle defined in descendant's coordinate space.

public final void offsetRectIntoDescendantCoords (View descendant, Rect rect)

Added in API level 1

Offset a rectangle that is in our coordinate space into an ancestor's coordinate space.

Parameters
descendant A descendant of this view
rect A rectangle defined in descendant's coordinate space.

public boolean onInterceptHoverEvent (MotionEvent event)

Added in API level 14

Implement this method to intercept hover events before they are handled by child views.

This method is called before dispatching a hover event to a child of the view group or to the view group's own onHoverEvent(MotionEvent) to allow the view group a chance to intercept the hover event. This method can also be used to watch all pointer motions that occur within the bounds of the view group even when the pointer is hovering over a child of the view group rather than over the view group itself.

The view group can prevent its children from receiving hover events by implementing this method and returning true to indicate that it would like to intercept hover events. The view group must continuously return true from onInterceptHoverEvent(MotionEvent) for as long as it wishes to continue intercepting hover events from its children.

Interception preserves the invariant that at most one view can be hovered at a time by transferring hover focus from the currently hovered child to the view group or vice-versa as needed.

If this method returns true and a child is already hovered, then the child view will first receive a hover exit event and then the view group itself will receive a hover enter event in onHoverEvent(MotionEvent). Likewise, if this method had previously returned true to intercept hover events and instead returns false while the pointer is hovering within the bounds of one of a child, then the view group will first receive a hover exit event in onHoverEvent(MotionEvent) and then the hovered child will receive a hover enter event.

The default implementation always returns false.

Parameters
event The motion event that describes the hover.
Returns
  • True if the view group would like to intercept the hover event and prevent its children from receiving it.

public boolean onInterceptTouchEvent (MotionEvent ev)

Added in API level 1

Implement this method to intercept all touch screen motion events. This allows you to watch events as they are dispatched to your children, and take ownership of the current gesture at any point.

Using this function takes some care, as it has a fairly complicated interaction with View.onTouchEvent(MotionEvent), and using it requires implementing that method as well as this one in the correct way. Events will be received in the following order:

  1. You will receive the down event here.
  2. The down event will be handled either by a child of this view group, or given to your own onTouchEvent() method to handle; this means you should implement onTouchEvent() to return true, so you will continue to see the rest of the gesture (instead of looking for a parent view to handle it). Also, by returning true from onTouchEvent(), you will not receive any following events in onInterceptTouchEvent() and all touch processing must happen in onTouchEvent() like normal.
  3. For as long as you return false from this function, each following event (up to and including the final up) will be delivered first here and then to the target's onTouchEvent().
  4. If you return true from here, you will not receive any following events: the target view will receive the same event but with the action ACTION_CANCEL, and all further events will be delivered to your onTouchEvent() method and no longer appear here.

Parameters
ev The motion event being dispatched down the hierarchy.
Returns
  • Return true to steal motion events from the children and have them dispatched to this ViewGroup through onTouchEvent(). The current target will receive an ACTION_CANCEL event, and no further messages will be delivered here.

public boolean onNestedFling (View target, float velocityX, float velocityY, boolean consumed)

Request a fling from a nested scroll.

This method signifies that a nested scrolling child has detected suitable conditions for a fling. Generally this means that a touch scroll has ended with a velocity in the direction of scrolling that meets or exceeds the minimum fling velocity along a scrollable axis.

If a nested scrolling child view would normally fling but it is at the edge of its own content, it can use this method to delegate the fling to its nested scrolling parent instead. The parent may optionally consume the fling or observe a child fling.

Parameters
target View that initiated the nested scroll
velocityX Horizontal velocity in pixels per second.
velocityY Vertical velocity in pixels per second
consumed true if the child consumed the fling, false otherwise
Returns
  • true if this parent consumed or otherwise reacted to the fling

public void onNestedPreScroll (View target, int dx, int dy, int[] consumed)

React to a nested scroll in progress before the target view consumes a portion of the scroll.

When working with nested scrolling often the parent view may want an opportunity to consume the scroll before the nested scrolling child does. An example of this is a drawer that contains a scrollable list. The user will want to be able to scroll the list fully into view before the list itself begins scrolling.

onNestedPreScroll is called when a nested scrolling child invokes dispatchNestedPreScroll(int, int, int[], int[]). The implementation should report how any pixels of the scroll reported by dx, dy were consumed in the consumed array. Index 0 corresponds to dx and index 1 corresponds to dy. This parameter will never be null. Initial values for consumed[0] and consumed[1] will always be 0.

Parameters
target View that initiated the nested scroll
dx Horizontal scroll distance in pixels
dy Vertical scroll distance in pixels
consumed Output. The horizontal and vertical scroll distance consumed by this parent

public void onNestedScroll (View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed)

React to a nested scroll in progress.

This method will be called when the ViewParent's current nested scrolling child view dispatches a nested scroll event. To receive calls to this method the ViewParent must have previously returned true for a call to onStartNestedScroll(View, View, int).

Both the consumed and unconsumed portions of the scroll distance are reported to the ViewParent. An implementation may choose to use the consumed portion to match or chase scroll position of multiple child elements, for example. The unconsumed portion may be used to allow continuous dragging of multiple scrolling or draggable elements, such as scrolling a list within a vertical drawer where the drawer begins dragging once the edge of inner scrolling content is reached.

Parameters
target The descendent view controlling the nested scroll
dxConsumed Horizontal scroll distance in pixels already consumed by target
dyConsumed Vertical scroll distance in pixels already consumed by target
dxUnconsumed Horizontal scroll distance in pixels not consumed by target
dyUnconsumed Vertical scroll distance in pixels not consumed by target

public void onNestedScrollAccepted (View child, View target, int axes)

React to the successful claiming of a nested scroll operation.

This method will be called after onStartNestedScroll returns true. It offers an opportunity for the view and its superclasses to perform initial configuration for the nested scroll. Implementations of this method should always call their superclass's implementation of this method if one is present.

Parameters
child Direct child of this ViewParent containing target
target View that initiated the nested scroll
axes Flags consisting of SCROLL_AXIS_HORIZONTAL, SCROLL_AXIS_VERTICAL or both

public boolean onRequestSendAccessibilityEvent (View child, AccessibilityEvent event)

Added in API level 14

Called when a child has requested sending an AccessibilityEvent and gives an opportunity to its parent to augment the event.

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

Parameters
child The child which requests sending the event.
event The event to be sent.
Returns
  • True if the event should be sent.

public boolean onStartNestedScroll (View child, View target, int nestedScrollAxes)

React to a descendant view initiating a nestable scroll operation, claiming the nested scroll operation if appropriate.

This method will be called in response to a descendant view invoking startNestedScroll(int). Each parent up the view hierarchy will be given an opportunity to respond and claim the nested scrolling operation by returning true.

This method may be overridden by ViewParent implementations to indicate when the view is willing to support a nested scrolling operation that is about to begin. If it returns true, this ViewParent will become the target view's nested scrolling parent for the duration of the scroll operation in progress. When the nested scroll is finished this ViewParent will receive a call to onStopNestedScroll(View).

Parameters
child Direct child of this ViewParent containing target
target View that initiated the nested scroll
nestedScrollAxes Flags consisting of SCROLL_AXIS_HORIZONTAL, SCROLL_AXIS_VERTICAL or both
Returns
  • true if this ViewParent accepts the nested scroll operation

public void onStopNestedScroll (View child)

React to a nested scroll operation ending.

Perform cleanup after a nested scrolling operation. This method will be called when a nested scroll stops, for example when a nested touch scroll ends with a ACTION_UP or ACTION_CANCEL event. Implementations of this method should always call their superclass's implementation of this method if one is present.

Parameters
child View that initiated the nested scroll

public void recomputeViewAttributes (View child)

Added in API level 1

Tell view hierarchy that the global view attributes need to be re-evaluated.

Parameters
child View whose attributes have changed.

public void removeAllViews ()

Added in API level 1

Call this method to remove all child views from the ViewGroup.

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

public void removeAllViewsInLayout ()

Added in API level 1

Called by a ViewGroup subclass to remove child views from itself, when it must first know its size on screen before it can calculate how many child views it will render. An example is a Gallery or a ListView, which may "have" 50 children, but actually only render the number of children that can currently fit inside the object on screen. Do not call this method unless you are extending ViewGroup and understand the view measuring and layout pipeline.

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

public void removeView (View view)

Added in API level 1

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

public void removeViewAt (int index)

Added in API level 1

Removes the view at the specified position in the group.

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

Parameters
index the position in the group of the view to remove

public void removeViewInLayout (View view)

Added in API level 1

Removes a view during layout. This is useful if in your onLayout() method, you need to remove more views.

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

Parameters
view the view to remove from the group

public void removeViews (int start, int count)

Added in API level 1

Removes the specified range of views from the group.

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

Parameters
start the first position in the group of the range of views to remove
count the number of views to remove

public void removeViewsInLayout (int start, int count)

Added in API level 1

Removes a range of views during layout. This is useful if in your onLayout() method, you need to remove more views.

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

Parameters
start the index of the first view to remove from the group
count the number of views to remove from the group

public void requestChildFocus (View child, View focused)

Added in API level 1

Called when a child of this parent wants focus

Parameters
child The child of this ViewParent that wants focus. This view will contain the focused view. It is not necessarily the view that actually has focus.
focused The view that is a descendant of child that actually has focus

public boolean requestChildRectangleOnScreen (View child, Rect rectangle, boolean immediate)

Added in API level 1

Called when a child of this group wants a particular rectangle to be positioned onto the screen. ViewGroups overriding this can trust that:

  • child will be a direct child of this group
  • rectangle will be in the child's coordinates

ViewGroups overriding this should uphold the contract:

  • nothing will change if the rectangle is already visible
  • the view port will be scrolled only just enough to make the rectangle visible
Parameters
child The direct child making the request.
rectangle The rectangle in the child's coordinates the child wishes to be on the screen.
immediate True to forbid animated or delayed scrolling, false otherwise
Returns
  • Whether the group scrolled to handle the operation

public void requestDisallowInterceptTouchEvent (boolean disallowIntercept)

Added in API level 1

Called when a child does not want this parent and its ancestors to intercept touch events with onInterceptTouchEvent(MotionEvent).

This parent should pass this call onto its parents. This parent must obey this request for the duration of the touch (that is, only clear the flag after this parent has received an up or a cancel.

Parameters
disallowIntercept True if the child does not want the parent to intercept touch events.

public boolean requestFocus (int direction, Rect previouslyFocusedRect)

Added in API level 1

Call this to try to give focus to a specific view or to one of its descendants and give it hints about the direction and a specific rectangle that the focus is coming from. The rectangle can help give larger views a finer grained hint about where focus is coming from, and therefore, where to show selection, or forward focus change internally. A view will not actually take focus if it is not focusable (isFocusable() returns false), or if it is focusable and it is not focusable in touch mode (isFocusableInTouchMode()) while the device is in touch mode. A View will not take focus if it is not visible. A View will not take focus if one of its parents has getDescendantFocusability() equal to FOCUS_BLOCK_DESCENDANTS. See also focusSearch(int), which is what you call to say that you have focus, and you want your parent to look for the next one. You may wish to override this method if your custom View has an internal View that it wishes to forward the request to. Looks for a view to give focus to respecting the setting specified by getDescendantFocusability(). Uses onRequestFocusInDescendants(int, android.graphics.Rect) to find focus within the children of this group when appropriate.

Parameters
direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRect The rectangle (in this View's coordinate system) to give a finer grained hint about where focus is coming from. May be null if there is no hint.
Returns
  • Whether this view or one of its descendants actually took focus.

public boolean requestSendAccessibilityEvent (View child, AccessibilityEvent event)

Added in API level 14

Called by a child to request from its parent to send an AccessibilityEvent. The child has already populated a record for itself in the event and is delegating to its parent to send the event. The parent can optionally add a record for itself.

Note: An accessibility event is fired by an individual view which populates the event with a record for its state and requests from its parent to perform the sending. The parent can optionally add a record for itself before dispatching the request to its parent. A parent can also choose not to respect the request for sending the event. The accessibility event is sent by the topmost view in the view tree.

Parameters
child The child which requests sending the event.
event The event to be sent.
Returns
  • True if the event was sent.

public void requestTransparentRegion (View child)

Added in API level 1

Called when a child wants the view hierarchy to gather and report transparent regions to the window compositor. Views that "punch" holes in the view hierarchy, such as SurfaceView can use this API to improve performance of the system. When no such a view is present in the hierarchy, this optimization in unnecessary and might slightly reduce the view hierarchy performance.

Parameters
child the view requesting the transparent region computation

public void scheduleLayoutAnimation ()

Added in API level 1

Schedules the layout animation to be played after the next layout pass of this view group. This can be used to restart the layout animation when the content of the view group changes or when the activity is paused and resumed.

public void setAddStatesFromChildren (boolean addsStates)

Added in API level 1

Sets whether this ViewGroup's drawable states also include its children's drawable states. This is used, for example, to make a group appear to be focused when its child EditText or button is focused.

public void setAlwaysDrawnWithCacheEnabled (boolean always)

Added in API level 1

Indicates whether this ViewGroup will always try to draw its children using their drawing cache. This property can be set to true when the cache rendering is slightly different from the children's normal rendering. Renderings can be different, for instance, when the cache's quality is set to low. When this property is disabled, the ViewGroup will use the drawing cache of its children only when asked to. It's usually the task of subclasses to tell ViewGroup when to start using the drawing cache and when to stop using it.

Parameters
always true to always draw with the drawing cache, false otherwise

public void setAnimationCacheEnabled (boolean enabled)

Added in API level 1

Enables or disables the children's drawing cache during a layout animation. By default, the drawing cache is enabled but this will prevent nested layout animations from working. To nest animations, you must disable the cache.

Parameters
enabled true to enable the animation cache, false otherwise

public void setClipChildren (boolean clipChildren)

Added in API level 1

By default, children are clipped to their bounds before drawing. This allows view groups to override this behavior for animations, etc.

Related XML Attributes
Parameters
clipChildren true to clip children to their bounds, false otherwise

public void setClipToPadding (boolean clipToPadding)

Added in API level 1

By default, children are clipped to the padding of the ViewGroup. This allows view groups to override this behavior

Related XML Attributes
Parameters
clipToPadding true to clip children to the padding of the group, false otherwise

public void setDescendantFocusability (int focusability)

Added in API level 1

Set the descendant focusability of this view group. This defines the relationship between this view group and its descendants when looking for a view to take focus in requestFocus(int, android.graphics.Rect).

public void setLayoutAnimation (LayoutAnimationController controller)

Added in API level 1

Sets the layout animation controller used to animate the group's children after the first layout.

Parameters
controller the animation controller

public void setLayoutAnimationListener (Animation.AnimationListener animationListener)

Added in API level 1

Specifies the animation listener to which layout animation events must be sent. Only onAnimationStart(Animation) and onAnimationEnd(Animation) are invoked.

Parameters
animationListener the layout animation listener

public void setLayoutMode (int layoutMode)

Added in API level 18

Sets the basis of alignment during the layout of this ViewGroup. Valid values are either LAYOUT_MODE_CLIP_BOUNDS or LAYOUT_MODE_OPTICAL_BOUNDS.

Related XML Attributes
Parameters
layoutMode the layout mode to use during layout operations
See Also

public void setLayoutTransition (LayoutTransition transition)

Added in API level 11

Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is not null, changes in layout which occur because of children being added to or removed from the ViewGroup will be animated according to the animations defined in that LayoutTransition object. By default, the transition object is null (so layout changes are not animated).

Replacing a non-null transition will cause that previous transition to be canceled, if it is currently running, to restore this container to its correct post-transition state.

Related XML Attributes
Parameters
transition The LayoutTransition object that will animated changes in layout. A value of null means no transition will run on layout changes.

public void setMotionEventSplittingEnabled (boolean split)

Added in API level 11

Enable or disable the splitting of MotionEvents to multiple children during touch event dispatch. This behavior is enabled by default for applications that target an SDK version of HONEYCOMB or newer.

When this option is enabled MotionEvents may be split and dispatched to different child views depending on where each pointer initially went down. This allows for user interactions such as scrolling two panes of content independently, chording of buttons, and performing independent gestures on different pieces of content.

Related XML Attributes
Parameters
split true to allow MotionEvents to be split and dispatched to multiple child views. false to only allow one child view to be the target of any MotionEvent received by this ViewGroup.

public void setOnHierarchyChangeListener (ViewGroup.OnHierarchyChangeListener listener)

Added in API level 1

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

Parameters
listener the callback to invoke on hierarchy change

public void setPersistentDrawingCache (int drawingCacheToKeep)

Added in API level 1

Indicates what types of drawing caches should be kept in memory after they have been created.

Parameters
drawingCacheToKeep one or a combination of PERSISTENT_NO_CACHE, PERSISTENT_ANIMATION_CACHE, PERSISTENT_SCROLLING_CACHE and PERSISTENT_ALL_CACHES

public void setTransitionGroup (boolean isTransitionGroup)

Changes whether or not this ViewGroup should be treated as a single entity during Activity Transitions.

Parameters
isTransitionGroup Whether or not the ViewGroup should be treated as a unit in Activity transitions. If false, the ViewGroup won't transition, only its children. If true, the entire ViewGroup will transition together.

public boolean shouldDelayChildPressedState ()

Added in API level 14

Return true if the pressed state should be delayed for children or descendants of this ViewGroup. Generally, this should be done for containers that can scroll, such as a List. This prevents the pressed state from appearing when the user is actually trying to scroll the content. The default implementation returns true for compatibility reasons. Subclasses that do not scroll should generally override this method and return false.

public boolean showContextMenuForChild (View originalView)

Added in API level 1

Bring up a context menu for the specified view or its ancestors.

In most cases, a subclass does not need to override this. However, if the subclass is added directly to the window manager (for example, addView(View, android.view.ViewGroup.LayoutParams)) then it should override this and show the context menu.

Parameters
originalView The source view where the context menu was first invoked
Returns
  • true if a context menu was displayed

public ActionMode startActionModeForChild (View originalView, ActionMode.Callback callback)

Added in API level 11

Start an action mode for the specified view.

In most cases, a subclass does not need to override this. However, if the subclass is added directly to the window manager (for example, addView(View, android.view.ViewGroup.LayoutParams)) then it should override this and start the action mode.

Parameters
originalView The source view where the action mode was first invoked
callback The callback that will handle lifecycle events for the action mode
Returns
  • The new action mode if it was started, null otherwise

public void startLayoutAnimation ()

Added in API level 1

Runs the layout animation. Calling this method triggers a relayout of this view group.

public void startViewTransition (View view)

Added in API level 11

This method tells the ViewGroup that the given View object, which should have this ViewGroup as its parent, should be kept around (re-displayed when the ViewGroup draws its children) even if it is removed from its parent. This allows animations, such as those used by Fragment and LayoutTransition to animate the removal of views. A call to this method should always be accompanied by a later call to endViewTransition(View), such as after an animation on the View has finished, so that the View finally gets removed.

Parameters
view The View object to be kept visible even if it gets removed from its parent.

public void updateViewLayout (View view, ViewGroup.LayoutParams params)

Added in API level 1

Protected Methods

protected boolean addViewInLayout (View child, int index, ViewGroup.LayoutParams params, boolean preventRequestLayout)

Added in API level 1

Adds a view during layout. This is useful if in your onLayout() method, you need to add more views (as does the list view for example). If index is negative, it means put it at the end of the list.

Parameters
child the view to add to the group
index the index at which the child must be added
params the layout parameters to associate with the child
preventRequestLayout if true, calling this method will not trigger a layout request on child
Returns
  • true if the child was added, false otherwise

protected boolean addViewInLayout (View child, int index, ViewGroup.LayoutParams params)

Added in API level 1

Adds a view during layout. This is useful if in your onLayout() method, you need to add more views (as does the list view for example). If index is negative, it means put it at the end of the list.

Parameters
child the view to add to the group
index the index at which the child must be added
params the layout parameters to associate with the child
Returns
  • true if the child was added, false otherwise

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 void attachViewToParent (View child, int index, ViewGroup.LayoutParams params)

Added in API level 1

Attaches a view to this view group. Attaching a view assigns this group as the parent, sets the layout parameters and puts the view in the list of children so that it can be retrieved by calling getChildAt(int).

This method is intended to be lightweight and makes no assumptions about whether the parent or child should be redrawn. Proper use of this method will include also making any appropriate requestLayout() or invalidate() calls. For example, callers can post a Runnable which performs a requestLayout() on the next frame, after all detach/attach calls are finished, causing layout to be run prior to redrawing the view hierarchy.

This method should be called only for views which were detached from their parent.

Parameters
child the child to attach
index the index at which the child should be attached
params the layout parameters of the child

protected boolean canAnimate ()

Added in API level 1

Indicates whether the view group has the ability to animate its children after the first layout.

Returns
  • true if the children can be animated, false otherwise

protected boolean checkLayoutParams (ViewGroup.LayoutParams p)

Added in API level 1

protected void cleanupLayoutState (View child)

Added in API level 1

Prevents the specified child to be laid out during the next layout pass.

Parameters
child the child on which to perform the cleanup

protected void debug (int depth)

Added in API level 1

Prints information about this view in the log output, with the tag VIEW_LOG_TAG. Each line in the output is preceded with an indentation defined by the depth.

Parameters
depth the indentation level

protected void detachAllViewsFromParent ()

Added in API level 1

Detaches all views from the parent. Detaching a view should be followed either by a call to attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(View, boolean). Detachment should only be temporary; reattachment or removal should happen within the same drawing cycle as detachment. When a view is detached, its parent is null and cannot be retrieved by a call to getChildAt(int).

protected void detachViewFromParent (View child)

Added in API level 1

Detaches a view from its parent. Detaching a view should be followed either by a call to attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(View, boolean). Detachment should only be temporary; reattachment or removal should happen within the same drawing cycle as detachment. When a view is detached, its parent is null and cannot be retrieved by a call to getChildAt(int).

Parameters
child the child to detach

protected void detachViewFromParent (int index)

Added in API level 1

Detaches a view from its parent. Detaching a view should be followed either by a call to attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(View, boolean). Detachment should only be temporary; reattachment or removal should happen within the same drawing cycle as detachment. When a view is detached, its parent is null and cannot be retrieved by a call to getChildAt(int).

Parameters
index the index of the child to detach

protected void detachViewsFromParent (int start, int count)

Added in API level 1

Detaches a range of views from their parents. Detaching a view should be followed either by a call to attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(View, boolean). Detachment should only be temporary; reattachment or removal should happen within the same drawing cycle as detachment. When a view is detached, its parent is null and cannot be retrieved by a call to getChildAt(int).

Parameters
start the first index of the childrend range to detach
count the number of children to detach

protected void dispatchDraw (Canvas canvas)

Added in API level 1

Called by draw to draw the child views. This may be overridden by derived classes to gain control just before its children are drawn (but after its own view has been drawn).

Parameters
canvas the canvas on which to draw the view

protected void dispatchFreezeSelfOnly (SparseArray<Parcelable> container)

Added in API level 1

Perform dispatching of a saveHierarchyState(android.util.SparseArray) freeze()} to only this view, not to its children. For use when overriding dispatchSaveInstanceState(android.util.SparseArray) dispatchFreeze()} to allow subclasses to freeze their own state but not the state of their children.

Parameters
container the container

protected boolean dispatchGenericFocusedEvent (MotionEvent event)

Added in API level 14

Dispatch a generic motion event to the currently focused view.

Do not call this method directly. Call dispatchGenericMotionEvent(MotionEvent) instead.

Parameters
event The motion event to be dispatched.
Returns
  • True if the event was handled by the view, false otherwise.

protected boolean dispatchGenericPointerEvent (MotionEvent event)

Added in API level 14

Dispatch a generic motion event to the view under the first pointer.

Do not call this method directly. Call dispatchGenericMotionEvent(MotionEvent) instead.

Parameters
event The motion event to be dispatched.
Returns
  • True if the event was handled by the view, false otherwise.

protected boolean dispatchHoverEvent (MotionEvent event)

Added in API level 14

Dispatch a hover event.

Do not call this method directly. Call dispatchGenericMotionEvent(MotionEvent) instead.

Parameters
event The motion event to be dispatched.
Returns
  • True if the event was handled by the view, false otherwise.

protected void dispatchRestoreInstanceState (SparseArray<Parcelable> container)

Added in API level 1

Called by restoreHierarchyState(android.util.SparseArray) to retrieve the state for this view and its children. May be overridden to modify how restoring happens to a view's children; for example, some views may want to not store state for their children.

Parameters
container The SparseArray which holds previously saved state.

protected void dispatchSaveInstanceState (SparseArray<Parcelable> container)

Added in API level 1

Called by saveHierarchyState(android.util.SparseArray) to store the state for this view and its children. May be overridden to modify how freezing happens to a view's children; for example, some views may want to not store state for their children.

Parameters
container The SparseArray in which to save the view's state.

protected void dispatchSetPressed (boolean pressed)

Added in API level 1

Dispatch setPressed to all of this View's children.

Parameters
pressed The new pressed state

protected void dispatchThawSelfOnly (SparseArray<Parcelable> container)

Added in API level 1

Perform dispatching of a restoreHierarchyState(android.util.SparseArray) to only this view, not to its children. For use when overriding dispatchRestoreInstanceState(android.util.SparseArray) to allow subclasses to thaw their own state but not the state of their children.

Parameters
container the container

protected void dispatchVisibilityChanged (View changedView, int visibility)

Added in API level 8

Dispatch a view visibility change down the view hierarchy. ViewGroups should override to route to their children.

Parameters
changedView The view whose visibility changed. Could be 'this' or an ancestor view.
visibility The new visibility of changedView: VISIBLE, INVISIBLE or GONE.

protected boolean drawChild (Canvas canvas, View child, long drawingTime)

Added in API level 1

Draw one child of this View Group. This method is responsible for getting the canvas in the right state. This includes clipping, translating so that the child's scrolled origin is at 0, 0, and applying any animation transformations.

Parameters
canvas The canvas on which to draw the child
child Who to draw
drawingTime The time at which draw is occurring
Returns
  • True if an invalidate() was issued

protected void drawableStateChanged ()

Added in API level 1

This function is called whenever the state of the view changes in such a way that it impacts the state of drawables being shown.

If the View has a StateListAnimator, it will also be called to run necessary state change animations.

Be sure to call through to the superclass when overriding this function.

protected ViewGroup.LayoutParams generateDefaultLayoutParams ()

Added in API level 1

Returns a set of default layout parameters. These parameters are requested when the View passed to addView(View) has no layout parameters already set. If null is returned, an exception is thrown from addView.

Returns
  • a set of default layout parameters or null

protected ViewGroup.LayoutParams generateLayoutParams (ViewGroup.LayoutParams p)

Added in API level 1

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 The layout parameters to convert into a suitable set of layout parameters for this ViewGroup.
Returns

protected int getChildDrawingOrder (int childCount, int i)

Added in API level 1

Returns the index of the child to draw for this iteration. Override this if you want to change the drawing order of children. By default, it returns i.

NOTE: In order for this method to be called, you must enable child ordering first by calling setChildrenDrawingOrderEnabled(boolean).

Parameters
i The current iteration.
Returns
  • The index of the child to draw this iteration.

protected boolean getChildStaticTransformation (View child, Transformation t)

Added in API level 1

Sets t to be the static transformation of the child, if set, returning a boolean to indicate whether a static transform was set. The default implementation simply returns false; subclasses may override this method for different behavior. setStaticTransformationsEnabled(boolean) must be set to true for this method to be called.

Parameters
child The child view whose static transform is being requested
t The Transformation which will hold the result
Returns
  • true if the transformation was set, false otherwise

protected boolean isChildrenDrawingOrderEnabled ()

Added in API level 7

Indicates whether the ViewGroup is drawing its children in the order defined by getChildDrawingOrder(int, int).

Returns

protected boolean isChildrenDrawnWithCacheEnabled ()

Added in API level 1

Indicates whether the ViewGroup is currently drawing its children using their drawing cache.

Returns
  • true if children should be drawn with their cache, false otherwise

protected void measureChild (View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)

Added in API level 1

Ask one of the children of this view to measure itself, taking into account both the MeasureSpec requirements for this view and its padding. The heavy lifting is done in getChildMeasureSpec.

Parameters
child The child to measure
parentWidthMeasureSpec The width requirements for this view
parentHeightMeasureSpec The height requirements for this view

protected void measureChildWithMargins (View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)

Added in API level 1

Ask one of the children of this view to measure itself, taking into account both the MeasureSpec requirements for this view and its padding and margins. The child must have MarginLayoutParams The heavy lifting is done in getChildMeasureSpec.

Parameters
child The child to measure
parentWidthMeasureSpec The width requirements for this view
widthUsed Extra space that has been used up by the parent horizontally (possibly by other children of the parent)
parentHeightMeasureSpec The height requirements for this view
heightUsed Extra space that has been used up by the parent vertically (possibly by other children of the parent)

protected void measureChildren (int widthMeasureSpec, int heightMeasureSpec)

Added in API level 1

Ask all of the children of this view to measure themselves, taking into account both the MeasureSpec requirements for this view and its padding. We skip children that are in the GONE state The heavy lifting is done in getChildMeasureSpec.

Parameters
widthMeasureSpec The width requirements for this view
heightMeasureSpec The height requirements for this view

protected void onAnimationEnd ()

Added in API level 1

Invoked by a parent ViewGroup to notify the end of the animation currently associated with this view. If you override this method, always call super.onAnimationEnd();

protected void onAnimationStart ()

Added in API level 1

Invoked by a parent ViewGroup to notify the start of the animation currently associated with this view. If you override this method, always call super.onAnimationStart();

protected void onAttachedToWindow ()

Added in API level 1

This is called when the view is attached to a window. At this point it has a Surface and will start drawing. Note that this function is guaranteed to be called before onDraw(android.graphics.Canvas), however it may be called any time before the first onDraw -- including before or after onMeasure(int, int).

protected int[] onCreateDrawableState (int extraSpace)

Added in API level 1

Generate the new Drawable state for this view. This is called by the view system when the cached Drawable state is determined to be invalid. To retrieve the current state, you should use getDrawableState().

Parameters
extraSpace if non-zero, this is the number of extra entries you would like in the returned array in which you can place your own states.
Returns
  • Returns an array holding the current Drawable state of the view.

protected void onDetachedFromWindow ()

Added in API level 1

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.

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

Added in API level 1

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 This is a new size or position for this view
l Left position, relative to parent
t Top position, relative to parent
r Right position, relative to parent
b Bottom position, relative to parent

protected boolean onRequestFocusInDescendants (int direction, Rect previouslyFocusedRect)

Added in API level 1

Look for a descendant to call requestFocus() on. Called by requestFocus(int, android.graphics.Rect) when it wants to request focus within its children. Override this to customize how your ViewGroup requests focus within its children.

Parameters
direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRect The rectangle (in this View's coordinate system) to give a finer grained hint about where focus is coming from. May be null if there is no hint.
Returns
  • Whether focus was taken.

protected void removeDetachedView (View child, boolean animate)

Added in API level 1

Finishes the removal of a detached view. This method will dispatch the detached from window event and notify the hierarchy change listener.

This method is intended to be lightweight and makes no assumptions about whether the parent or child should be redrawn. Proper use of this method will include also making any appropriate requestLayout() or invalidate() calls. For example, callers can post a Runnable which performs a requestLayout() on the next frame, after all detach/remove calls are finished, causing layout to be run prior to redrawing the view hierarchy.

Parameters
child the child to be definitely removed from the view hierarchy
animate if true and the view has an animation, the view is placed in the disappearing views list, otherwise, it is detached from the window

protected void setChildrenDrawingCacheEnabled (boolean enabled)

Added in API level 1

Enables or disables the drawing cache for each child of this view group.

Parameters
enabled true to enable the cache, false to dispose of it

protected void setChildrenDrawingOrderEnabled (boolean enabled)

Added in API level 7

Tells the ViewGroup whether to draw its children in the order defined by the method getChildDrawingOrder(int, int).

Parameters
enabled true if the order of the children when drawing is determined by getChildDrawingOrder(int, int), false otherwise

protected void setChildrenDrawnWithCacheEnabled (boolean enabled)

Added in API level 1

Tells the ViewGroup to draw its children using their drawing cache. This property is ignored when isAlwaysDrawnWithCacheEnabled() is true. A child's drawing cache will be used only if it has been enabled. Subclasses should call this method to start and stop using the drawing cache when they perform performance sensitive operations, like scrolling or animating.

Parameters
enabled true if children should be drawn with their cache, false otherwise

protected void setStaticTransformationsEnabled (boolean enabled)

Added in API level 3

When this property is set to true, this ViewGroup supports static transformations on children; this causes getChildStaticTransformation(View, android.view.animation.Transformation) to be invoked when a child is drawn. Any subclass overriding getChildStaticTransformation(View, android.view.animation.Transformation) should set this property to true.

Parameters
enabled True to enable static transformations on children, false otherwise.