ViewGroup


public abstract class ViewGroup
extends View implements ViewParent, ViewManager

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup


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

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

This constant was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int PERSISTENT_ANIMATION_CACHE

This constant was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int PERSISTENT_NO_CACHE

This constant was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

int PERSISTENT_SCROLLING_CACHE

This constant was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

Inherited constants

Inherited fields

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 addExtraDataToAccessibilityNodeInfo(AccessibilityNodeInfo info, String extraDataKey, Bundle arguments)

Adds extra data to an AccessibilityNodeInfo based on an explicit request for the additional data.

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.

void addKeyboardNavigationClusters(Collection<View> views, int direction)

Adds any keyboard navigation cluster roots that are descendants of this view (possibly including this view if it is a cluster root 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.

boolean dispatchCapturedPointerEvent(MotionEvent event)

Pass a captured pointer event down to the focused view.

void dispatchConfigurationChanged(Configuration newConfig)

Dispatch a notification about a resource configuration change down the view hierarchy.

void dispatchCreateViewTranslationRequest(Map<AutofillId, long[]> viewIds, int[] supportedFormats, TranslationCapability capability, List<ViewTranslationRequest> requests)

Dispatch to collect the ViewTranslationRequests for translation purpose by traversing the hierarchy when the app requests ui translation. The implementation calls dispatchCreateViewTranslationRequest(Map, int, TranslationCapability, List) for all the child views.

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 dispatchPointerCaptureChanged(boolean hasCapture)
void dispatchProvideAutofillStructure(ViewStructure structure, int flags)

Dispatches creation of a ViewStructures for autofill purposes down the hierarchy, when an Assist structure is being created as part of an autofill request.

This implementation adds in all child views of the view group, in addition to calling the default View implementation.

void dispatchProvideStructure(ViewStructure structure)

Dispatch creation of ViewStructure down the hierarchy.

void dispatchScrollCaptureSearch(Rect localVisibleRect, Point windowOffset, Consumer<ScrollCaptureTarget> targets)

Handle the scroll capture search request by checking this view if applicable, then to each child view.

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)

This method is deprecated. Use WindowInsets#isVisible(int) to find out about system bar visibilities by setting a OnApplyWindowInsetsListener on this view.

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 dispatchWindowInsetsAnimationEnd(WindowInsetsAnimation animation)

Dispatches WindowInsetsAnimation.Callback#onEnd(WindowInsetsAnimation) when Window Insets animation ends.

void dispatchWindowInsetsAnimationPrepare(WindowInsetsAnimation animation)

Dispatches WindowInsetsAnimation.Callback#onPrepare(WindowInsetsAnimation) when Window Insets animation is being prepared.

WindowInsets dispatchWindowInsetsAnimationProgress(WindowInsets insets, List<WindowInsetsAnimation> runningAnimations)

Dispatches WindowInsetsAnimation.Callback#onProgress(WindowInsets, List) when Window Insets animation makes progress.

WindowInsetsAnimation.Bounds dispatchWindowInsetsAnimationStart(WindowInsetsAnimation animation, WindowInsetsAnimation.Bounds bounds)

Dispatches WindowInsetsAnimation.Callback#onStart(WindowInsetsAnimation, Bounds) when Window Insets animation is started.

void dispatchWindowSystemUiVisiblityChanged(int visible)

This method is deprecated. SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

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(android.view.View).

View findFocus()

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

OnBackInvokedDispatcher findOnBackInvokedDispatcherForChild(View child, View requester)

Walk up the View hierarchy to find the nearest OnBackInvokedDispatcher.

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

final int getChildDrawingOrder(int drawingPosition)

Converts drawing order position to container position.

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

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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

This method is deprecated. Use onDescendantInvalidated(android.view.View, android.view.View) instead to observe updates to draw state in descendants.

ViewParent invalidateChildInParent(int[] location, Rect dirty)

This method is deprecated. Use onDescendantInvalidated(android.view.View, android.view.View) instead to observe updates to draw state in descendants.

boolean isAlwaysDrawnWithCacheEnabled()

This method was deprecated in API level 23. As of Build.VERSION_CODES.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 Build.VERSION_CODES.M, this property is ignored. Caching behavior of children may be controlled through View#setLayerType(int, Paint).

boolean isLayoutSuppressed()

Returns whether layout calls on this container are currently being suppressed, due to an earlier call to suppressLayout(boolean).

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.

void onDescendantInvalidated(View child, View target)

The target View has been invalidated, or has had a drawing property changed that requires the hierarchy to re-render. If you override this method you must call through to the superclass implementation.

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)

Resolve the pointer icon that should be used for specified pointer in the motion event.

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

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

