Most visited

Recently visited

Added in API level 1

ViewGroup

public abstract class ViewGroup
extends View implements ViewParent, ViewManager

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
Known Direct Subclasses
Known Indirect Subclasses


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

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 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 Defines whether a child is limited to draw inside of its bounds or not. 
android:clipToPadding Defines whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero. 
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 Defines the layout mode of this ViewGroup. 
android:persistentDrawingCache Defines the persistence of the drawing cache. 
android:splitMotionEvents Sets whether this ViewGroup should split MotionEvents to separate child views during touch event dispatch. 

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.

Inherited constants

From class android.view.View

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> outChildren)

Adds the children of this View relevant for accessibility to the given list as output.

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, 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, int index, ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

void addView(View child)

Adds a child view.

void addView(View child, int 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.

void dispatchDrawableHotspotChanged(float x, float y)

Dispatches drawable hotspot changes to child views that meet at least one of the following criteria:

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 dispatchProvideStructure(ViewStructure structure)

Dispatch creation of ViewStructure down the hierarchy.

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)

Dispatch callbacks to setOnSystemUiVisibilityChangeListener(View.OnSystemUiVisibilityChangeListener) down the view hierarchy.

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.

CharSequence getAccessibilityClassName()

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

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.

boolean getClipToPadding()

Returns whether this ViewGroup will clip its children to its padding, and resize (but not clip) any EdgeEffect to the padded region, if padding is present.

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 getTouchscreenBlocksFocus()

Check whether this ViewGroup should ignore focus requests for itself and its children.

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()

This method was deprecated in API level 23. As of M, this property is ignored. Child views may no longer have their caching behavior disabled by parents.

boolean isAnimationCacheEnabled()

This method was deprecated in API level 23. As of M, this property is ignored. Caching behavior of children may be controlled through setLayerType(int, Paint).

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.

boolean onNestedPreFling(View target, float velocityX, float velocityY)

React to a nested fling before the target view consumes it.

boolean onNestedPrePerformAccessibilityAction(View target, int action, Bundle args)

React to an accessibility action delegated by a target descendant view before the target processes it.

Subclasses should always call super.onNestedPrePerformAccessibilityAction

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.

PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex)

Returns the pointer icon for the motion event, or null if it doesn't specify the icon.

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 onViewAdded(View child)

Called when a new child is added to this ViewGroup.

void onViewRemoved(View child)

Called when a child view is removed from this ViewGroup.

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)

This method was deprecated in API level 23. As of M, this property is ignored. Child views may no longer have their caching behavior disabled by parents.

void setAnimationCacheEnabled(boolean enabled)

This method was deprecated in API level 23. As of M, this property is ignored. Caching behavior of children may be controlled through setLayerType(int, Paint).

void setClipChildren(boolean clipChildren)

By default, children are clipped to their bounds before drawing.

void setClipToPadding(boolean clipToPadding)

Sets whether this ViewGroup will clip its children to its padding and resize (but not clip) any EdgeEffect to the padded region, if padding is present.

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 setTouchscreenBlocksFocus(boolean touchscreenBlocksFocus)

Set whether this ViewGroup should ignore focus requests for itself and its children.

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, float x, float y)

Shows the context menu for the specified view or its ancestors anchored to the specified view-relative coordinate.

boolean showContextMenuForChild(View originalView)

Shows the context menu for the specified view or its ancestors.

ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback, int type)

Start an action mode of a specific type for the specified view.

ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback)

Start an action mode for the specified view with the default type TYPE_PRIMARY.

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(int index)

Detaches a view from its parent.

void detachViewFromParent(View child)

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()

This method was deprecated in API level 23. As of M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use setLayerType(int, Paint) on individual Views instead.

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

This method was deprecated in API level 23. As of M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use setLayerType(int, Paint) on individual Views instead.

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.

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.accessibility.AccessibilityEventSource
From interface android.view.ViewParent
From interface android.view.ViewManager

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.

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.

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.

Related methods:

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.

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 children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero. 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.

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.

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.

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.

Related methods:

Constants

CLIP_TO_PADDING_MASK

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

Constant Value: 34 (0x00000022)

FOCUS_AFTER_DESCENDANTS

Added in API level 1
int FOCUS_AFTER_DESCENDANTS

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

Constant Value: 262144 (0x00040000)

FOCUS_BEFORE_DESCENDANTS

Added in API level 1
int FOCUS_BEFORE_DESCENDANTS

This view will get focus before any of its descendants.

Constant Value: 131072 (0x00020000)

FOCUS_BLOCK_DESCENDANTS

Added in API level 1
int FOCUS_BLOCK_DESCENDANTS

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