void onStopNestedScroll(View child)

React to a nested scroll operation ending.

void 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 View.draw(android.graphics.Canvas), View.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 ViewGroup#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.

boolean restoreDefaultFocus()

Gives focus to the default-focus view in the view hierarchy that has this view as a root.

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 Build.VERSION_CODES.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 Build.VERSION_CODES.M, this property is ignored. Caching behavior of children may be controlled through View#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)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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.

void setWindowInsetsAnimationCallback(WindowInsetsAnimation.Callback callback)

Sets a WindowInsetsAnimation.Callback to be notified about animations of windows that cause insets.

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 ActionMode#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 suppressLayout(boolean suppress)

Tells this ViewGroup to suppress all layout() calls until layout suppression is disabled with a later call to suppressLayout(false).

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

Converts drawing order position to container position.

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 Build.VERSION_CODES.M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use View#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 View#requestFocus on.

void removeDetachedView(View child, boolean animate)

Finishes the removal of a detached view.

void setChildrenDrawingCacheEnabled(boolean enabled)

This method was deprecated in API level 28. The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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 Build.VERSION_CODES.M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use View#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(android.view.View, android.view.animation.Transformation) to be invoked when a child is drawn.

Inherited methods

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.

May be a boolean value, such as "true" or "false".

android:alwaysDrawnWithCache

Defines whether the ViewGroup should always draw its children using their drawing cache or not. The default value is true. Deprecated: The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11.

May be a boolean value, such as "true" or "false".

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.

May be a boolean value, such as "true" or "false".

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.

May be a boolean value, such as "true" or "false".

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.

May be a boolean value, such as "true" or "false".

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.

May be a boolean value, such as "true" or "false".

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
afterDescendants1The ViewGroup will get focus only if none of its descendants want it.
beforeDescendants0The ViewGroup will get focus before any of its descendants.
blocksDescendants2The ViewGroup will block its descendants from receiving focus.

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.

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

android:layoutMode

Defines the layout mode of this ViewGroup.

Must be one of the following constant values.

ConstantValueDescription
clipBounds0Use the children's clip bounds when laying out this container.
opticalBounds1Use the children's optical bounds when laying out this container.

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 if the cache is created over and over again. By default the persistence is set to scrolling. Deprecated: The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11.

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

ConstantValueDescription
all3The drawing cache is always persisted.
animation1The drawing cache is persisted after a layout animation.
none0The drawing cache is not persisted after use.
scrolling2The drawing cache is persisted after a scroll.

android:splitMotionEvents

Sets whether this ViewGroup should split MotionEvents to separate child views during touch event dispatch. If false (default prior to HONEYCOMB), touch events will be dispatched to the child view where the first pointer went down until the last pointer goes up. If true (default for HONEYCOMB and later), 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 ViewGroup.setMotionEventSplittingEnabled(boolean) for more information.

May be a boolean value, such as "true" or "false".

Related methods:

Constants

CLIP_TO_PADDING_MASK

Added in API level 1
protected static final 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
public static final 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
public static final 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
public static final 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
public static final 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
public static final 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
Deprecated in API level 28
public static final int PERSISTENT_ALL_CACHES

This constant was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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

Constant Value: 3 (0x00000003)

PERSISTENT_ANIMATION_CACHE

Added in API level 1
Deprecated in API level 28
public static final int PERSISTENT_ANIMATION_CACHE

This constant was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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
Deprecated in API level 28
public static final int PERSISTENT_NO_CACHE

This constant was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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

Constant Value: 0 (0x00000000)

PERSISTENT_SCROLLING_CACHE

Added in API level 1
Deprecated in API level 28
public static final int PERSISTENT_SCROLLING_CACHE

This constant was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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
public ViewGroup (Context context)

Parameters
context Context

ViewGroup

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

Parameters
context Context

attrs AttributeSet

ViewGroup

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

Parameters
context Context

attrs AttributeSet

defStyleAttr int

ViewGroup

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

addExtraDataToAccessibilityNodeInfo

Added in API level 26
public void addExtraDataToAccessibilityNodeInfo (AccessibilityNodeInfo info, 
                String extraDataKey, 
                Bundle arguments)

Adds extra data to an AccessibilityNodeInfo based on an explicit request for the additional data.

This method only needs overloading if the node is marked as having extra data available.

Parameters
info AccessibilityNodeInfo: The info to which to add the extra data. Never null.

extraDataKey String: A key specifying the type of extra data to add to the info. The extra data should be added to the Bundle returned by the info's AccessibilityNodeInfo#getExtras method. Never null.

arguments Bundle: A Bundle holding any arguments relevant for this request. May be null if the service provided no arguments.

addFocusables

Added in API level 4
public 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. Value is View.FOCUS_BACKWARD, View.FOCUS_FORWARD, View.FOCUS_LEFT, View.FOCUS_UP, View.FOCUS_RIGHT, or View.FOCUS_DOWN

focusableMode int: The type of focusables to be added. Value is either 0 or a combination of View.FOCUSABLES_ALL, and View.FOCUSABLES_TOUCH_MODE

addKeyboardNavigationClusters

Added in API level 26
public void addKeyboardNavigationClusters (Collection<View> views, 
                int direction)

Adds any keyboard navigation cluster roots that are descendants of this view (possibly including this view if it is a cluster root itself) to views.

Parameters
views Collection: Keyboard navigation cluster roots found so far This value cannot be null.

direction int: Direction to look

addStatesFromChildren

Added in API level 1
public 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
public 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
public void addView (View child, 
                ViewGroup.LayoutParams params)

Adds a child view with the specified layout parameters.

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

Parameters
child View: the child view to add

params ViewGroup.LayoutParams: the layout parameters to set on the child

addView

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

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

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

Parameters
child View: the child view to add

index int: the position at which to add the child

addView

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

Adds a child view with the specified layout parameters.

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

Parameters
child View: the child view to add

index int: the position at which to add the child or -1 to add last

params ViewGroup.LayoutParams: the layout parameters to set on the child

addView

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

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

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

Parameters
child View: the child view to add

addView