Constant Value: 393216 (0x00060000)

LAYOUT_MODE_CLIP_BOUNDS

Added in API level 18
int LAYOUT_MODE_CLIP_BOUNDS

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

Constant Value: 0 (0x00000000)

LAYOUT_MODE_OPTICAL_BOUNDS

Added in API level 18
int LAYOUT_MODE_OPTICAL_BOUNDS

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)

PERSISTENT_ALL_CACHES

Added in API level 1
int PERSISTENT_ALL_CACHES

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

Constant Value: 3 (0x00000003)

PERSISTENT_ANIMATION_CACHE

Added in API level 1
int PERSISTENT_ANIMATION_CACHE

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

Constant Value: 1 (0x00000001)

PERSISTENT_NO_CACHE

Added in API level 1
int PERSISTENT_NO_CACHE

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

Constant Value: 0 (0x00000000)

PERSISTENT_SCROLLING_CACHE

Added in API level 1
int PERSISTENT_SCROLLING_CACHE

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

Constant Value: 2 (0x00000002)

Public constructors

ViewGroup

Added in API level 1
ViewGroup (Context context)

Parameters
context Context

ViewGroup

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

Parameters
context Context
attrs AttributeSet

ViewGroup

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

Parameters
context Context
attrs AttributeSet
defStyleAttr int

ViewGroup

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

Parameters
context Context
attrs AttributeSet
defStyleAttr int
defStyleRes int

Public methods

addChildrenForAccessibility

Added in API level 16
void addChildrenForAccessibility (ArrayList<View> outChildren)

Adds the children of this View relevant for accessibility to the given list as output. Since some Views are not important for accessibility the added child views are not necessarily direct children of this view, rather they are the first level of descendants important for accessibility.

Parameters
outChildren ArrayList: The output list that will receive children for accessibility.

addFocusables

Added in API level 4
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. 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 enabled depending on the focusable mode parameter.

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

addStatesFromChildren

Added in API level 1
boolean addStatesFromChildren ()

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.

Returns
boolean

addTouchables

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

Parameters
views ArrayList: Touchable views found so far

addView

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

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 View: the child view to add
params ViewGroup.LayoutParams: the layout parameters to set on the child

addView

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

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

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

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

See also:

addView

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

Adds a child view with the specified layout parameters.

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

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

addView

Added in API level 1
void addView (View child)

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

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

Parameters
child View: the child view to add

See also:

addView

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

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 View: the child view to add
width int
height int

bringChildToFront

Added in API level 1
void bringChildToFront (View child)

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 View: The child to bring to the top of the z order

childDrawableStateChanged

Added in API level 1
void childDrawableStateChanged (View child)

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

Parameters
child View: The child whose drawable state has changed.

childHasTransientStateChanged

Added in API level 19
void childHasTransientStateChanged (View child, 
                boolean childHasTransientState)

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

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

clearChildFocus

Added in API level 1
void clearChildFocus (View child)

Called when a child of this parent is giving up focus

Parameters
child View: The view that is giving up focus

clearDisappearingChildren

Added in API level 1
void clearDisappearingChildren ()

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

clearFocus

Added in API level 1
void clearFocus ()

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 which the framework will give focus to this view.

dispatchApplyWindowInsets

Added in API level 20
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 WindowInsets: Insets to apply
Returns
WindowInsets The provided insets minus the insets that were consumed

dispatchConfigurationChanged

Added in API level 8
void dispatchConfigurationChanged (Configuration newConfig)

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

Parameters
newConfig Configuration: The new resource configuration.

dispatchDisplayHint

Added in API level 8
void dispatchDisplayHint (int hint)

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 int: A hint about whether or not this view is displayed: VISIBLE or INVISIBLE.

dispatchDragEvent

Added in API level 11
boolean dispatchDragEvent (DragEvent event)

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.

Parameters
event DragEvent
Returns
boolean

dispatchDrawableHotspotChanged

Added in API level 22
void dispatchDrawableHotspotChanged (float x, 
                float y)

Dispatches drawable hotspot changes to child views that meet at least one of the following criteria:

Parameters
x float: hotspot x coordinate
y float: hotspot y coordinate

See also:

dispatchKeyEvent

Added in API level 1
boolean dispatchKeyEvent (KeyEvent event)

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 KeyEvent: The key event to be dispatched.
Returns
boolean True if the event was handled, false otherwise.

dispatchKeyEventPreIme

Added in API level 3
boolean dispatchKeyEventPreIme (KeyEvent event)

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 KeyEvent: The key event to be dispatched.
Returns
boolean True if the event was handled, false otherwise.

dispatchKeyShortcutEvent