Added in API level 1
public void addView (View child, 
                int 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 View.draw(android.graphics.Canvas), View.onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

Parameters
child View: the child view to add

width int

height int

bringChildToFront

Added in API level 1
public 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 Build.VERSION_CODES.KITKAT this method should be followed by calls to requestLayout() and View#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
public 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. This value cannot be null.

childHasTransientStateChanged

Added in API level 19
public 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 This value cannot be null.

childHasTransientState boolean: true if this child has transient state

clearChildFocus

Added in API level 1
public 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
public 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
public 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 not in touch-mode, the framework will try to give focus to the first focusable View from the top after focus is cleared. 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
public WindowInsets dispatchApplyWindowInsets (WindowInsets insets)

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

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

Clients wishing to provide custom behavior should override the onApplyWindowInsets(android.view.WindowInsets) method or alternatively provide a 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

dispatchCapturedPointerEvent

Added in API level 26
public boolean dispatchCapturedPointerEvent (MotionEvent event)

Pass a captured pointer 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.

dispatchConfigurationChanged

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

dispatchCreateViewTranslationRequest

Added in API level 31
public void dispatchCreateViewTranslationRequest (Map<AutofillId, long[]> viewIds, 
                int[] supportedFormats, 
                TranslationCapability capability, 
                List<ViewTranslationRequest> requests)

Dispatch to collect the ViewTranslationRequests for translation purpose by traversing the hierarchy when the app requests ui translation. Typically, this method should only be overridden by subclasses that provide a view hierarchy (such as ViewGroup). Other classes should override View#onCreateViewTranslationRequest for normal view or override View#onVirtualViewTranslationResponses for view contains virtual children. When requested to start the ui translation, the system will call this method to traverse the view hierarchy to collect ViewTranslationRequests and create a Translator to translate the requests. All the ViewTranslationRequests must be added when the traversal is done.

The default implementation calls View#onCreateViewTranslationRequest for normal view or calls View#onVirtualViewTranslationResponses for view contains virtual children to build ViewTranslationRequest if the view should be translated. The view is marked as having transient state so that recycling of views doesn't prevent the system from attaching the response to it. Therefore, if overriding this method, you should set or reset the transient state.

The implementation calls dispatchCreateViewTranslationRequest(Map, int, TranslationCapability, List) for all the child views.

Parameters
viewIds Map: This value cannot be null.

supportedFormats int: This value cannot be null. Value is TranslationSpec.DATA_FORMAT_TEXT

capability TranslationCapability: This value may be null.

requests List: This value cannot be null.

dispatchDisplayHint

Added in API level 8
public 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: View.VISIBLE or View.INVISIBLE. Value is View.VISIBLE, View.INVISIBLE, or View.GONE

dispatchDragEvent

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

dispatchKeyEvent

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

dispatchPointerCaptureChanged

Added in API level 26
public void dispatchPointerCaptureChanged (boolean hasCapture)

Parameters
hasCapture boolean

dispatchProvideAutofillStructure

Added in API level 26
public void dispatchProvideAutofillStructure (ViewStructure structure, 
                int flags)

Dispatches creation of a ViewStructures for autofill purposes down the hierarchy, when an Assist structure is being created as part of an autofill request.

The default implementation does the following:

Typically, this method should only be overridden by subclasses that provide a view hierarchy (such as ViewGroup) - other classes should override onProvideAutofillStructure(android.view.ViewStructure, int) or onProvideAutofillVirtualStructure(android.view.ViewStructure, int) instead.

When overridden, it must:

  • Either call super.dispatchProvideAutofillStructure(structure, flags) or explicitly set the AutofillId in the structure (for example, by calling structure.setAutofillId(getAutofillId())).
  • Decide how to handle the AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS flag - when set, all views in the structure should be considered important for autofill, regardless of what isImportantForAutofill() returns. We encourage you to respect this flag to provide a better user experience - this flag is typically used when an user explicitly requested autofill. If the flag is not set, then only views marked as important for autofill should be included in the structure - skipping non-important views optimizes the overall autofill performance.

This implementation adds in all child views of the view group, in addition to calling the default View implementation.

Parameters
structure ViewStructure: fill in with structured view data for autofill purposes. This value cannot be null.

flags int: Value is either 0 or View.AUTOFILL_FLAG_INCLUDE_NOT_IMPORTANT_VIEWS

dispatchProvideStructure

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

dispatchScrollCaptureSearch

Added in API level 31
public void dispatchScrollCaptureSearch (Rect localVisibleRect, 
                Point windowOffset, 
                Consumer<ScrollCaptureTarget> targets)

Handle the scroll capture search request by checking this view if applicable, then to each child view.

Parameters
localVisibleRect Rect: the visible area of this ViewGroup in local coordinates, according to the parent This value cannot be null.

windowOffset Point: the offset of this view within the window This value cannot be null.

targets Consumer: accepts potential scroll capture targets; results.accept may be called zero or more times on the calling thread before onScrollCaptureSearch returns This value cannot be null.

dispatchSetActivated

Added in API level 11
public 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
public 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
public void dispatchSystemUiVisibilityChanged (int visible)

This method is deprecated.
Use WindowInsets#isVisible(int) to find out about system bar visibilities by setting a OnApplyWindowInsetsListener on this view.

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

Parameters
visible int

dispatchTouchEvent

Added in API level 1
public 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
public 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
public 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. Value is View.FOCUS_LEFT, View.FOCUS_UP, View.FOCUS_RIGHT, or View.FOCUS_DOWN

Returns
boolean True if the this view consumed this unhandled move.

dispatchWindowFocusChanged

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

dispatchWindowInsetsAnimationEnd

Added in API level 30
public void dispatchWindowInsetsAnimationEnd (WindowInsetsAnimation animation)

Dispatches WindowInsetsAnimation.Callback#onEnd(WindowInsetsAnimation) when Window Insets animation ends.

Parameters
animation WindowInsetsAnimation: This value cannot be null.

dispatchWindowInsetsAnimationPrepare

Added in API level 30
public void dispatchWindowInsetsAnimationPrepare (WindowInsetsAnimation animation)

Dispatches WindowInsetsAnimation.Callback#onPrepare(WindowInsetsAnimation) when Window Insets animation is being prepared.

Parameters
animation WindowInsetsAnimation: This value cannot be null.

dispatchWindowInsetsAnimationProgress

Added in API level 30
public WindowInsets dispatchWindowInsetsAnimationProgress (WindowInsets insets, 
                List<WindowInsetsAnimation> runningAnimations)

Dispatches WindowInsetsAnimation.Callback#onProgress(WindowInsets, List) when Window Insets animation makes progress.

Parameters
insets WindowInsets: This value cannot be null.

runningAnimations List: This value cannot be null.

Returns
WindowInsets This value cannot be null.

dispatchWindowInsetsAnimationStart

Added in API level 30
public WindowInsetsAnimation.Bounds dispatchWindowInsetsAnimationStart (WindowInsetsAnimation animation, 
                WindowInsetsAnimation.Bounds bounds)

Dispatches WindowInsetsAnimation.Callback#onStart(WindowInsetsAnimation, Bounds) when Window Insets animation is started.

Parameters
animation WindowInsetsAnimation: This value cannot be null.

bounds WindowInsetsAnimation.Bounds: This value cannot be null.

Returns
WindowInsetsAnimation.Bounds This value cannot be null.

dispatchWindowSystemUiVisiblityChanged

Added in API level 16
public void dispatchWindowSystemUiVisiblityChanged (int visible)

This method is deprecated.
SystemUiVisibility flags are deprecated. Use WindowInsetsController instead.

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

Parameters
visible int

dispatchWindowVisibilityChanged

Added in API level 1
public 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. Value is View.VISIBLE, View.INVISIBLE, or View.GONE

endViewTransition

Added in API level 11
public void endViewTransition (View view)

This method should always be called following an earlier call to startViewTransition(android.view.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(android.view.View).

findFocus

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

findOnBackInvokedDispatcherForChild

Added in API level 33
public OnBackInvokedDispatcher findOnBackInvokedDispatcherForChild (View child, 
                View requester)

Walk up the View hierarchy to find the nearest OnBackInvokedDispatcher.

Parameters
child View: The direct child of this view for which to find a dispatcher. This value cannot be null.

requester View: The requester that will use the dispatcher. Can be the same as child. This value cannot be null.

Returns
OnBackInvokedDispatcher The OnBackInvokedDispatcher from this or the nearest ancestor, or null if the view is both not attached and have no ancestor providing an OnBackInvokedDispatcher.

findViewsWithText

Added in API level 14
public 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: Value is either 0 or a combination of View.FIND_VIEWS_WITH_TEXT, and View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION

focusSearch

Added in API level 1
public 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
public 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
public boolean gatherTransparentRegion (Region region)

This is used by the ViewRoot 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). This value may be null.

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
public 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
public CharSequence getAccessibilityClassName ()

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

Returns
CharSequence

getChildAt

Added in API level 1
public 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
public int getChildCount ()

Returns the number of children in the group.

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

getChildDrawingOrder

Added in API level 29
public final int getChildDrawingOrder (int drawingPosition)

Converts drawing order position to container position.

Children are not necessarily drawn in the order in which they appear in the container. ViewGroups can enable a custom ordering via setChildrenDrawingOrderEnabled(boolean). This method returns the container position of a child that appears in the given position in the current drawing order.

Parameters
drawingPosition int: the drawing order position.

Returns
int the container position of a child for this drawing order position.

getChildMeasureSpec

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

getClipToPadding

Added in API level 21
public 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
public 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
public 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
public 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
public 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
public 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
public 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
public int getNestedScrollAxes ()

Return the current axes of nested scrolling for this ViewGroup.

A ViewGroup returning something other than View.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

getOverlay

Added in API level 18
public 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
Deprecated in API level 28
public int getPersistentDrawingCache ()

This method was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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

getTouchscreenBlocksFocus

Added in API level 21
public boolean getTouchscreenBlocksFocus ()

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

Returns
boolean

hasFocus

Added in API level 1
public boolean hasFocus ()

Returns true if this view has or contains focus

Returns
boolean true if this view has or contains focus

hasTransientState

Added in API level 16
public 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
public 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
public final void invalidateChild (View child, 
                Rect dirty)

This method is deprecated.
Use onDescendantInvalidated(android.view.View, android.view.View) instead to observe updates to draw state in descendants.

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
public ViewParent invalidateChildInParent (int[] location, 
                Rect dirty)

This method is deprecated.
Use onDescendantInvalidated(android.view.View, android.view.View) instead to observe updates to draw state in descendants.

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
Deprecated in API level 23
public boolean isAlwaysDrawnWithCacheEnabled ()

This method was deprecated in API level 23.
As of Build.VERSION_CODES.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

isAnimationCacheEnabled

Added in API level 1
Deprecated in API level 23
public boolean isAnimationCacheEnabled ()

This method was deprecated in API level 23.
As of Build.VERSION_CODES.M, this property is ignored. Caching behavior of children may be controlled through View#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

isLayoutSuppressed

Added in API level 29
public boolean isLayoutSuppressed ()

Returns whether layout calls on this container are currently being suppressed, due to an earlier call to suppressLayout(boolean).

Returns
boolean true if layout calls are currently suppressed, false otherwise.

isMotionEventSplittingEnabled

Added in API level 11
public 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
public boolean isTransitionGroup ()

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

Returns
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 View.getTransitionName() is not null or if a non-null ViewOutlineProvider other than ViewOutlineProvider.BACKGROUND was given to View.setOutlineProvider(android.view.ViewOutlineProvider) and false otherwise.

jumpDrawablesToCurrentState

Added in API level 11
public void jumpDrawablesToCurrentState ()

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

Also calls StateListAnimator#jumpToCurrentState() if there is a StateListAnimator attached to this view.
If you override this method you must call through to the superclass implementation.

layout

Added in API level 1
public 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. (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
public 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. This value cannot be null.

source View: The descendant view that changed. May not be null.

changeType int: A bit mask of the types of changes that occurred. One or more of:

offsetDescendantRectToMyCoords

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

onDescendantInvalidated

Added in API level 26
public void onDescendantInvalidated (View child, 
                View target)

The target View has been invalidated, or has had a drawing property changed that requires the hierarchy to re-render. This method is called by the View hierarchy to signal ancestors that a View either needs to re-record its drawing commands, or drawing properties have changed. This is how Views schedule a drawing traversal. This signal is generally only dispatched for attached Views, since only they need to draw. If you override this method you must call through to the superclass implementation.

Parameters
child View: This value cannot be null.

target View: This value cannot be null.

onInterceptHoverEvent

Added in API level 14
public 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 View.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 View.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 View.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
public 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 MotionEvent#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

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

Request a fling from a nested scroll.

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

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

Parameters
target View: View that initiated the nested scroll This value cannot be null.

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

public 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 This value cannot be null.

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

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

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

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

onNestedPreScroll is called when a nested scrolling child invokes View#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 This value cannot be null.

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 This value cannot be null.

onNestedScroll

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

React to a nested scroll in progress.

This method will be called when the ViewParent's current nested scrolling child view dispatches a nested scroll event. To receive calls to this method the ViewParent must have previously returned true for a call to onStartNestedScroll(android.view.View, android.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 This value cannot be null.

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

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

React to the successful claiming of a nested scroll operation.

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

Parameters
child View: Direct child of this ViewParent containing target This value cannot be null.

target View: View that initiated the nested scroll This value cannot be null.

axes int: Flags consisting of View#SCROLL_AXIS_HORIZONTAL, View#SCROLL_AXIS_VERTICAL or both

onRequestSendAccessibilityEvent

Added in API level 14
public 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 View.setAccessibilityDelegate(android.view.View.AccessibilityDelegate) its View.AccessibilityDelegate.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.

onResolvePointerIcon

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

Resolve the pointer icon that should be used for specified pointer in the motion event. The default implementation will resolve the pointer icon to one set using setPointerIcon(android.view.PointerIcon) for mouse devices. Subclasses may override this to customize the icon for the given pointer. For example, the pointer icon for a stylus pointer can be resolved in the following way:

 @Override
 public PointerIcon onResolvePointerIcon(MotionEvent event, int pointerIndex) {
     final int toolType = event.getToolType(pointerIndex);
     if (!event.isFromSource(InputDevice.SOURCE_MOUSE)
             && event.isFromSource(InputDevice.SOURCE_STYLUS)
             && (toolType == MotionEvent.TOOL_TYPE_STYLUS
                     || toolType == MotionEvent.TOOL_TYPE_ERASER)) {
         // Show this pointer icon only if this pointer is a stylus.
         return PointerIcon.getSystemIcon(mContext, PointerIcon.TYPE_WAIT);
     }
     // Use the default logic for determining the pointer icon for other non-stylus pointers,
     // like for the mouse cursor.
     return super.onResolvePointerIcon(event, pointerIndex);
 }
 

Parameters
event MotionEvent: The MotionEvent that requires a pointer icon to be resolved for one of pointers.

pointerIndex int: The index of the pointer in event for which to retrieve the PointerIcon. This will be between 0 and MotionEvent#getPointerCount().

Returns
PointerIcon the pointer icon to use for specified pointer, or null if a pointer icon is not specified and the default icon should be used.

onStartNestedScroll

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

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

This method will be called in response to a descendant view invoking View#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(android.view.View).

Parameters
child View: Direct child of this ViewParent containing target This value cannot be null.

target View: View that initiated the nested scroll This value cannot be null.

nestedScrollAxes int: Flags consisting of View#SCROLL_AXIS_HORIZONTAL, View#SCROLL_AXIS_VERTICAL or both

Returns
boolean true if this ViewParent accepts the nested scroll operation

onStopNestedScroll

public void onStopNestedScroll (View child)

React to a nested scroll operation ending.

Perform cleanup after a nested scrolling operation. This method will be called when a nested scroll stops, for example when a nested touch scroll ends with a MotionEvent#ACTION_UP or MotionEvent#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 This value cannot be null.

onViewAdded

Added in API level 23
public 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
public 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
public 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
public void removeAllViews ()

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

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

removeAllViewsInLayout

Added in API level 1
public 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 View.draw(android.graphics.Canvas), View.onDraw(android.graphics.Canvas), dispatchDraw(android.graphics.Canvas) or any related method.

removeView

Added in API level 1
public void removeView (View view)

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

Parameters
view View

removeViewAt

Added in API level 1
public void removeViewAt (int index)

Removes the view at the specified position in the group.

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

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

removeViewInLayout

Added in API level 1
public 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 View.draw(android.graphics.Canvas), View.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
public void removeViews (int start, 
                int count)

Removes the specified range of views from the group.

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

Parameters
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
public 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 View.draw(android.graphics.Canvas), View.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
public 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
public 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. This value cannot be null.

      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
public void requestDisallowInterceptTouchEvent (boolean disallowIntercept)

Called when a child does not want this parent and its ancestors to intercept touch events with ViewGroup#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
public 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 ViewGroup.getDescendantFocusability() equal to ViewGroup#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.

requestSendAccessibilityEvent

Added in API level 14
public 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. This value cannot be null.

event AccessibilityEvent: The event to be sent.

Returns
boolean True if the event was sent.

requestTransparentRegion

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

restoreDefaultFocus

Added in API level 26
public boolean restoreDefaultFocus ()

Gives focus to the default-focus view in the view hierarchy that has this view as a root. If the default-focus view cannot be found, falls back to calling requestFocus(int).

Returns
boolean Whether this view or one of its descendants actually took focus

scheduleLayoutAnimation

Added in API level 1
public 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
public 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
Deprecated in API level 23
public void setAlwaysDrawnWithCacheEnabled (boolean always)

This method was deprecated in API level 23.
As of Build.VERSION_CODES.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

setAnimationCacheEnabled

Added in API level 1
Deprecated in API level 23
public void setAnimationCacheEnabled (boolean enabled)

This method was deprecated in API level 23.
As of Build.VERSION_CODES.M, this property is ignored. Caching behavior of children may be controlled through View#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

setClipChildren

Added in API level 1
public 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
public 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
public 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
public 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
public void setLayoutAnimationListener (Animation.AnimationListener animationListener)

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

Parameters
animationListener Animation.AnimationListener: the layout animation listener

setLayoutMode

Added in API level 18
public 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
public 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
public 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 Build.VERSION_CODES#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
public void setOnHierarchyChangeListener (ViewGroup.OnHierarchyChangeListener listener)

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

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

setPersistentDrawingCache

Added in API level 1
Deprecated in API level 28
public void setPersistentDrawingCache (int drawingCacheToKeep)

This method was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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

setTouchscreenBlocksFocus

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

setWindowInsetsAnimationCallback

Added in API level 30
public void setWindowInsetsAnimationCallback (WindowInsetsAnimation.Callback callback)

Sets a WindowInsetsAnimation.Callback to be notified about animations of windows that cause insets.

The callback's dispatch mode will affect whether animation callbacks are dispatched to the children of this view.

Parameters
callback WindowInsetsAnimation.Callback: This value may be null.

shouldDelayChildPressedState

Added in API level 14
public 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
public 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, ViewManager#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(android.view.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 Float#NaN to disable anchoring

y float: the Y coordinate in pixels relative to the original view to which the menu should be anchored, or Float#NaN to disable anchoring

Returns
boolean true if the context menu was shown, false otherwise

showContextMenuForChild

Added in API level 1
public 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, ViewManager#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
public 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, ViewManager#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 ActionMode#TYPE_PRIMARY or ActionMode#TYPE_FLOATING.

Returns
ActionMode The new action mode if it was started, null otherwise

startActionModeForChild

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

Start an action mode for the specified view with the default type ActionMode#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, ViewManager#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
public void startLayoutAnimation ()

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

startViewTransition

Added in API level 11
public 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(android.view.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.

suppressLayout

Added in API level 29
public void suppressLayout (boolean suppress)

Tells this ViewGroup to suppress all layout() calls until layout suppression is disabled with a later call to suppressLayout(false). When layout suppression is disabled, a requestLayout() call is sent if layout() was attempted while layout was being suppressed.

Parameters
suppress boolean

updateViewLayout

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

Parameters
view View

params ViewGroup.LayoutParams

Protected methods

addViewInLayout

Added in API level 1
protected 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
protected 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
protected void attachLayoutAnimationParameters (View child, 
                ViewGroup.LayoutParams params, 
                int index, 
                int count)

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

Parameters
child View: the child to associate with animation parameters

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

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

count int: the number of children in the view group

attachViewToParent

Added in API level 1
protected 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 View.requestLayout() or View.invalidate() calls. For example, callers can post a Runnable which performs a View.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

canAnimate

Added in API level 1
protected 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
protected boolean checkLayoutParams (ViewGroup.LayoutParams p)

Parameters
p ViewGroup.LayoutParams

Returns
boolean

cleanupLayoutState

Added in API level 1
protected 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
protected void debug (int depth)

Parameters
depth int

detachAllViewsFromParent

Added in API level 1
protected void detachAllViewsFromParent ()

Detaches all views from the parent. Detaching a view should be followed either by a call to attachViewToParent(android.view.View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(android.view.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).

detachViewFromParent

Added in API level 1
protected void detachViewFromParent (int index)

Detaches a view from its parent. Detaching a view should be followed either by a call to attachViewToParent(android.view.View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(android.view.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

detachViewFromParent

Added in API level 1
protected void detachViewFromParent (View child)

Detaches a view from its parent. Detaching a view should be followed either by a call to attachViewToParent(android.view.View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(android.view.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

detachViewsFromParent

Added in API level 1
protected 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(android.view.View, int, android.view.ViewGroup.LayoutParams) or a call to removeDetachedView(android.view.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

dispatchDraw

Added in API level 1
protected 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: This value cannot be null.

dispatchFreezeSelfOnly

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

Perform dispatching of a View.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
protected boolean dispatchGenericFocusedEvent (MotionEvent event)

Dispatch a generic motion event to the currently focused view.

Do not call this method directly. Call dispatchGenericMotionEvent(android.view.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
protected boolean dispatchGenericPointerEvent (MotionEvent event)

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

Do not call this method directly. Call dispatchGenericMotionEvent(android.view.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
protected boolean dispatchHoverEvent (MotionEvent event)

Dispatch a hover event.

Do not call this method directly. Call dispatchGenericMotionEvent(android.view.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
protected 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
protected 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
protected 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
protected void dispatchThawSelfOnly (SparseArray<Parcelable> container)

Perform dispatching of a View.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
protected 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. This value cannot be null.

visibility int: The new visibility of changedView: View.VISIBLE, View.INVISIBLE or View.GONE. Value is View.VISIBLE, View.INVISIBLE, or View.GONE

drawChild

Added in API level 1
protected 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 This value cannot be null.

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

generateDefaultLayoutParams

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

Returns a set of default layout parameters. These parameters are requested when the View passed to addView(android.view.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
protected 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
protected int getChildDrawingOrder (int childCount, 
                int drawingPosition)

Converts drawing order position to container position. Override this if you want to change the drawing order of children. By default, it returns drawingPosition.

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

Parameters
childCount int

drawingPosition int: the drawing order position.

Returns
int the container position of a child for this drawing order position.

getChildStaticTransformation

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

isChildrenDrawingOrderEnabled

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

isChildrenDrawnWithCacheEnabled

Added in API level 1
Deprecated in API level 23
protected boolean isChildrenDrawnWithCacheEnabled ()

This method was deprecated in API level 23.
As of Build.VERSION_CODES.M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use View#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

measureChild

Added in API level 1
protected 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
protected 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
protected 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
protected 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).
If you override this method you must call through to the superclass implementation.

onCreateDrawableState

Added in API level 1
protected 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
protected void onDetachedFromWindow ()

This is called when the view is detached from a window. At this point it no longer has a surface for drawing.
If you override this method you must call through to the superclass implementation.

onLayout

Added in API level 1
protected 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. 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
protected boolean onRequestFocusInDescendants (int direction, 
                Rect previouslyFocusedRect)

Look for a descendant to call View#requestFocus on. Called by ViewGroup#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
protected 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 View.requestLayout() or View.invalidate() calls. For example, callers can post a Runnable which performs a View.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

setChildrenDrawingCacheEnabled

Added in API level 1
Deprecated in API level 28
protected void setChildrenDrawingCacheEnabled (boolean enabled)

This method was deprecated in API level 28.
The view drawing cache was largely made obsolete with the introduction of hardware-accelerated rendering in API 11. With hardware-acceleration, intermediate cache layers are largely unnecessary and can easily result in a net loss in performance due to the cost of creating and updating the layer. In the rare cases where caching layers are useful, such as for alpha animations, View.setLayerType(int, android.graphics.Paint) handles this with hardware rendering. For software-rendered snapshots of a small part of the View hierarchy or individual Views it is recommended to create a Canvas from either a Bitmap or Picture and call View.draw(android.graphics.Canvas) on the View. However these software-rendered usages are discouraged and have compatibility issues with hardware-only rendering features such as Config.HARDWARE bitmaps, real-time shadows, and outline clipping. For screenshots of the UI for feedback reports or unit testing the PixelCopy API is recommended.

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
protected 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(android.graphics.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

setChildrenDrawnWithCacheEnabled

Added in API level 1
Deprecated in API level 23
protected void setChildrenDrawnWithCacheEnabled (boolean enabled)

This method was deprecated in API level 23.
As of Build.VERSION_CODES.M, this property is ignored. Child views may no longer be forced to cache their rendering state by their parents. Use View#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

setStaticTransformationsEnabled

Added in API level 3
protected void setStaticTransformationsEnabled (boolean enabled)

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

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