Added in API level 1
boolean dispatchKeyShortcutEvent (KeyEvent event)

Dispatches a key shortcut event.

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

dispatchProvideStructure

Added in API level 23
void dispatchProvideStructure (ViewStructure structure)

Dispatch creation of ViewStructure down the hierarchy. This implementation adds in all child views of the view group, in addition to calling the default View implementation.

Parameters
structure ViewStructure

dispatchSetActivated

Added in API level 11
void dispatchSetActivated (boolean activated)

Dispatch setActivated to all of this View's children.

Parameters
activated boolean: The new activated state

dispatchSetSelected

Added in API level 1
void dispatchSetSelected (boolean selected)

Dispatch setSelected to all of this View's children.

Parameters
selected boolean: The new selected state

dispatchSystemUiVisibilityChanged

Added in API level 11
void dispatchSystemUiVisibilityChanged (int visible)

Dispatch callbacks to setOnSystemUiVisibilityChangeListener(View.OnSystemUiVisibilityChangeListener) down the view hierarchy.

Parameters
visible int

dispatchTouchEvent

Added in API level 1
boolean dispatchTouchEvent (MotionEvent ev)

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

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

dispatchTrackballEvent

Added in API level 1
boolean dispatchTrackballEvent (MotionEvent event)

Pass a trackball motion event down to the focused view.

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

dispatchUnhandledMove

Added in API level 1
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. 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 View: The currently focused view.
direction int: The direction focus wants to move. One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT.
Returns
boolean True if the this view consumed this unhandled move.

dispatchWindowFocusChanged

Added in API level 1
void dispatchWindowFocusChanged (boolean hasFocus)

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

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

dispatchWindowSystemUiVisiblityChanged

Added in API level 16
void dispatchWindowSystemUiVisiblityChanged (int visible)

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

Parameters
visible int

dispatchWindowVisibilityChanged

Added in API level 1
void dispatchWindowVisibilityChanged (int visibility)

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

Parameters
visibility int: The new visibility of the window.

endViewTransition

Added in API level 11
void endViewTransition (View view)

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.

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

findFocus

Added in API level 1
View findFocus ()

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

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

findViewsWithText

Added in API level 14
void findViewsWithText (ArrayList<View> outViews, 
                CharSequence text, 
                int flags)

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 ArrayList: The output list of matching Views.
text CharSequence: The text to match against.
flags int

focusSearch

Added in API level 1
View focusSearch (View focused, 
                int direction)

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

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

focusableViewAvailable

Added in API level 1
void focusableViewAvailable (View v)

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 View: The view that has become newly focusable

gatherTransparentRegion

Added in API level 1
boolean gatherTransparentRegion (Region region)

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 Region: The transparent region for this ViewAncestor (window).
Returns
boolean 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.

generateLayoutParams

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

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

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

getAccessibilityClassName

Added in API level 23
CharSequence getAccessibilityClassName ()

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

Returns
CharSequence

getChildAt

Added in API level 1
View getChildAt (int index)

Returns the view at the specified position in the group.

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

getChildCount

Added in API level 1
int getChildCount ()

Returns the number of children in the group.

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

getChildMeasureSpec

Added in API level 1
int getChildMeasureSpec (int spec, 
                int padding, 
                int childDimension)

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 int: The requirements for this view
padding int: The padding of this view for the current dimension and margins, if applicable
childDimension int: How big the child wants to be in the current dimension
Returns
int a MeasureSpec integer for the child

getChildVisibleRect

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

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 View: A child View, whose rectangular visible region we want to compute
r Rect: The input rectangle, defined in the child coordinate system. Will be overwritten to contain the resulting visible rectangle, expressed in global (root) coordinates
offset Point: 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
boolean true if the resulting rectangle is not empty, false otherwise

getClipChildren

Added in API level 18
boolean getClipChildren ()

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

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

See also:

getClipToPadding

Added in API level 21
boolean getClipToPadding ()

Returns whether this ViewGroup will clip its children to its padding, and resize (but not clip) any EdgeEffect to the padded region, if padding is present.

By default, children are clipped to the padding of their parent Viewgroup. This clipping behavior is only enabled if padding is non-zero.

Related XML Attributes:

Returns
boolean true if this ViewGroup clips children to its padding and resizes (but doesn't clip) any EdgeEffect to the padded region, false otherwise.

getDescendantFocusability

Added in API level 1
int getDescendantFocusability ()

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

Returns
int one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS.

getFocusedChild

Added in API level 1
View getFocusedChild ()

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

Returns
View the focused child or null.

getLayoutAnimation

Added in API level 1
LayoutAnimationController getLayoutAnimation ()

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

Returns
LayoutAnimationController the current animation controller

getLayoutAnimationListener

Added in API level 1
Animation.AnimationListener getLayoutAnimationListener ()

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

Returns
Animation.AnimationListener an Animation.AnimationListener

getLayoutMode

Added in API level 18
int getLayoutMode ()

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
int the layout mode to use during layout operations

See also:

getLayoutTransition

Added in API level 11
LayoutTransition getLayoutTransition ()

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
LayoutTransition LayoutTranstion The LayoutTransition object that will animated changes in layout. A value of null means no transition will run on layout changes.

getNestedScrollAxes

Added in API level 21
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
int Flags indicating the current axes of nested scrolling

See also:

getOverlay

Added in API level 18
ViewGroupOverlay getOverlay ()

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
ViewGroupOverlay The ViewGroupOverlay object for this view.

See also:

getPersistentDrawingCache

Added in API level 1
int getPersistentDrawingCache ()

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

Returns
int one or a combination of PERSISTENT_NO_CACHE, PERSISTENT_ANIMATION_CACHE, PERSISTENT_SCROLLING_CACHE and PERSISTENT_ALL_CACHES

See also:

getTouchscreenBlocksFocus

Added in API level 21
boolean getTouchscreenBlocksFocus ()

Check whether this ViewGroup should ignore focus requests for itself and its children.

Returns
boolean

hasFocus

Added in API level 1
boolean hasFocus ()

Returns true if this view has or contains focus

Returns
boolean true if this view has or contains focus

hasFocusable

Added in API level 1
boolean hasFocusable ()

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
boolean True if the view is focusable or if the view contains a focusable View, false otherwise.

hasTransientState

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

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
boolean true if the view has transient state

indexOfChild

Added in API level 1
int indexOfChild (View child)

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

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

invalidateChild

Added in API level 1
void invalidateChild (View child, 
                Rect dirty)

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

Parameters
child View: The child which is dirty
dirty Rect: The area within the child that is invalid

invalidateChildInParent

Added in API level 1
ViewParent invalidateChildInParent (int[] location, 
                Rect dirty)

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 int: An array of 2 ints containing the left and top coordinates of the child to invalidate
dirty Rect: The area within the child that is invalid
Returns
ViewParent the parent of this ViewParent or null

isAlwaysDrawnWithCacheEnabled

Added in API level 1
boolean isAlwaysDrawnWithCacheEnabled ()

This method was deprecated in API level 23.
As of M, this property is ignored. Child views may no longer have their caching behavior disabled by parents.

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

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

See also:

isAnimationCacheEnabled

Added in API level 1
boolean isAnimationCacheEnabled ()

This method was deprecated in API level 23.
As of M, this property is ignored. Caching behavior of children may be controlled through setLayerType(int, Paint).

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
boolean true if the animation cache is enabled, false otherwise

See also:

isMotionEventSplittingEnabled

Added in API level 11
boolean isMotionEventSplittingEnabled ()

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

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

isTransitionGroup

Added in API level 21
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
boolean True if the ViewGroup should be acted on together during an Activity transition. The default value is true when there is a non-null background or if getTransitionName() is not null or if a non-null ViewOutlineProvider other than BACKGROUND was given to setOutlineProvider(ViewOutlineProvider) and false otherwise.

jumpDrawablesToCurrentState

Added in API level 11
void jumpDrawablesToCurrentState ()

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

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

layout

Added in API level 1
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. (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 int: Left position, relative to parent
t int: Top position, relative to parent
r int: Right position, relative to parent
b int: Bottom position, relative to parent

notifySubtreeAccessibilityStateChanged

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

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

offsetDescendantRectToMyCoords

Added in API level 1
void offsetDescendantRectToMyCoords (View descendant, 
                Rect rect)

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

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

offsetRectIntoDescendantCoords

Added in API level 1
void offsetRectIntoDescendantCoords (View descendant, 
                Rect rect)

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

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

onInterceptHoverEvent

Added in API level 14
boolean onInterceptHoverEvent (MotionEvent event)

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 handles mouse hover on the scroll bars.

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

onInterceptTouchEvent

Added in API level 1
boolean onInterceptTouchEvent (MotionEvent ev)

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 MotionEvent: The motion event being dispatched down the hierarchy.
Returns
boolean 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.

onNestedFling

Added in API level 21
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: View that initiated the nested scroll
velocityX float: Horizontal velocity in pixels per second
velocityY float: Vertical velocity in pixels per second
consumed boolean: true if the child consumed the fling, false otherwise
Returns
boolean true if this parent consumed or otherwise reacted to the fling

onNestedPreFling

Added in API level 21
boolean onNestedPreFling (View target, 
                float velocityX, 
                float velocityY)

React to a nested fling before the target view consumes it.

This method siginfies that a nested scrolling child has detected a fling with the given velocity along each axis. 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 parent is consuming motion as part of a pre-scroll, it may be appropriate for it to also consume the pre-fling to complete that same motion. By returning true from this method, the parent indicates that the child should not fling its own internal content as well.

Parameters
target View: View that initiated the nested scroll
velocityX float: Horizontal velocity in pixels per second
velocityY float: Vertical velocity in pixels per second
Returns
boolean true if this parent consumed the fling ahead of the target view

onNestedPrePerformAccessibilityAction

Added in API level 22
boolean onNestedPrePerformAccessibilityAction (View target, 
                int action, 
                Bundle args)

React to an accessibility action delegated by a target descendant view before the target processes it.

This method may be called by a target descendant view if the target wishes to give a view in its parent chain a chance to react to the event before normal processing occurs. Most commonly this will be a scroll event such as ACTION_SCROLL_FORWARD. A ViewParent that supports acting as a nested scrolling parent should override this method and act accordingly to implement scrolling via accesibility systems.

Subclasses should always call super.onNestedPrePerformAccessibilityAction

Parameters
target View: The target view dispatching this action
action int: Action being performed; see AccessibilityNodeInfo
args Bundle: Optional action arguments
Returns
boolean false by default. Subclasses should return true if they handle the event.

onNestedPreScroll

Added in API level 21
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: View that initiated the nested scroll
dx int: Horizontal scroll distance in pixels
dy int: Vertical scroll distance in pixels
consumed int: Output. The horizontal and vertical scroll distance consumed by this parent

onNestedScroll

Added in API level 21
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 View: The descendent view controlling the nested scroll
dxConsumed int: Horizontal scroll distance in pixels already consumed by target
dyConsumed int: Vertical scroll distance in pixels already consumed by target
dxUnconsumed int: Horizontal scroll distance in pixels not consumed by target
dyUnconsumed int: Vertical scroll distance in pixels not consumed by target

onNestedScrollAccepted

Added in API level 21
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 View: Direct child of this ViewParent containing target
target View: View that initiated the nested scroll
axes int: Flags consisting of SCROLL_AXIS_HORIZONTAL, SCROLL_AXIS_VERTICAL or both

onRequestSendAccessibilityEvent

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

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 View: The child which requests sending the event.
event AccessibilityEvent: The event to be sent.
Returns
boolean True if the event should be sent.

See also:

onResolvePointerIcon

Added in API level 24
PointerIcon onResolvePointerIcon (MotionEvent event, 
                int pointerIndex)

Returns the pointer icon for the motion event, or null if it doesn't specify the icon. The default implementation does not care the location or event types, but some subclasses may use it (such as WebViews).

Parameters
event MotionEvent: The MotionEvent from a mouse
pointerIndex int: The index of the pointer for which to retrieve the PointerIcon. This will be between 0 and getPointerCount().
Returns
PointerIcon

onStartNestedScroll

Added in API level 21
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 View: Direct child of this ViewParent containing target
target View: View that initiated the nested scroll
nestedScrollAxes int: Flags consisting of SCROLL_AXIS_HORIZONTAL, SCROLL_AXIS_VERTICAL or both
Returns
boolean true if this ViewParent accepts the nested scroll operation

onStopNestedScroll

Added in API level 21
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: View that initiated the nested scroll

onViewAdded

Added in API level 23
void onViewAdded (View child)

Called when a new child is added to this ViewGroup. Overrides should always call super.onViewAdded.

Parameters
child View: the added child view

onViewRemoved

Added in API level 23
void onViewRemoved (View child)

Called when a child view is removed from this ViewGroup. Overrides should always call super.onViewRemoved.

Parameters
child View: the removed child view

recomputeViewAttributes

Added in API level 1
void recomputeViewAttributes (View child)

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

Parameters
child View: View whose attributes have changed.

removeAllViews

Added in API level 1
void removeAllViews ()

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.

removeAllViewsInLayout

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

removeView

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

Parameters
view View

removeViewAt

Added in API level 1
void removeViewAt (int index)

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 int: the position in the group of the view to remove

removeViewInLayout

Added in API level 1
void removeViewInLayout (View view)

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 View: the view to remove from the group

removeViews

Added in API level 1
void removeViews (int start, 
                int count)

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 int: the first position in the group of the range of views to remove
count int: the number of views to remove

removeViewsInLayout

Added in API level 1
void removeViewsInLayout (int start, 
                int count)

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 int: the index of the first view to remove from the group
count int: the number of views to remove from the group

requestChildFocus

Added in API level 1
void requestChildFocus (View child, 
                View focused)

Called when a child of this parent wants focus

Parameters
child View: 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 View: The view that is a descendant of child that actually has focus

requestChildRectangleOnScreen

Added in API level 1
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. ViewGroups overriding this can trust that:

  • child will be a direct child of this group
  • rectangle will be in the child's content 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 View: The direct child making the request.
      rectangle Rect: The rectangle in the child's coordinates the child wishes to be on the screen.
      immediate boolean: True to forbid animated or delayed scrolling, false otherwise
      Returns
      boolean Whether the group scrolled to handle the operation

requestDisallowInterceptTouchEvent

Added in API level 1
void requestDisallowInterceptTouchEvent (boolean disallowIntercept)

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 boolean: True if the child does not want the parent to intercept touch events.

requestFocus

Added in API level 1
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. 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 int: One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRect Rect: 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
boolean Whether this view or one of its descendants actually took focus.

See also:

requestSendAccessibilityEvent

Added in API level 14
boolean requestSendAccessibilityEvent (View child, 
                AccessibilityEvent event)

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 View: The child which requests sending the event.
event AccessibilityEvent: The event to be sent.
Returns
boolean True if the event was sent.

requestTransparentRegion

Added in API level 1
void requestTransparentRegion (View child)

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 View: the view requesting the transparent region computation

scheduleLayoutAnimation

Added in API level 1
void scheduleLayoutAnimation ()

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.

setAddStatesFromChildren

Added in API level 1
void setAddStatesFromChildren (boolean addsStates)

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.

Parameters
addsStates boolean

setAlwaysDrawnWithCacheEnabled

Added in API level 1
void setAlwaysDrawnWithCacheEnabled (boolean always)

This method was deprecated in API level 23.
As of M, this property is ignored. Child views may no longer have their caching behavior disabled by parents.

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 boolean: true to always draw with the drawing cache, false otherwise

See also:

setAnimationCacheEnabled

Added in API level 1
void setAnimationCacheEnabled (boolean enabled)

This method was deprecated in API level 23.
As of M, this property is ignored. Caching behavior of children may be controlled through setLayerType(int, Paint).

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 boolean: true to enable the animation cache, false otherwise

See also:

setClipChildren

Added in API level 1
void setClipChildren (boolean clipChildren)

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 boolean: true to clip children to their bounds, false otherwise

setClipToPadding

Added in API level 1
void setClipToPadding (boolean clipToPadding)

Sets whether this ViewGroup will clip its children to its padding and resize (but not clip) any EdgeEffect to the padded region, if padding is present.

By default, children are clipped to the padding of their parent ViewGroup. This clipping behavior is only enabled if padding is non-zero.

Related XML Attributes:

Parameters
clipToPadding boolean: true to clip children to the padding of the group, and resize (but not clip) any EdgeEffect to the padded region. False otherwise.

setDescendantFocusability

Added in API level 1
void setDescendantFocusability (int focusability)

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

Parameters
focusability int: one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS.

setLayoutAnimation

Added in API level 1
void setLayoutAnimation (LayoutAnimationController controller)

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

Parameters
controller LayoutAnimationController: the animation controller

setLayoutAnimationListener

Added in API level 1
void setLayoutAnimationListener (Animation.AnimationListener animationListener)

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

Parameters
animationListener Animation.AnimationListener: the layout animation listener

setLayoutMode

Added in API level 18
void setLayoutMode (int layoutMode)

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 int: the layout mode to use during layout operations

See also:

setLayoutTransition

Added in API level 11
void setLayoutTransition (LayoutTransition transition)

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 LayoutTransition: The LayoutTransition object that will animated changes in layout. A value of null means no transition will run on layout changes.

setMotionEventSplittingEnabled

Added in API level 11
void setMotionEventSplittingEnabled (boolean split)

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

setOnHierarchyChangeListener

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

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

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

setPersistentDrawingCache

Added in API level 1
void setPersistentDrawingCache (int drawingCacheToKeep)

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

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

See also:

setTouchscreenBlocksFocus

Added in API level 21
void setTouchscreenBlocksFocus (boolean touchscreenBlocksFocus)

Set whether this ViewGroup should ignore focus requests for itself and its children. If this option is enabled and the ViewGroup or a descendant currently has focus, focus will proceed forward.

Parameters
touchscreenBlocksFocus boolean: true to enable blocking focus in the presence of a touchscreen

setTransitionGroup

Added in API level 21
void setTransitionGroup (boolean isTransitionGroup)

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

Parameters
isTransitionGroup boolean: 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.

See also:

shouldDelayChildPressedState

Added in API level 14
boolean shouldDelayChildPressedState ()

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.

Returns
boolean

showContextMenuForChild

Added in API level 24
boolean showContextMenuForChild (View originalView, 
                float x, 
                float y)

Shows the context menu for the specified view or its ancestors anchored to the specified view-relative coordinate.

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.

If a subclass overrides this method it should also override showContextMenuForChild(View).

Parameters
originalView View: the source view where the context menu was first invoked
x float: the X coordinate in pixels relative to the original view to which the menu should be anchored, or NaN to disable anchoring
y float: the Y coordinate in pixels relative to the original view to which the menu should be anchored, or NaN to disable anchoring
Returns
boolean true if the context menu was shown, false otherwise

showContextMenuForChild

Added in API level 1
boolean showContextMenuForChild (View originalView)

Shows the 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 View: the source view where the context menu was first invoked
Returns
boolean true if the context menu was shown, false otherwise

startActionModeForChild

Added in API level 23
ActionMode startActionModeForChild (View originalView, 
                ActionMode.Callback callback, 
                int type)

Start an action mode of a specific type 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 View: The source view where the action mode was first invoked
callback ActionMode.Callback: The callback that will handle lifecycle events for the action mode
type int: One of TYPE_PRIMARY or TYPE_FLOATING.
Returns
ActionMode The new action mode if it was started, null otherwise

startActionModeForChild

Added in API level 11
ActionMode startActionModeForChild (View originalView, 
                ActionMode.Callback callback)

Start an action mode for the specified view with the default type TYPE_PRIMARY.

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 View: The source view where the action mode was first invoked
callback ActionMode.Callback: The callback that will handle lifecycle events for the action mode
Returns
ActionMode The new action mode if it was started, null otherwise

startLayoutAnimation

Added in API level 1
void startLayoutAnimation ()

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

startViewTransition

Added in API level 11
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. 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 View: The View object to be kept visible even if it gets removed from its parent.

updateViewLayout

Added in API level 1
void updateViewLayout (View view, 
                ViewGroup.LayoutParams params)

Parameters
view View
params ViewGroup.LayoutParams

Protected methods

addViewInLayout

Added in API level 1
boolean addViewInLayout (View child, 
                int index, 
                ViewGroup.LayoutParams params, 
                boolean preventRequestLayout)

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 View: the view to add to the group
index int: the index at which the child must be added or -1 to add last
params ViewGroup.LayoutParams: the layout parameters to associate with the child
preventRequestLayout boolean: if true, calling this method will not trigger a layout request on child
Returns
boolean true if the child was added, false otherwise

addViewInLayout

Added in API level 1
boolean addViewInLayout (View child, 
                int index, 
                ViewGroup.LayoutParams params)

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 View: the view to add to the group
index int: the index at which the child must be added or -1 to add last
params ViewGroup.LayoutParams: the layout parameters to associate with the child
Returns
boolean true if the child was added, false otherwise

attachLayoutAnimationParameters

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

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

Parameters
child View: the child to associate with animation parameters
params ViewGroup.LayoutParams: the child's layout parameters which hold the animation parameters
index int: the index of the child in the view group
count int: the number of children in the view group

attachViewToParent

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

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 View: the child to attach
index int: the index at which the child should be attached
params ViewGroup.LayoutParams: the layout parameters of the child

See also:

canAnimate

Added in API level 1
boolean canAnimate ()

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

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

checkLayoutParams

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

Parameters
p ViewGroup.LayoutParams
Returns
boolean

cleanupLayoutState

Added in API level 1
void cleanupLayoutState (View child)

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

Parameters
child View: the child on which to perform the cleanup

debug

Added in API level 1
void debug (int depth)

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 int: the indentation level

detachAllViewsFromParent

Added in API level 1
void detachAllViewsFromParent ()

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

See also:

detachViewFromParent

Added in API level 1
void detachViewFromParent (int index)

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 int: the index of the child to detach

See also:

detachViewFromParent

Added in API level 1
void detachViewFromParent (View child)

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 View: the child to detach

See also:

detachViewsFromParent

Added in API level 1
void detachViewsFromParent (int start, 
                int count)

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 int: the first index of the childrend range to detach
count int: the number of children to detach

See also:

dispatchDraw

Added in API level 1
void dispatchDraw (Canvas canvas)

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 Canvas: the canvas on which to draw the view

dispatchFreezeSelfOnly

Added in API level 1
void dispatchFreezeSelfOnly (SparseArray<Parcelable> container)

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 SparseArray: the container

dispatchGenericFocusedEvent

Added in API level 14
boolean dispatchGenericFocusedEvent (MotionEvent event)

Dispatch a generic motion event to the currently focused view.

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

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

dispatchGenericPointerEvent

Added in API level 14
boolean dispatchGenericPointerEvent (MotionEvent event)

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

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

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

dispatchHoverEvent

Added in API level 14
boolean dispatchHoverEvent (MotionEvent event)

Dispatch a hover event.

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

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

dispatchRestoreInstanceState

Added in API level 1
void dispatchRestoreInstanceState (SparseArray<Parcelable> container)

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 SparseArray: The SparseArray which holds previously saved state.

dispatchSaveInstanceState

Added in API level 1
void dispatchSaveInstanceState (SparseArray<Parcelable> container)

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 SparseArray: The SparseArray in which to save the view's state.

dispatchSetPressed

Added in API level 1
void dispatchSetPressed (boolean pressed)

Dispatch setPressed to all of this View's children.

Parameters
pressed boolean: The new pressed state

dispatchThawSelfOnly

Added in API level 1
void dispatchThawSelfOnly (SparseArray<Parcelable> container)

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 SparseArray: the container

dispatchVisibilityChanged

Added in API level 8
void dispatchVisibilityChanged (View changedView, 
                int visibility)

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

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

drawChild

Added in API level 1
boolean drawChild (Canvas canvas, 
                View child, 
                long drawingTime)

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 Canvas: The canvas on which to draw the child
child View: Who to draw
drawingTime long: The time at which draw is occurring
Returns
boolean True if an invalidate() was issued

drawableStateChanged

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

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.

generateDefaultLayoutParams

Added in API level 1
ViewGroup.LayoutParams generateDefaultLayoutParams ()

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
ViewGroup.LayoutParams a set of default layout parameters or null

generateLayoutParams

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

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

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

getChildDrawingOrder

Added in API level 1
int getChildDrawingOrder (int childCount, 
                int i)

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
childCount int
i int: The current iteration.
Returns
int The index of the child to draw this iteration.

See also:

getChildStaticTransformation

Added in API level 1
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. 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 View: The child view whose static transform is being requested
t Transformation: The Transformation which will hold the result
Returns
boolean true if the transformation was set, false otherwise

See also:

isChildrenDrawingOrderEnabled

Added in API level 7
boolean isChildrenDrawingOrderEnabled ()

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

Returns
boolean true if children drawing order is defined by getChildDrawingOrder(int, int), false otherwise

See also:

isChildrenDrawnWithCacheEnabled

Added in API level 1
boolean isChildrenDrawnWithCacheEnabled ()

This method was deprecated in API level 23.
As of M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use setLayerType(int, Paint) on individual Views instead.

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

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

See also:

measureChild

Added in API level 1
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. The heavy lifting is done in getChildMeasureSpec.

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

measureChildWithMargins

Added in API level 1
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. The child must have MarginLayoutParams The heavy lifting is done in getChildMeasureSpec.

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

measureChildren

Added in API level 1
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. We skip children that are in the GONE state The heavy lifting is done in getChildMeasureSpec.

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

onAttachedToWindow

Added in API level 1
void onAttachedToWindow ()

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

onCreateDrawableState

Added in API level 1
int[] onCreateDrawableState (int extraSpace)

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 int: 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
int[] Returns an array holding the current Drawable state of the view.

onDetachedFromWindow

Added in API level 1
void onDetachedFromWindow ()

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

onLayout

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

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

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

onRequestFocusInDescendants

Added in API level 1
boolean onRequestFocusInDescendants (int direction, 
                Rect previouslyFocusedRect)

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 int: One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
previouslyFocusedRect Rect: 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
boolean Whether focus was taken.

removeDetachedView

Added in API level 1
void removeDetachedView (View child, 
                boolean animate)

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 View: the child to be definitely removed from the view hierarchy
animate boolean: if true and the view has an animation, the view is placed in the disappearing views list, otherwise, it is detached from the window

See also:

setChildrenDrawingCacheEnabled

Added in API level 1
void setChildrenDrawingCacheEnabled (boolean enabled)

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

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

setChildrenDrawingOrderEnabled

Added in API level 7
void setChildrenDrawingOrderEnabled (boolean enabled)

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

Note that Z reordering, done by dispatchDraw(Canvas), will override custom child ordering done via this method.

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

See also:

setChildrenDrawnWithCacheEnabled

Added in API level 1
void setChildrenDrawnWithCacheEnabled (boolean enabled)

This method was deprecated in API level 23.
As of M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use setLayerType(int, Paint) on individual Views instead.

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 boolean: true if children should be drawn with their cache, false otherwise

See also:

setStaticTransformationsEnabled

Added in API level 3
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. Any subclass overriding getChildStaticTransformation(View, android.view.animation.Transformation) should set this property to true.

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

See also:

Hooray!