ViewGroup.java revision 57c79c8a4988e236b223502258a799e8b0ea4ca0
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.view;
18
19import android.animation.LayoutTransition;
20import android.content.Context;
21import android.content.pm.PackageManager;
22import android.content.res.Configuration;
23import android.content.res.TypedArray;
24import android.graphics.Bitmap;
25import android.graphics.Canvas;
26import android.graphics.Color;
27import android.graphics.Insets;
28import android.graphics.Matrix;
29import android.graphics.Paint;
30import android.graphics.PointF;
31import android.graphics.Rect;
32import android.graphics.RectF;
33import android.graphics.Region;
34import android.os.Build;
35import android.os.Parcelable;
36import android.os.SystemClock;
37import android.util.AttributeSet;
38import android.util.Log;
39import android.util.Pools.SynchronizedPool;
40import android.util.SparseArray;
41import android.view.accessibility.AccessibilityEvent;
42import android.view.accessibility.AccessibilityNodeInfo;
43import android.view.animation.Animation;
44import android.view.animation.AnimationUtils;
45import android.view.animation.LayoutAnimationController;
46import android.view.animation.Transformation;
47
48import com.android.internal.R;
49import com.android.internal.util.Predicate;
50
51import java.util.ArrayList;
52import java.util.Collections;
53import java.util.HashSet;
54import java.util.List;
55import java.util.Map;
56
57import static android.os.Build.VERSION_CODES.JELLY_BEAN_MR1;
58
59/**
60 * <p>
61 * A <code>ViewGroup</code> is a special view that can contain other views
62 * (called children.) The view group is the base class for layouts and views
63 * containers. This class also defines the
64 * {@link android.view.ViewGroup.LayoutParams} class which serves as the base
65 * class for layouts parameters.
66 * </p>
67 *
68 * <p>
69 * Also see {@link LayoutParams} for layout attributes.
70 * </p>
71 *
72 * <div class="special reference">
73 * <h3>Developer Guides</h3>
74 * <p>For more information about creating user interface layouts, read the
75 * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer
76 * guide.</p></div>
77 *
78 * <p>Here is a complete implementation of a custom ViewGroup that implements
79 * a simple {@link android.widget.FrameLayout} along with the ability to stack
80 * children in left and right gutters.</p>
81 *
82 * {@sample development/samples/ApiDemos/src/com/example/android/apis/view/CustomLayout.java
83 *      Complete}
84 *
85 * <p>If you are implementing XML layout attributes as shown in the example, this is the
86 * corresponding definition for them that would go in <code>res/values/attrs.xml</code>:</p>
87 *
88 * {@sample development/samples/ApiDemos/res/values/attrs.xml CustomLayout}
89 *
90 * <p>Finally the layout manager can be used in an XML layout like so:</p>
91 *
92 * {@sample development/samples/ApiDemos/res/layout/custom_layout.xml Complete}
93 *
94 * @attr ref android.R.styleable#ViewGroup_clipChildren
95 * @attr ref android.R.styleable#ViewGroup_clipToPadding
96 * @attr ref android.R.styleable#ViewGroup_layoutAnimation
97 * @attr ref android.R.styleable#ViewGroup_animationCache
98 * @attr ref android.R.styleable#ViewGroup_persistentDrawingCache
99 * @attr ref android.R.styleable#ViewGroup_alwaysDrawnWithCache
100 * @attr ref android.R.styleable#ViewGroup_addStatesFromChildren
101 * @attr ref android.R.styleable#ViewGroup_descendantFocusability
102 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
103 * @attr ref android.R.styleable#ViewGroup_splitMotionEvents
104 * @attr ref android.R.styleable#ViewGroup_layoutMode
105 */
106public abstract class ViewGroup extends View implements ViewParent, ViewManager {
107    private static final String TAG = "ViewGroup";
108
109    private static final boolean DBG = false;
110    /** @hide */
111    public static boolean DEBUG_DRAW = false;
112
113    /**
114     * Views which have been hidden or removed which need to be animated on
115     * their way out.
116     * This field should be made private, so it is hidden from the SDK.
117     * {@hide}
118     */
119    protected ArrayList<View> mDisappearingChildren;
120
121    /**
122     * Listener used to propagate events indicating when children are added
123     * and/or removed from a view group.
124     * This field should be made private, so it is hidden from the SDK.
125     * {@hide}
126     */
127    protected OnHierarchyChangeListener mOnHierarchyChangeListener;
128
129    // The view contained within this ViewGroup that has or contains focus.
130    private View mFocused;
131
132    /**
133     * A Transformation used when drawing children, to
134     * apply on the child being drawn.
135     */
136    private Transformation mChildTransformation;
137
138    /**
139     * Used to track the current invalidation region.
140     */
141    RectF mInvalidateRegion;
142
143    /**
144     * A Transformation used to calculate a correct
145     * invalidation area when the application is autoscaled.
146     */
147    Transformation mInvalidationTransformation;
148
149    // View currently under an ongoing drag
150    private View mCurrentDragView;
151
152    // Metadata about the ongoing drag
153    private DragEvent mCurrentDrag;
154    private HashSet<View> mDragNotifiedChildren;
155
156    // Does this group have a child that can accept the current drag payload?
157    private boolean mChildAcceptsDrag;
158
159    // Used during drag dispatch
160    private PointF mLocalPoint;
161
162    // Layout animation
163    private LayoutAnimationController mLayoutAnimationController;
164    private Animation.AnimationListener mAnimationListener;
165
166    // First touch target in the linked list of touch targets.
167    private TouchTarget mFirstTouchTarget;
168
169    // For debugging only.  You can see these in hierarchyviewer.
170    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
171    @ViewDebug.ExportedProperty(category = "events")
172    private long mLastTouchDownTime;
173    @ViewDebug.ExportedProperty(category = "events")
174    private int mLastTouchDownIndex = -1;
175    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
176    @ViewDebug.ExportedProperty(category = "events")
177    private float mLastTouchDownX;
178    @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
179    @ViewDebug.ExportedProperty(category = "events")
180    private float mLastTouchDownY;
181
182    // First hover target in the linked list of hover targets.
183    // The hover targets are children which have received ACTION_HOVER_ENTER.
184    // They might not have actually handled the hover event, but we will
185    // continue sending hover events to them as long as the pointer remains over
186    // their bounds and the view group does not intercept hover.
187    private HoverTarget mFirstHoverTarget;
188
189    // True if the view group itself received a hover event.
190    // It might not have actually handled the hover event.
191    private boolean mHoveredSelf;
192
193    /**
194     * Internal flags.
195     *
196     * This field should be made private, so it is hidden from the SDK.
197     * {@hide}
198     */
199    @ViewDebug.ExportedProperty(flagMapping = {
200            @ViewDebug.FlagToString(mask = FLAG_CLIP_CHILDREN, equals = FLAG_CLIP_CHILDREN,
201                    name = "CLIP_CHILDREN"),
202            @ViewDebug.FlagToString(mask = FLAG_CLIP_TO_PADDING, equals = FLAG_CLIP_TO_PADDING,
203                    name = "CLIP_TO_PADDING"),
204            @ViewDebug.FlagToString(mask = FLAG_PADDING_NOT_NULL, equals = FLAG_PADDING_NOT_NULL,
205                    name = "PADDING_NOT_NULL")
206    }, formatToHexString = true)
207    protected int mGroupFlags;
208
209    /**
210     * Either {@link #LAYOUT_MODE_CLIP_BOUNDS} or {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
211     */
212    private int mLayoutMode = LAYOUT_MODE_UNDEFINED;
213
214    /**
215     * NOTE: If you change the flags below make sure to reflect the changes
216     *       the DisplayList class
217     */
218
219    // When set, ViewGroup invalidates only the child's rectangle
220    // Set by default
221    static final int FLAG_CLIP_CHILDREN = 0x1;
222
223    // When set, ViewGroup excludes the padding area from the invalidate rectangle
224    // Set by default
225    private static final int FLAG_CLIP_TO_PADDING = 0x2;
226
227    // When set, dispatchDraw() will invoke invalidate(); this is set by drawChild() when
228    // a child needs to be invalidated and FLAG_OPTIMIZE_INVALIDATE is set
229    static final int FLAG_INVALIDATE_REQUIRED  = 0x4;
230
231    // When set, dispatchDraw() will run the layout animation and unset the flag
232    private static final int FLAG_RUN_ANIMATION = 0x8;
233
234    // When set, there is either no layout animation on the ViewGroup or the layout
235    // animation is over
236    // Set by default
237    static final int FLAG_ANIMATION_DONE = 0x10;
238
239    // If set, this ViewGroup has padding; if unset there is no padding and we don't need
240    // to clip it, even if FLAG_CLIP_TO_PADDING is set
241    private static final int FLAG_PADDING_NOT_NULL = 0x20;
242
243    // When set, this ViewGroup caches its children in a Bitmap before starting a layout animation
244    // Set by default
245    private static final int FLAG_ANIMATION_CACHE = 0x40;
246
247    // When set, this ViewGroup converts calls to invalidate(Rect) to invalidate() during a
248    // layout animation; this avoid clobbering the hierarchy
249    // Automatically set when the layout animation starts, depending on the animation's
250    // characteristics
251    static final int FLAG_OPTIMIZE_INVALIDATE = 0x80;
252
253    // When set, the next call to drawChild() will clear mChildTransformation's matrix
254    static final int FLAG_CLEAR_TRANSFORMATION = 0x100;
255
256    // When set, this ViewGroup invokes mAnimationListener.onAnimationEnd() and removes
257    // the children's Bitmap caches if necessary
258    // This flag is set when the layout animation is over (after FLAG_ANIMATION_DONE is set)
259    private static final int FLAG_NOTIFY_ANIMATION_LISTENER = 0x200;
260
261    /**
262     * When set, the drawing method will call {@link #getChildDrawingOrder(int, int)}
263     * to get the index of the child to draw for that iteration.
264     *
265     * @hide
266     */
267    protected static final int FLAG_USE_CHILD_DRAWING_ORDER = 0x400;
268
269    /**
270     * When set, this ViewGroup supports static transformations on children; this causes
271     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
272     * invoked when a child is drawn.
273     *
274     * Any subclass overriding
275     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
276     * set this flags in {@link #mGroupFlags}.
277     *
278     * {@hide}
279     */
280    protected static final int FLAG_SUPPORT_STATIC_TRANSFORMATIONS = 0x800;
281
282    // UNUSED FLAG VALUE: 0x1000;
283
284    /**
285     * When set, this ViewGroup's drawable states also include those
286     * of its children.
287     */
288    private static final int FLAG_ADD_STATES_FROM_CHILDREN = 0x2000;
289
290    /**
291     * When set, this ViewGroup tries to always draw its children using their drawing cache.
292     */
293    static final int FLAG_ALWAYS_DRAWN_WITH_CACHE = 0x4000;
294
295    /**
296     * When set, and if FLAG_ALWAYS_DRAWN_WITH_CACHE is not set, this ViewGroup will try to
297     * draw its children with their drawing cache.
298     */
299    static final int FLAG_CHILDREN_DRAWN_WITH_CACHE = 0x8000;
300
301    /**
302     * When set, this group will go through its list of children to notify them of
303     * any drawable state change.
304     */
305    private static final int FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE = 0x10000;
306
307    private static final int FLAG_MASK_FOCUSABILITY = 0x60000;
308
309    /**
310     * This view will get focus before any of its descendants.
311     */
312    public static final int FOCUS_BEFORE_DESCENDANTS = 0x20000;
313
314    /**
315     * This view will get focus only if none of its descendants want it.
316     */
317    public static final int FOCUS_AFTER_DESCENDANTS = 0x40000;
318
319    /**
320     * This view will block any of its descendants from getting focus, even
321     * if they are focusable.
322     */
323    public static final int FOCUS_BLOCK_DESCENDANTS = 0x60000;
324
325    /**
326     * Used to map between enum in attrubutes and flag values.
327     */
328    private static final int[] DESCENDANT_FOCUSABILITY_FLAGS =
329            {FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS,
330                    FOCUS_BLOCK_DESCENDANTS};
331
332    /**
333     * When set, this ViewGroup should not intercept touch events.
334     * {@hide}
335     */
336    protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000;
337
338    /**
339     * When set, this ViewGroup will split MotionEvents to multiple child Views when appropriate.
340     */
341    private static final int FLAG_SPLIT_MOTION_EVENTS = 0x200000;
342
343    /**
344     * When set, this ViewGroup will not dispatch onAttachedToWindow calls
345     * to children when adding new views. This is used to prevent multiple
346     * onAttached calls when a ViewGroup adds children in its own onAttached method.
347     */
348    private static final int FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW = 0x400000;
349
350    /**
351     * When true, indicates that a layoutMode has been explicitly set, either with
352     * an explicit call to {@link #setLayoutMode(int)} in code or from an XML resource.
353     * This distinguishes the situation in which a layout mode was inherited from
354     * one of the ViewGroup's ancestors and cached locally.
355     */
356    private static final int FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET = 0x800000;
357
358    static final int FLAG_IS_TRANSITION_GROUP = 0x1000000;
359
360    static final int FLAG_IS_TRANSITION_GROUP_SET = 0x2000000;
361
362    /**
363     * When set, focus will not be permitted to enter this group if a touchscreen is present.
364     */
365    static final int FLAG_TOUCHSCREEN_BLOCKS_FOCUS = 0x4000000;
366
367    /**
368     * Indicates which types of drawing caches are to be kept in memory.
369     * This field should be made private, so it is hidden from the SDK.
370     * {@hide}
371     */
372    protected int mPersistentDrawingCache;
373
374    /**
375     * Used to indicate that no drawing cache should be kept in memory.
376     */
377    public static final int PERSISTENT_NO_CACHE = 0x0;
378
379    /**
380     * Used to indicate that the animation drawing cache should be kept in memory.
381     */
382    public static final int PERSISTENT_ANIMATION_CACHE = 0x1;
383
384    /**
385     * Used to indicate that the scrolling drawing cache should be kept in memory.
386     */
387    public static final int PERSISTENT_SCROLLING_CACHE = 0x2;
388
389    /**
390     * Used to indicate that all drawing caches should be kept in memory.
391     */
392    public static final int PERSISTENT_ALL_CACHES = 0x3;
393
394    // Layout Modes
395
396    private static final int LAYOUT_MODE_UNDEFINED = -1;
397
398    /**
399     * This constant is a {@link #setLayoutMode(int) layoutMode}.
400     * Clip bounds are the raw values of {@link #getLeft() left}, {@link #getTop() top},
401     * {@link #getRight() right} and {@link #getBottom() bottom}.
402     */
403    public static final int LAYOUT_MODE_CLIP_BOUNDS = 0;
404
405    /**
406     * This constant is a {@link #setLayoutMode(int) layoutMode}.
407     * Optical bounds describe where a widget appears to be. They sit inside the clip
408     * bounds which need to cover a larger area to allow other effects,
409     * such as shadows and glows, to be drawn.
410     */
411    public static final int LAYOUT_MODE_OPTICAL_BOUNDS = 1;
412
413    /** @hide */
414    public static int LAYOUT_MODE_DEFAULT = LAYOUT_MODE_CLIP_BOUNDS;
415
416    /**
417     * We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL
418     * are set at the same time.
419     */
420    protected static final int CLIP_TO_PADDING_MASK = FLAG_CLIP_TO_PADDING | FLAG_PADDING_NOT_NULL;
421
422    // Index of the child's left position in the mLocation array
423    private static final int CHILD_LEFT_INDEX = 0;
424    // Index of the child's top position in the mLocation array
425    private static final int CHILD_TOP_INDEX = 1;
426
427    // Child views of this ViewGroup
428    private View[] mChildren;
429    // Number of valid children in the mChildren array, the rest should be null or not
430    // considered as children
431    private int mChildrenCount;
432
433    // Whether layout calls are currently being suppressed, controlled by calls to
434    // suppressLayout()
435    boolean mSuppressLayout = false;
436
437    // Whether any layout calls have actually been suppressed while mSuppressLayout
438    // has been true. This tracks whether we need to issue a requestLayout() when
439    // layout is later re-enabled.
440    private boolean mLayoutCalledWhileSuppressed = false;
441
442    private static final int ARRAY_INITIAL_CAPACITY = 12;
443    private static final int ARRAY_CAPACITY_INCREMENT = 12;
444
445    private static Paint sDebugPaint;
446    private static float[] sDebugLines;
447
448    // Used to draw cached views
449    Paint mCachePaint;
450
451    // Used to animate add/remove changes in layout
452    private LayoutTransition mTransition;
453
454    // The set of views that are currently being transitioned. This list is used to track views
455    // being removed that should not actually be removed from the parent yet because they are
456    // being animated.
457    private ArrayList<View> mTransitioningViews;
458
459    // List of children changing visibility. This is used to potentially keep rendering
460    // views during a transition when they otherwise would have become gone/invisible
461    private ArrayList<View> mVisibilityChangingChildren;
462
463    // Temporary holder of presorted children, only used for
464    // input/software draw dispatch for correctly Z ordering.
465    private ArrayList<View> mPreSortedChildren;
466
467    // Indicates how many of this container's child subtrees contain transient state
468    @ViewDebug.ExportedProperty(category = "layout")
469    private int mChildCountWithTransientState = 0;
470
471    /**
472     * Currently registered axes for nested scrolling. Flag set consisting of
473     * {@link #SCROLL_AXIS_HORIZONTAL} {@link #SCROLL_AXIS_VERTICAL} or {@link #SCROLL_AXIS_NONE}
474     * for null.
475     */
476    private int mNestedScrollAxes;
477
478    public ViewGroup(Context context) {
479        this(context, null);
480    }
481
482    public ViewGroup(Context context, AttributeSet attrs) {
483        this(context, attrs, 0);
484    }
485
486    public ViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
487        this(context, attrs, defStyleAttr, 0);
488    }
489
490    public ViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
491        super(context, attrs, defStyleAttr, defStyleRes);
492        initViewGroup();
493        initFromAttributes(context, attrs, defStyleAttr, defStyleRes);
494    }
495
496    private boolean debugDraw() {
497        return DEBUG_DRAW || mAttachInfo != null && mAttachInfo.mDebugLayout;
498    }
499
500    private void initViewGroup() {
501        // ViewGroup doesn't draw by default
502        if (!debugDraw()) {
503            setFlags(WILL_NOT_DRAW, DRAW_MASK);
504        }
505        mGroupFlags |= FLAG_CLIP_CHILDREN;
506        mGroupFlags |= FLAG_CLIP_TO_PADDING;
507        mGroupFlags |= FLAG_ANIMATION_DONE;
508        mGroupFlags |= FLAG_ANIMATION_CACHE;
509        mGroupFlags |= FLAG_ALWAYS_DRAWN_WITH_CACHE;
510
511        if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
512            mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
513        }
514
515        setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS);
516
517        mChildren = new View[ARRAY_INITIAL_CAPACITY];
518        mChildrenCount = 0;
519
520        mPersistentDrawingCache = PERSISTENT_SCROLLING_CACHE;
521    }
522
523    private void initFromAttributes(
524            Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
525        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ViewGroup, defStyleAttr,
526                defStyleRes);
527
528        final int N = a.getIndexCount();
529        for (int i = 0; i < N; i++) {
530            int attr = a.getIndex(i);
531            switch (attr) {
532                case R.styleable.ViewGroup_clipChildren:
533                    setClipChildren(a.getBoolean(attr, true));
534                    break;
535                case R.styleable.ViewGroup_clipToPadding:
536                    setClipToPadding(a.getBoolean(attr, true));
537                    break;
538                case R.styleable.ViewGroup_animationCache:
539                    setAnimationCacheEnabled(a.getBoolean(attr, true));
540                    break;
541                case R.styleable.ViewGroup_persistentDrawingCache:
542                    setPersistentDrawingCache(a.getInt(attr, PERSISTENT_SCROLLING_CACHE));
543                    break;
544                case R.styleable.ViewGroup_addStatesFromChildren:
545                    setAddStatesFromChildren(a.getBoolean(attr, false));
546                    break;
547                case R.styleable.ViewGroup_alwaysDrawnWithCache:
548                    setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true));
549                    break;
550                case R.styleable.ViewGroup_layoutAnimation:
551                    int id = a.getResourceId(attr, -1);
552                    if (id > 0) {
553                        setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id));
554                    }
555                    break;
556                case R.styleable.ViewGroup_descendantFocusability:
557                    setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]);
558                    break;
559                case R.styleable.ViewGroup_splitMotionEvents:
560                    setMotionEventSplittingEnabled(a.getBoolean(attr, false));
561                    break;
562                case R.styleable.ViewGroup_animateLayoutChanges:
563                    boolean animateLayoutChanges = a.getBoolean(attr, false);
564                    if (animateLayoutChanges) {
565                        setLayoutTransition(new LayoutTransition());
566                    }
567                    break;
568                case R.styleable.ViewGroup_layoutMode:
569                    setLayoutMode(a.getInt(attr, LAYOUT_MODE_UNDEFINED));
570                    break;
571                case R.styleable.ViewGroup_transitionGroup:
572                    setTransitionGroup(a.getBoolean(attr, false));
573                    break;
574                case R.styleable.ViewGroup_touchscreenBlocksFocus:
575                    setTouchscreenBlocksFocus(a.getBoolean(attr, false));
576                    break;
577            }
578        }
579
580        a.recycle();
581    }
582
583    /**
584     * Gets the descendant focusability of this view group.  The descendant
585     * focusability defines the relationship between this view group and its
586     * descendants when looking for a view to take focus in
587     * {@link #requestFocus(int, android.graphics.Rect)}.
588     *
589     * @return one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
590     *   {@link #FOCUS_BLOCK_DESCENDANTS}.
591     */
592    @ViewDebug.ExportedProperty(category = "focus", mapping = {
593        @ViewDebug.IntToString(from = FOCUS_BEFORE_DESCENDANTS, to = "FOCUS_BEFORE_DESCENDANTS"),
594        @ViewDebug.IntToString(from = FOCUS_AFTER_DESCENDANTS, to = "FOCUS_AFTER_DESCENDANTS"),
595        @ViewDebug.IntToString(from = FOCUS_BLOCK_DESCENDANTS, to = "FOCUS_BLOCK_DESCENDANTS")
596    })
597    public int getDescendantFocusability() {
598        return mGroupFlags & FLAG_MASK_FOCUSABILITY;
599    }
600
601    /**
602     * Set the descendant focusability of this view group. This defines the relationship
603     * between this view group and its descendants when looking for a view to
604     * take focus in {@link #requestFocus(int, android.graphics.Rect)}.
605     *
606     * @param focusability one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
607     *   {@link #FOCUS_BLOCK_DESCENDANTS}.
608     */
609    public void setDescendantFocusability(int focusability) {
610        switch (focusability) {
611            case FOCUS_BEFORE_DESCENDANTS:
612            case FOCUS_AFTER_DESCENDANTS:
613            case FOCUS_BLOCK_DESCENDANTS:
614                break;
615            default:
616                throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, "
617                        + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS");
618        }
619        mGroupFlags &= ~FLAG_MASK_FOCUSABILITY;
620        mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY);
621    }
622
623    /**
624     * {@inheritDoc}
625     */
626    @Override
627    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
628        if (mFocused != null) {
629            mFocused.unFocus(this);
630            mFocused = null;
631        }
632        super.handleFocusGainInternal(direction, previouslyFocusedRect);
633    }
634
635    /**
636     * {@inheritDoc}
637     */
638    public void requestChildFocus(View child, View focused) {
639        if (DBG) {
640            System.out.println(this + " requestChildFocus()");
641        }
642        if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
643            return;
644        }
645
646        // Unfocus us, if necessary
647        super.unFocus(focused);
648
649        // We had a previous notion of who had focus. Clear it.
650        if (mFocused != child) {
651            if (mFocused != null) {
652                mFocused.unFocus(focused);
653            }
654
655            mFocused = child;
656        }
657        if (mParent != null) {
658            mParent.requestChildFocus(this, focused);
659        }
660    }
661
662    /**
663     * {@inheritDoc}
664     */
665    public void focusableViewAvailable(View v) {
666        if (mParent != null
667                // shortcut: don't report a new focusable view if we block our descendants from
668                // getting focus
669                && (getDescendantFocusability() != FOCUS_BLOCK_DESCENDANTS)
670                && (isFocusableInTouchMode() || !shouldBlockFocusForTouchscreen())
671                // shortcut: don't report a new focusable view if we already are focused
672                // (and we don't prefer our descendants)
673                //
674                // note: knowing that mFocused is non-null is not a good enough reason
675                // to break the traversal since in that case we'd actually have to find
676                // the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and
677                // an ancestor of v; this will get checked for at ViewAncestor
678                && !(isFocused() && getDescendantFocusability() != FOCUS_AFTER_DESCENDANTS)) {
679            mParent.focusableViewAvailable(v);
680        }
681    }
682
683    /**
684     * {@inheritDoc}
685     */
686    public boolean showContextMenuForChild(View originalView) {
687        return mParent != null && mParent.showContextMenuForChild(originalView);
688    }
689
690    /**
691     * {@inheritDoc}
692     */
693    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
694        return mParent != null ? mParent.startActionModeForChild(originalView, callback) : null;
695    }
696
697    /**
698     * Find the nearest view in the specified direction that wants to take
699     * focus.
700     *
701     * @param focused The view that currently has focus
702     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and
703     *        FOCUS_RIGHT, or 0 for not applicable.
704     */
705    public View focusSearch(View focused, int direction) {
706        if (isRootNamespace()) {
707            // root namespace means we should consider ourselves the top of the
708            // tree for focus searching; otherwise we could be focus searching
709            // into other tabs.  see LocalActivityManager and TabHost for more info
710            return FocusFinder.getInstance().findNextFocus(this, focused, direction);
711        } else if (mParent != null) {
712            return mParent.focusSearch(focused, direction);
713        }
714        return null;
715    }
716
717    /**
718     * {@inheritDoc}
719     */
720    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
721        return false;
722    }
723
724    /**
725     * {@inheritDoc}
726     */
727    @Override
728    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
729        ViewParent parent = mParent;
730        if (parent == null) {
731            return false;
732        }
733        final boolean propagate = onRequestSendAccessibilityEvent(child, event);
734        if (!propagate) {
735            return false;
736        }
737        return parent.requestSendAccessibilityEvent(this, event);
738    }
739
740    /**
741     * Called when a child has requested sending an {@link AccessibilityEvent} and
742     * gives an opportunity to its parent to augment the event.
743     * <p>
744     * If an {@link android.view.View.AccessibilityDelegate} has been specified via calling
745     * {@link android.view.View#setAccessibilityDelegate(android.view.View.AccessibilityDelegate)} its
746     * {@link android.view.View.AccessibilityDelegate#onRequestSendAccessibilityEvent(ViewGroup, View, AccessibilityEvent)}
747     * is responsible for handling this call.
748     * </p>
749     *
750     * @param child The child which requests sending the event.
751     * @param event The event to be sent.
752     * @return True if the event should be sent.
753     *
754     * @see #requestSendAccessibilityEvent(View, AccessibilityEvent)
755     */
756    public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) {
757        if (mAccessibilityDelegate != null) {
758            return mAccessibilityDelegate.onRequestSendAccessibilityEvent(this, child, event);
759        } else {
760            return onRequestSendAccessibilityEventInternal(child, event);
761        }
762    }
763
764    /**
765     * @see #onRequestSendAccessibilityEvent(View, AccessibilityEvent)
766     *
767     * Note: Called from the default {@link View.AccessibilityDelegate}.
768     */
769    boolean onRequestSendAccessibilityEventInternal(View child, AccessibilityEvent event) {
770        return true;
771    }
772
773    /**
774     * Translates the given bounds and intersections from child coordinates to
775     * local coordinates. In case any interactive sibling of the calling child
776     * covers the latter, a new intersections is added to the intersection list.
777     * This method is for the exclusive use by the accessibility layer to compute
778     * a point where a sequence of down and up events would click on a view.
779     *
780     * @param child The child making the call.
781     * @param bounds The bounds to translate in child coordinates.
782     * @param intersections The intersections of interactive views covering the child.
783     * @return True if the bounds and intersections were computed, false otherwise.
784     */
785    boolean translateBoundsAndIntersectionsInWindowCoordinates(View child,
786            RectF bounds, List<RectF> intersections) {
787        // Not attached, done.
788        if (mAttachInfo == null) {
789            return false;
790        }
791
792        if (getAlpha() <= 0 || getTransitionAlpha() <= 0 ||
793                getVisibility() != VISIBLE) {
794            // Cannot click on a view with an invisible predecessor.
795            return false;
796        }
797
798        // Compensate for the child transformation.
799        if (!child.hasIdentityMatrix()) {
800            Matrix matrix = child.getMatrix();
801            matrix.mapRect(bounds);
802            final int intersectionCount = intersections.size();
803            for (int i = 0; i < intersectionCount; i++) {
804                RectF intersection = intersections.get(i);
805                matrix.mapRect(intersection);
806            }
807        }
808
809        // Translate the bounds from child to parent coordinates.
810        final int dx = child.mLeft - mScrollX;
811        final int dy = child.mTop - mScrollY;
812        bounds.offset(dx, dy);
813        offsetRects(intersections, dx, dy);
814
815        // If the bounds do not intersect our bounds, done.
816        if (!bounds.intersects(0, 0, getWidth(), getHeight())) {
817            return false;
818        }
819
820        // Check whether any clickable siblings cover the child
821        // view and if so keep track of the intersections. Also
822        // respect Z ordering when iterating over children.
823        ArrayList<View> orderedList = buildOrderedChildList();
824        final boolean useCustomOrder = orderedList == null
825                && isChildrenDrawingOrderEnabled();
826
827        final int childCount = mChildrenCount;
828        for (int i = childCount - 1; i >= 0; i--) {
829            final int childIndex = useCustomOrder
830                    ? getChildDrawingOrder(childCount, i) : i;
831            final View sibling = (orderedList == null)
832                    ? mChildren[childIndex] : orderedList.get(childIndex);
833
834            // We care only about siblings over the child.
835            if (sibling == child) {
836                break;
837            }
838
839            // Ignore invisible views as they are not interactive.
840            if (sibling.getVisibility() != View.VISIBLE) {
841                continue;
842            }
843
844            // If sibling is not interactive we do not care.
845            if (!sibling.isClickable() && !sibling.isLongClickable()) {
846                continue;
847            }
848
849            // Compute the sibling bounds in its coordinates.
850            RectF siblingBounds = mAttachInfo.mTmpTransformRect1;
851            siblingBounds.set(0, 0, sibling.getWidth(), sibling.getHeight());
852
853            // Take into account the sibling transformation matrix.
854            if (!sibling.hasIdentityMatrix()) {
855                sibling.getMatrix().mapRect(siblingBounds);
856            }
857
858            // Offset the sibling to our coordinates.
859            final int siblingDx = sibling.mLeft - mScrollX;
860            final int siblingDy = sibling.mTop - mScrollY;
861            siblingBounds.offset(siblingDx, siblingDy);
862
863            // Compute the intersection between the child and the sibling.
864            if (siblingBounds.intersect(bounds)) {
865                // If an interactive sibling completely covers the child, done.
866                if (siblingBounds.equals(bounds)) {
867                    if (orderedList != null) orderedList.clear();
868                    return false;
869                }
870                // Keep track of the intersection rectangle.
871                RectF intersection = new RectF(siblingBounds);
872                intersections.add(intersection);
873            }
874        }
875        if (orderedList != null) orderedList.clear();
876
877        if (mParent instanceof ViewGroup) {
878            ViewGroup parentGroup = (ViewGroup) mParent;
879            return parentGroup.translateBoundsAndIntersectionsInWindowCoordinates(
880                    this, bounds, intersections);
881        }
882
883        return true;
884    }
885
886    /**
887     * Called when a child view has changed whether or not it is tracking transient state.
888     */
889    public void childHasTransientStateChanged(View child, boolean childHasTransientState) {
890        final boolean oldHasTransientState = hasTransientState();
891        if (childHasTransientState) {
892            mChildCountWithTransientState++;
893        } else {
894            mChildCountWithTransientState--;
895        }
896
897        final boolean newHasTransientState = hasTransientState();
898        if (mParent != null && oldHasTransientState != newHasTransientState) {
899            try {
900                mParent.childHasTransientStateChanged(this, newHasTransientState);
901            } catch (AbstractMethodError e) {
902                Log.e(TAG, mParent.getClass().getSimpleName() +
903                        " does not fully implement ViewParent", e);
904            }
905        }
906    }
907
908    @Override
909    public boolean hasTransientState() {
910        return mChildCountWithTransientState > 0 || super.hasTransientState();
911    }
912
913    /**
914     * {@inheritDoc}
915     */
916    @Override
917    public boolean dispatchUnhandledMove(View focused, int direction) {
918        return mFocused != null &&
919                mFocused.dispatchUnhandledMove(focused, direction);
920    }
921
922    /**
923     * {@inheritDoc}
924     */
925    public void clearChildFocus(View child) {
926        if (DBG) {
927            System.out.println(this + " clearChildFocus()");
928        }
929
930        mFocused = null;
931        if (mParent != null) {
932            mParent.clearChildFocus(this);
933        }
934    }
935
936    /**
937     * {@inheritDoc}
938     */
939    @Override
940    public void clearFocus() {
941        if (DBG) {
942            System.out.println(this + " clearFocus()");
943        }
944        if (mFocused == null) {
945            super.clearFocus();
946        } else {
947            View focused = mFocused;
948            mFocused = null;
949            focused.clearFocus();
950        }
951    }
952
953    /**
954     * {@inheritDoc}
955     */
956    @Override
957    void unFocus(View focused) {
958        if (DBG) {
959            System.out.println(this + " unFocus()");
960        }
961        if (mFocused == null) {
962            super.unFocus(focused);
963        } else {
964            mFocused.unFocus(focused);
965            mFocused = null;
966        }
967    }
968
969    /**
970     * Returns the focused child of this view, if any. The child may have focus
971     * or contain focus.
972     *
973     * @return the focused child or null.
974     */
975    public View getFocusedChild() {
976        return mFocused;
977    }
978
979    View getDeepestFocusedChild() {
980        View v = this;
981        while (v != null) {
982            if (v.isFocused()) {
983                return v;
984            }
985            v = v instanceof ViewGroup ? ((ViewGroup) v).getFocusedChild() : null;
986        }
987        return null;
988    }
989
990    /**
991     * Returns true if this view has or contains focus
992     *
993     * @return true if this view has or contains focus
994     */
995    @Override
996    public boolean hasFocus() {
997        return (mPrivateFlags & PFLAG_FOCUSED) != 0 || mFocused != null;
998    }
999
1000    /*
1001     * (non-Javadoc)
1002     *
1003     * @see android.view.View#findFocus()
1004     */
1005    @Override
1006    public View findFocus() {
1007        if (DBG) {
1008            System.out.println("Find focus in " + this + ": flags="
1009                    + isFocused() + ", child=" + mFocused);
1010        }
1011
1012        if (isFocused()) {
1013            return this;
1014        }
1015
1016        if (mFocused != null) {
1017            return mFocused.findFocus();
1018        }
1019        return null;
1020    }
1021
1022    /**
1023     * {@inheritDoc}
1024     */
1025    @Override
1026    public boolean hasFocusable() {
1027        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
1028            return false;
1029        }
1030
1031        if (isFocusable()) {
1032            return true;
1033        }
1034
1035        final int descendantFocusability = getDescendantFocusability();
1036        if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
1037            final int count = mChildrenCount;
1038            final View[] children = mChildren;
1039
1040            for (int i = 0; i < count; i++) {
1041                final View child = children[i];
1042                if (child.hasFocusable()) {
1043                    return true;
1044                }
1045            }
1046        }
1047
1048        return false;
1049    }
1050
1051    /**
1052     * {@inheritDoc}
1053     */
1054    @Override
1055    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
1056        final int focusableCount = views.size();
1057
1058        final int descendantFocusability = getDescendantFocusability();
1059
1060        if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
1061            if (shouldBlockFocusForTouchscreen()) {
1062                focusableMode |= FOCUSABLES_TOUCH_MODE;
1063            }
1064
1065            final int count = mChildrenCount;
1066            final View[] children = mChildren;
1067
1068            for (int i = 0; i < count; i++) {
1069                final View child = children[i];
1070                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1071                    child.addFocusables(views, direction, focusableMode);
1072                }
1073            }
1074        }
1075
1076        // we add ourselves (if focusable) in all cases except for when we are
1077        // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable.  this is
1078        // to avoid the focus search finding layouts when a more precise search
1079        // among the focusable children would be more interesting.
1080        if ((descendantFocusability != FOCUS_AFTER_DESCENDANTS
1081                // No focusable descendants
1082                || (focusableCount == views.size())) &&
1083                (isFocusableInTouchMode() || !shouldBlockFocusForTouchscreen())) {
1084            super.addFocusables(views, direction, focusableMode);
1085        }
1086    }
1087
1088    /**
1089     * Set whether this ViewGroup should ignore focus requests for itself and its children.
1090     * If this option is enabled and the ViewGroup or a descendant currently has focus, focus
1091     * will proceed forward.
1092     *
1093     * @param touchscreenBlocksFocus true to enable blocking focus in the presence of a touchscreen
1094     */
1095    public void setTouchscreenBlocksFocus(boolean touchscreenBlocksFocus) {
1096        if (touchscreenBlocksFocus) {
1097            mGroupFlags |= FLAG_TOUCHSCREEN_BLOCKS_FOCUS;
1098            if (hasFocus()) {
1099                final View focusedChild = getDeepestFocusedChild();
1100                if (!focusedChild.isFocusableInTouchMode()) {
1101                    final View newFocus = focusSearch(FOCUS_FORWARD);
1102                    if (newFocus != null) {
1103                        newFocus.requestFocus();
1104                    }
1105                }
1106            }
1107        } else {
1108            mGroupFlags &= ~FLAG_TOUCHSCREEN_BLOCKS_FOCUS;
1109        }
1110    }
1111
1112    /**
1113     * Check whether this ViewGroup should ignore focus requests for itself and its children.
1114     */
1115    public boolean getTouchscreenBlocksFocus() {
1116        return (mGroupFlags & FLAG_TOUCHSCREEN_BLOCKS_FOCUS) != 0;
1117    }
1118
1119    boolean shouldBlockFocusForTouchscreen() {
1120        return getTouchscreenBlocksFocus() &&
1121                mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN);
1122    }
1123
1124    @Override
1125    public void findViewsWithText(ArrayList<View> outViews, CharSequence text, int flags) {
1126        super.findViewsWithText(outViews, text, flags);
1127        final int childrenCount = mChildrenCount;
1128        final View[] children = mChildren;
1129        for (int i = 0; i < childrenCount; i++) {
1130            View child = children[i];
1131            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
1132                    && (child.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
1133                child.findViewsWithText(outViews, text, flags);
1134            }
1135        }
1136    }
1137
1138    /** @hide */
1139    @Override
1140    public View findViewByAccessibilityIdTraversal(int accessibilityId) {
1141        View foundView = super.findViewByAccessibilityIdTraversal(accessibilityId);
1142        if (foundView != null) {
1143            return foundView;
1144        }
1145        final int childrenCount = mChildrenCount;
1146        final View[] children = mChildren;
1147        for (int i = 0; i < childrenCount; i++) {
1148            View child = children[i];
1149            foundView = child.findViewByAccessibilityIdTraversal(accessibilityId);
1150            if (foundView != null) {
1151                return foundView;
1152            }
1153        }
1154        return null;
1155    }
1156
1157    /**
1158     * {@inheritDoc}
1159     */
1160    @Override
1161    public void dispatchWindowFocusChanged(boolean hasFocus) {
1162        super.dispatchWindowFocusChanged(hasFocus);
1163        final int count = mChildrenCount;
1164        final View[] children = mChildren;
1165        for (int i = 0; i < count; i++) {
1166            children[i].dispatchWindowFocusChanged(hasFocus);
1167        }
1168    }
1169
1170    /**
1171     * {@inheritDoc}
1172     */
1173    @Override
1174    public void addTouchables(ArrayList<View> views) {
1175        super.addTouchables(views);
1176
1177        final int count = mChildrenCount;
1178        final View[] children = mChildren;
1179
1180        for (int i = 0; i < count; i++) {
1181            final View child = children[i];
1182            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1183                child.addTouchables(views);
1184            }
1185        }
1186    }
1187
1188    /**
1189     * @hide
1190     */
1191    @Override
1192    public void makeOptionalFitsSystemWindows() {
1193        super.makeOptionalFitsSystemWindows();
1194        final int count = mChildrenCount;
1195        final View[] children = mChildren;
1196        for (int i = 0; i < count; i++) {
1197            children[i].makeOptionalFitsSystemWindows();
1198        }
1199    }
1200
1201    /**
1202     * {@inheritDoc}
1203     */
1204    @Override
1205    public void dispatchDisplayHint(int hint) {
1206        super.dispatchDisplayHint(hint);
1207        final int count = mChildrenCount;
1208        final View[] children = mChildren;
1209        for (int i = 0; i < count; i++) {
1210            children[i].dispatchDisplayHint(hint);
1211        }
1212    }
1213
1214    /**
1215     * Called when a view's visibility has changed. Notify the parent to take any appropriate
1216     * action.
1217     *
1218     * @param child The view whose visibility has changed
1219     * @param oldVisibility The previous visibility value (GONE, INVISIBLE, or VISIBLE).
1220     * @param newVisibility The new visibility value (GONE, INVISIBLE, or VISIBLE).
1221     * @hide
1222     */
1223    protected void onChildVisibilityChanged(View child, int oldVisibility, int newVisibility) {
1224        if (mTransition != null) {
1225            if (newVisibility == VISIBLE) {
1226                mTransition.showChild(this, child, oldVisibility);
1227            } else {
1228                mTransition.hideChild(this, child, newVisibility);
1229                if (mTransitioningViews != null && mTransitioningViews.contains(child)) {
1230                    // Only track this on disappearing views - appearing views are already visible
1231                    // and don't need special handling during drawChild()
1232                    if (mVisibilityChangingChildren == null) {
1233                        mVisibilityChangingChildren = new ArrayList<View>();
1234                    }
1235                    mVisibilityChangingChildren.add(child);
1236                    addDisappearingView(child);
1237                }
1238            }
1239        }
1240
1241        // in all cases, for drags
1242        if (mCurrentDrag != null) {
1243            if (newVisibility == VISIBLE) {
1244                notifyChildOfDrag(child);
1245            }
1246        }
1247    }
1248
1249    /**
1250     * {@inheritDoc}
1251     */
1252    @Override
1253    protected void dispatchVisibilityChanged(View changedView, int visibility) {
1254        super.dispatchVisibilityChanged(changedView, visibility);
1255        final int count = mChildrenCount;
1256        final View[] children = mChildren;
1257        for (int i = 0; i < count; i++) {
1258            children[i].dispatchVisibilityChanged(changedView, visibility);
1259        }
1260    }
1261
1262    /**
1263     * {@inheritDoc}
1264     */
1265    @Override
1266    public void dispatchWindowVisibilityChanged(int visibility) {
1267        super.dispatchWindowVisibilityChanged(visibility);
1268        final int count = mChildrenCount;
1269        final View[] children = mChildren;
1270        for (int i = 0; i < count; i++) {
1271            children[i].dispatchWindowVisibilityChanged(visibility);
1272        }
1273    }
1274
1275    /**
1276     * {@inheritDoc}
1277     */
1278    @Override
1279    public void dispatchConfigurationChanged(Configuration newConfig) {
1280        super.dispatchConfigurationChanged(newConfig);
1281        final int count = mChildrenCount;
1282        final View[] children = mChildren;
1283        for (int i = 0; i < count; i++) {
1284            children[i].dispatchConfigurationChanged(newConfig);
1285        }
1286    }
1287
1288    /**
1289     * {@inheritDoc}
1290     */
1291    public void recomputeViewAttributes(View child) {
1292        if (mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
1293            ViewParent parent = mParent;
1294            if (parent != null) parent.recomputeViewAttributes(this);
1295        }
1296    }
1297
1298    @Override
1299    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
1300        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
1301            super.dispatchCollectViewAttributes(attachInfo, visibility);
1302            final int count = mChildrenCount;
1303            final View[] children = mChildren;
1304            for (int i = 0; i < count; i++) {
1305                final View child = children[i];
1306                child.dispatchCollectViewAttributes(attachInfo,
1307                        visibility | (child.mViewFlags&VISIBILITY_MASK));
1308            }
1309        }
1310    }
1311
1312    /**
1313     * {@inheritDoc}
1314     */
1315    public void bringChildToFront(View child) {
1316        int index = indexOfChild(child);
1317        if (index >= 0) {
1318            removeFromArray(index);
1319            addInArray(child, mChildrenCount);
1320            child.mParent = this;
1321            requestLayout();
1322            invalidate();
1323        }
1324    }
1325
1326    private PointF getLocalPoint() {
1327        if (mLocalPoint == null) mLocalPoint = new PointF();
1328        return mLocalPoint;
1329    }
1330
1331    /**
1332     * {@inheritDoc}
1333     */
1334    // TODO: Write real docs
1335    @Override
1336    public boolean dispatchDragEvent(DragEvent event) {
1337        boolean retval = false;
1338        final float tx = event.mX;
1339        final float ty = event.mY;
1340
1341        ViewRootImpl root = getViewRootImpl();
1342
1343        // Dispatch down the view hierarchy
1344        final PointF localPoint = getLocalPoint();
1345
1346        switch (event.mAction) {
1347        case DragEvent.ACTION_DRAG_STARTED: {
1348            // clear state to recalculate which views we drag over
1349            mCurrentDragView = null;
1350
1351            // Set up our tracking of drag-started notifications
1352            mCurrentDrag = DragEvent.obtain(event);
1353            if (mDragNotifiedChildren == null) {
1354                mDragNotifiedChildren = new HashSet<View>();
1355            } else {
1356                mDragNotifiedChildren.clear();
1357            }
1358
1359            // Now dispatch down to our children, caching the responses
1360            mChildAcceptsDrag = false;
1361            final int count = mChildrenCount;
1362            final View[] children = mChildren;
1363            for (int i = 0; i < count; i++) {
1364                final View child = children[i];
1365                child.mPrivateFlags2 &= ~View.DRAG_MASK;
1366                if (child.getVisibility() == VISIBLE) {
1367                    final boolean handled = notifyChildOfDrag(children[i]);
1368                    if (handled) {
1369                        mChildAcceptsDrag = true;
1370                    }
1371                }
1372            }
1373
1374            // Return HANDLED if one of our children can accept the drag
1375            if (mChildAcceptsDrag) {
1376                retval = true;
1377            }
1378        } break;
1379
1380        case DragEvent.ACTION_DRAG_ENDED: {
1381            // Release the bookkeeping now that the drag lifecycle has ended
1382            if (mDragNotifiedChildren != null) {
1383                for (View child : mDragNotifiedChildren) {
1384                    // If a child was notified about an ongoing drag, it's told that it's over
1385                    child.dispatchDragEvent(event);
1386                    child.mPrivateFlags2 &= ~View.DRAG_MASK;
1387                    child.refreshDrawableState();
1388                }
1389
1390                mDragNotifiedChildren.clear();
1391                if (mCurrentDrag != null) {
1392                    mCurrentDrag.recycle();
1393                    mCurrentDrag = null;
1394                }
1395            }
1396
1397            // We consider drag-ended to have been handled if one of our children
1398            // had offered to handle the drag.
1399            if (mChildAcceptsDrag) {
1400                retval = true;
1401            }
1402        } break;
1403
1404        case DragEvent.ACTION_DRAG_LOCATION: {
1405            // Find the [possibly new] drag target
1406            final View target = findFrontmostDroppableChildAt(event.mX, event.mY, localPoint);
1407
1408            // If we've changed apparent drag target, tell the view root which view
1409            // we're over now [for purposes of the eventual drag-recipient-changed
1410            // notifications to the framework] and tell the new target that the drag
1411            // has entered its bounds.  The root will see setDragFocus() calls all
1412            // the way down to the final leaf view that is handling the LOCATION event
1413            // before reporting the new potential recipient to the framework.
1414            if (mCurrentDragView != target) {
1415                root.setDragFocus(target);
1416
1417                final int action = event.mAction;
1418                // If we've dragged off of a child view, send it the EXITED message
1419                if (mCurrentDragView != null) {
1420                    final View view = mCurrentDragView;
1421                    event.mAction = DragEvent.ACTION_DRAG_EXITED;
1422                    view.dispatchDragEvent(event);
1423                    view.mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
1424                    view.refreshDrawableState();
1425                }
1426                mCurrentDragView = target;
1427
1428                // If we've dragged over a new child view, send it the ENTERED message
1429                if (target != null) {
1430                    event.mAction = DragEvent.ACTION_DRAG_ENTERED;
1431                    target.dispatchDragEvent(event);
1432                    target.mPrivateFlags2 |= View.PFLAG2_DRAG_HOVERED;
1433                    target.refreshDrawableState();
1434                }
1435                event.mAction = action;  // restore the event's original state
1436            }
1437
1438            // Dispatch the actual drag location notice, localized into its coordinates
1439            if (target != null) {
1440                event.mX = localPoint.x;
1441                event.mY = localPoint.y;
1442
1443                retval = target.dispatchDragEvent(event);
1444
1445                event.mX = tx;
1446                event.mY = ty;
1447            }
1448        } break;
1449
1450        /* Entered / exited dispatch
1451         *
1452         * DRAG_ENTERED is not dispatched downwards from ViewGroup.  The reason for this is
1453         * that we're about to get the corresponding LOCATION event, which we will use to
1454         * determine which of our children is the new target; at that point we will
1455         * push a DRAG_ENTERED down to the new target child [which may itself be a ViewGroup].
1456         *
1457         * DRAG_EXITED *is* dispatched all the way down immediately: once we know the
1458         * drag has left this ViewGroup, we know by definition that every contained subview
1459         * is also no longer under the drag point.
1460         */
1461
1462        case DragEvent.ACTION_DRAG_EXITED: {
1463            if (mCurrentDragView != null) {
1464                final View view = mCurrentDragView;
1465                view.dispatchDragEvent(event);
1466                view.mPrivateFlags2 &= ~View.PFLAG2_DRAG_HOVERED;
1467                view.refreshDrawableState();
1468
1469                mCurrentDragView = null;
1470            }
1471        } break;
1472
1473        case DragEvent.ACTION_DROP: {
1474            if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, "Drop event: " + event);
1475            View target = findFrontmostDroppableChildAt(event.mX, event.mY, localPoint);
1476            if (target != null) {
1477                if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, "   dispatch drop to " + target);
1478                event.mX = localPoint.x;
1479                event.mY = localPoint.y;
1480                retval = target.dispatchDragEvent(event);
1481                event.mX = tx;
1482                event.mY = ty;
1483            } else {
1484                if (ViewDebug.DEBUG_DRAG) {
1485                    Log.d(View.VIEW_LOG_TAG, "   not dropped on an accepting view");
1486                }
1487            }
1488        } break;
1489        }
1490
1491        // If none of our children could handle the event, try here
1492        if (!retval) {
1493            // Call up to the View implementation that dispatches to installed listeners
1494            retval = super.dispatchDragEvent(event);
1495        }
1496        return retval;
1497    }
1498
1499    // Find the frontmost child view that lies under the given point, and calculate
1500    // the position within its own local coordinate system.
1501    View findFrontmostDroppableChildAt(float x, float y, PointF outLocalPoint) {
1502        final int count = mChildrenCount;
1503        final View[] children = mChildren;
1504        for (int i = count - 1; i >= 0; i--) {
1505            final View child = children[i];
1506            if (!child.canAcceptDrag()) {
1507                continue;
1508            }
1509
1510            if (isTransformedTouchPointInView(x, y, child, outLocalPoint)) {
1511                return child;
1512            }
1513        }
1514        return null;
1515    }
1516
1517    boolean notifyChildOfDrag(View child) {
1518        if (ViewDebug.DEBUG_DRAG) {
1519            Log.d(View.VIEW_LOG_TAG, "Sending drag-started to view: " + child);
1520        }
1521
1522        boolean canAccept = false;
1523        if (! mDragNotifiedChildren.contains(child)) {
1524            mDragNotifiedChildren.add(child);
1525            canAccept = child.dispatchDragEvent(mCurrentDrag);
1526            if (canAccept && !child.canAcceptDrag()) {
1527                child.mPrivateFlags2 |= View.PFLAG2_DRAG_CAN_ACCEPT;
1528                child.refreshDrawableState();
1529            }
1530        }
1531        return canAccept;
1532    }
1533
1534    @Override
1535    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
1536        super.dispatchWindowSystemUiVisiblityChanged(visible);
1537
1538        final int count = mChildrenCount;
1539        final View[] children = mChildren;
1540        for (int i=0; i <count; i++) {
1541            final View child = children[i];
1542            child.dispatchWindowSystemUiVisiblityChanged(visible);
1543        }
1544    }
1545
1546    @Override
1547    public void dispatchSystemUiVisibilityChanged(int visible) {
1548        super.dispatchSystemUiVisibilityChanged(visible);
1549
1550        final int count = mChildrenCount;
1551        final View[] children = mChildren;
1552        for (int i=0; i <count; i++) {
1553            final View child = children[i];
1554            child.dispatchSystemUiVisibilityChanged(visible);
1555        }
1556    }
1557
1558    @Override
1559    boolean updateLocalSystemUiVisibility(int localValue, int localChanges) {
1560        boolean changed = super.updateLocalSystemUiVisibility(localValue, localChanges);
1561
1562        final int count = mChildrenCount;
1563        final View[] children = mChildren;
1564        for (int i=0; i <count; i++) {
1565            final View child = children[i];
1566            changed |= child.updateLocalSystemUiVisibility(localValue, localChanges);
1567        }
1568        return changed;
1569    }
1570
1571    /**
1572     * {@inheritDoc}
1573     */
1574    @Override
1575    public boolean dispatchKeyEventPreIme(KeyEvent event) {
1576        if ((mPrivateFlags & (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS))
1577                == (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) {
1578            return super.dispatchKeyEventPreIme(event);
1579        } else if (mFocused != null && (mFocused.mPrivateFlags & PFLAG_HAS_BOUNDS)
1580                == PFLAG_HAS_BOUNDS) {
1581            return mFocused.dispatchKeyEventPreIme(event);
1582        }
1583        return false;
1584    }
1585
1586    /**
1587     * {@inheritDoc}
1588     */
1589    @Override
1590    public boolean dispatchKeyEvent(KeyEvent event) {
1591        if (mInputEventConsistencyVerifier != null) {
1592            mInputEventConsistencyVerifier.onKeyEvent(event, 1);
1593        }
1594
1595        if ((mPrivateFlags & (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS))
1596                == (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) {
1597            if (super.dispatchKeyEvent(event)) {
1598                return true;
1599            }
1600        } else if (mFocused != null && (mFocused.mPrivateFlags & PFLAG_HAS_BOUNDS)
1601                == PFLAG_HAS_BOUNDS) {
1602            if (mFocused.dispatchKeyEvent(event)) {
1603                return true;
1604            }
1605        }
1606
1607        if (mInputEventConsistencyVerifier != null) {
1608            mInputEventConsistencyVerifier.onUnhandledEvent(event, 1);
1609        }
1610        return false;
1611    }
1612
1613    /**
1614     * {@inheritDoc}
1615     */
1616    @Override
1617    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
1618        if ((mPrivateFlags & (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS))
1619                == (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) {
1620            return super.dispatchKeyShortcutEvent(event);
1621        } else if (mFocused != null && (mFocused.mPrivateFlags & PFLAG_HAS_BOUNDS)
1622                == PFLAG_HAS_BOUNDS) {
1623            return mFocused.dispatchKeyShortcutEvent(event);
1624        }
1625        return false;
1626    }
1627
1628    /**
1629     * {@inheritDoc}
1630     */
1631    @Override
1632    public boolean dispatchTrackballEvent(MotionEvent event) {
1633        if (mInputEventConsistencyVerifier != null) {
1634            mInputEventConsistencyVerifier.onTrackballEvent(event, 1);
1635        }
1636
1637        if ((mPrivateFlags & (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS))
1638                == (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) {
1639            if (super.dispatchTrackballEvent(event)) {
1640                return true;
1641            }
1642        } else if (mFocused != null && (mFocused.mPrivateFlags & PFLAG_HAS_BOUNDS)
1643                == PFLAG_HAS_BOUNDS) {
1644            if (mFocused.dispatchTrackballEvent(event)) {
1645                return true;
1646            }
1647        }
1648
1649        if (mInputEventConsistencyVerifier != null) {
1650            mInputEventConsistencyVerifier.onUnhandledEvent(event, 1);
1651        }
1652        return false;
1653    }
1654
1655    /**
1656     * {@inheritDoc}
1657     */
1658    @SuppressWarnings({"ConstantConditions"})
1659    @Override
1660    protected boolean dispatchHoverEvent(MotionEvent event) {
1661        final int action = event.getAction();
1662
1663        // First check whether the view group wants to intercept the hover event.
1664        final boolean interceptHover = onInterceptHoverEvent(event);
1665        event.setAction(action); // restore action in case it was changed
1666
1667        MotionEvent eventNoHistory = event;
1668        boolean handled = false;
1669
1670        // Send events to the hovered children and build a new list of hover targets until
1671        // one is found that handles the event.
1672        HoverTarget firstOldHoverTarget = mFirstHoverTarget;
1673        mFirstHoverTarget = null;
1674        if (!interceptHover && action != MotionEvent.ACTION_HOVER_EXIT) {
1675            final float x = event.getX();
1676            final float y = event.getY();
1677            final int childrenCount = mChildrenCount;
1678            if (childrenCount != 0) {
1679                final ArrayList<View> preorderedList = buildOrderedChildList();
1680                final boolean customOrder = preorderedList == null
1681                        && isChildrenDrawingOrderEnabled();
1682                final View[] children = mChildren;
1683                HoverTarget lastHoverTarget = null;
1684                for (int i = childrenCount - 1; i >= 0; i--) {
1685                    int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
1686                    final View child = (preorderedList == null)
1687                            ? children[childIndex] : preorderedList.get(childIndex);
1688                    if (!canViewReceivePointerEvents(child)
1689                            || !isTransformedTouchPointInView(x, y, child, null)) {
1690                        continue;
1691                    }
1692
1693                    // Obtain a hover target for this child.  Dequeue it from the
1694                    // old hover target list if the child was previously hovered.
1695                    HoverTarget hoverTarget = firstOldHoverTarget;
1696                    final boolean wasHovered;
1697                    for (HoverTarget predecessor = null; ;) {
1698                        if (hoverTarget == null) {
1699                            hoverTarget = HoverTarget.obtain(child);
1700                            wasHovered = false;
1701                            break;
1702                        }
1703
1704                        if (hoverTarget.child == child) {
1705                            if (predecessor != null) {
1706                                predecessor.next = hoverTarget.next;
1707                            } else {
1708                                firstOldHoverTarget = hoverTarget.next;
1709                            }
1710                            hoverTarget.next = null;
1711                            wasHovered = true;
1712                            break;
1713                        }
1714
1715                        predecessor = hoverTarget;
1716                        hoverTarget = hoverTarget.next;
1717                    }
1718
1719                    // Enqueue the hover target onto the new hover target list.
1720                    if (lastHoverTarget != null) {
1721                        lastHoverTarget.next = hoverTarget;
1722                    } else {
1723                        mFirstHoverTarget = hoverTarget;
1724                    }
1725                    lastHoverTarget = hoverTarget;
1726
1727                    // Dispatch the event to the child.
1728                    if (action == MotionEvent.ACTION_HOVER_ENTER) {
1729                        if (!wasHovered) {
1730                            // Send the enter as is.
1731                            handled |= dispatchTransformedGenericPointerEvent(
1732                                    event, child); // enter
1733                        }
1734                    } else if (action == MotionEvent.ACTION_HOVER_MOVE) {
1735                        if (!wasHovered) {
1736                            // Synthesize an enter from a move.
1737                            eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1738                            eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
1739                            handled |= dispatchTransformedGenericPointerEvent(
1740                                    eventNoHistory, child); // enter
1741                            eventNoHistory.setAction(action);
1742
1743                            handled |= dispatchTransformedGenericPointerEvent(
1744                                    eventNoHistory, child); // move
1745                        } else {
1746                            // Send the move as is.
1747                            handled |= dispatchTransformedGenericPointerEvent(event, child);
1748                        }
1749                    }
1750                    if (handled) {
1751                        break;
1752                    }
1753                }
1754                if (preorderedList != null) preorderedList.clear();
1755            }
1756        }
1757
1758        // Send exit events to all previously hovered children that are no longer hovered.
1759        while (firstOldHoverTarget != null) {
1760            final View child = firstOldHoverTarget.child;
1761
1762            // Exit the old hovered child.
1763            if (action == MotionEvent.ACTION_HOVER_EXIT) {
1764                // Send the exit as is.
1765                handled |= dispatchTransformedGenericPointerEvent(
1766                        event, child); // exit
1767            } else {
1768                // Synthesize an exit from a move or enter.
1769                // Ignore the result because hover focus has moved to a different view.
1770                if (action == MotionEvent.ACTION_HOVER_MOVE) {
1771                    dispatchTransformedGenericPointerEvent(
1772                            event, child); // move
1773                }
1774                eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1775                eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
1776                dispatchTransformedGenericPointerEvent(
1777                        eventNoHistory, child); // exit
1778                eventNoHistory.setAction(action);
1779            }
1780
1781            final HoverTarget nextOldHoverTarget = firstOldHoverTarget.next;
1782            firstOldHoverTarget.recycle();
1783            firstOldHoverTarget = nextOldHoverTarget;
1784        }
1785
1786        // Send events to the view group itself if no children have handled it.
1787        boolean newHoveredSelf = !handled;
1788        if (newHoveredSelf == mHoveredSelf) {
1789            if (newHoveredSelf) {
1790                // Send event to the view group as before.
1791                handled |= super.dispatchHoverEvent(event);
1792            }
1793        } else {
1794            if (mHoveredSelf) {
1795                // Exit the view group.
1796                if (action == MotionEvent.ACTION_HOVER_EXIT) {
1797                    // Send the exit as is.
1798                    handled |= super.dispatchHoverEvent(event); // exit
1799                } else {
1800                    // Synthesize an exit from a move or enter.
1801                    // Ignore the result because hover focus is moving to a different view.
1802                    if (action == MotionEvent.ACTION_HOVER_MOVE) {
1803                        super.dispatchHoverEvent(event); // move
1804                    }
1805                    eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1806                    eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
1807                    super.dispatchHoverEvent(eventNoHistory); // exit
1808                    eventNoHistory.setAction(action);
1809                }
1810                mHoveredSelf = false;
1811            }
1812
1813            if (newHoveredSelf) {
1814                // Enter the view group.
1815                if (action == MotionEvent.ACTION_HOVER_ENTER) {
1816                    // Send the enter as is.
1817                    handled |= super.dispatchHoverEvent(event); // enter
1818                    mHoveredSelf = true;
1819                } else if (action == MotionEvent.ACTION_HOVER_MOVE) {
1820                    // Synthesize an enter from a move.
1821                    eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1822                    eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
1823                    handled |= super.dispatchHoverEvent(eventNoHistory); // enter
1824                    eventNoHistory.setAction(action);
1825
1826                    handled |= super.dispatchHoverEvent(eventNoHistory); // move
1827                    mHoveredSelf = true;
1828                }
1829            }
1830        }
1831
1832        // Recycle the copy of the event that we made.
1833        if (eventNoHistory != event) {
1834            eventNoHistory.recycle();
1835        }
1836
1837        // Done.
1838        return handled;
1839    }
1840
1841    private void exitHoverTargets() {
1842        if (mHoveredSelf || mFirstHoverTarget != null) {
1843            final long now = SystemClock.uptimeMillis();
1844            MotionEvent event = MotionEvent.obtain(now, now,
1845                    MotionEvent.ACTION_HOVER_EXIT, 0.0f, 0.0f, 0);
1846            event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
1847            dispatchHoverEvent(event);
1848            event.recycle();
1849        }
1850    }
1851
1852    private void cancelHoverTarget(View view) {
1853        HoverTarget predecessor = null;
1854        HoverTarget target = mFirstHoverTarget;
1855        while (target != null) {
1856            final HoverTarget next = target.next;
1857            if (target.child == view) {
1858                if (predecessor == null) {
1859                    mFirstHoverTarget = next;
1860                } else {
1861                    predecessor.next = next;
1862                }
1863                target.recycle();
1864
1865                final long now = SystemClock.uptimeMillis();
1866                MotionEvent event = MotionEvent.obtain(now, now,
1867                        MotionEvent.ACTION_HOVER_EXIT, 0.0f, 0.0f, 0);
1868                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
1869                view.dispatchHoverEvent(event);
1870                event.recycle();
1871                return;
1872            }
1873            predecessor = target;
1874            target = next;
1875        }
1876    }
1877
1878    /** @hide */
1879    @Override
1880    protected boolean hasHoveredChild() {
1881        return mFirstHoverTarget != null;
1882    }
1883
1884    @Override
1885    public void addChildrenForAccessibility(ArrayList<View> childrenForAccessibility) {
1886        ChildListForAccessibility children = ChildListForAccessibility.obtain(this, true);
1887        try {
1888            final int childrenCount = children.getChildCount();
1889            for (int i = 0; i < childrenCount; i++) {
1890                View child = children.getChildAt(i);
1891                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1892                    if (child.includeForAccessibility()) {
1893                        childrenForAccessibility.add(child);
1894                    } else {
1895                        child.addChildrenForAccessibility(childrenForAccessibility);
1896                    }
1897                }
1898            }
1899        } finally {
1900            children.recycle();
1901        }
1902    }
1903
1904    /**
1905     * Implement this method to intercept hover events before they are handled
1906     * by child views.
1907     * <p>
1908     * This method is called before dispatching a hover event to a child of
1909     * the view group or to the view group's own {@link #onHoverEvent} to allow
1910     * the view group a chance to intercept the hover event.
1911     * This method can also be used to watch all pointer motions that occur within
1912     * the bounds of the view group even when the pointer is hovering over
1913     * a child of the view group rather than over the view group itself.
1914     * </p><p>
1915     * The view group can prevent its children from receiving hover events by
1916     * implementing this method and returning <code>true</code> to indicate
1917     * that it would like to intercept hover events.  The view group must
1918     * continuously return <code>true</code> from {@link #onInterceptHoverEvent}
1919     * for as long as it wishes to continue intercepting hover events from
1920     * its children.
1921     * </p><p>
1922     * Interception preserves the invariant that at most one view can be
1923     * hovered at a time by transferring hover focus from the currently hovered
1924     * child to the view group or vice-versa as needed.
1925     * </p><p>
1926     * If this method returns <code>true</code> and a child is already hovered, then the
1927     * child view will first receive a hover exit event and then the view group
1928     * itself will receive a hover enter event in {@link #onHoverEvent}.
1929     * Likewise, if this method had previously returned <code>true</code> to intercept hover
1930     * events and instead returns <code>false</code> while the pointer is hovering
1931     * within the bounds of one of a child, then the view group will first receive a
1932     * hover exit event in {@link #onHoverEvent} and then the hovered child will
1933     * receive a hover enter event.
1934     * </p><p>
1935     * The default implementation always returns false.
1936     * </p>
1937     *
1938     * @param event The motion event that describes the hover.
1939     * @return True if the view group would like to intercept the hover event
1940     * and prevent its children from receiving it.
1941     */
1942    public boolean onInterceptHoverEvent(MotionEvent event) {
1943        return false;
1944    }
1945
1946    private static MotionEvent obtainMotionEventNoHistoryOrSelf(MotionEvent event) {
1947        if (event.getHistorySize() == 0) {
1948            return event;
1949        }
1950        return MotionEvent.obtainNoHistory(event);
1951    }
1952
1953    /**
1954     * {@inheritDoc}
1955     */
1956    @Override
1957    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
1958        // Send the event to the child under the pointer.
1959        final int childrenCount = mChildrenCount;
1960        if (childrenCount != 0) {
1961            final float x = event.getX();
1962            final float y = event.getY();
1963
1964            final ArrayList<View> preorderedList = buildOrderedChildList();
1965            final boolean customOrder = preorderedList == null
1966                    && isChildrenDrawingOrderEnabled();
1967            final View[] children = mChildren;
1968            for (int i = childrenCount - 1; i >= 0; i--) {
1969                int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
1970                final View child = (preorderedList == null)
1971                        ? children[childIndex] : preorderedList.get(childIndex);
1972                if (!canViewReceivePointerEvents(child)
1973                        || !isTransformedTouchPointInView(x, y, child, null)) {
1974                    continue;
1975                }
1976
1977                if (dispatchTransformedGenericPointerEvent(event, child)) {
1978                    if (preorderedList != null) preorderedList.clear();
1979                    return true;
1980                }
1981            }
1982            if (preorderedList != null) preorderedList.clear();
1983        }
1984
1985        // No child handled the event.  Send it to this view group.
1986        return super.dispatchGenericPointerEvent(event);
1987    }
1988
1989    /**
1990     * {@inheritDoc}
1991     */
1992    @Override
1993    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
1994        // Send the event to the focused child or to this view group if it has focus.
1995        if ((mPrivateFlags & (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS))
1996                == (PFLAG_FOCUSED | PFLAG_HAS_BOUNDS)) {
1997            return super.dispatchGenericFocusedEvent(event);
1998        } else if (mFocused != null && (mFocused.mPrivateFlags & PFLAG_HAS_BOUNDS)
1999                == PFLAG_HAS_BOUNDS) {
2000            return mFocused.dispatchGenericMotionEvent(event);
2001        }
2002        return false;
2003    }
2004
2005    /**
2006     * Dispatches a generic pointer event to a child, taking into account
2007     * transformations that apply to the child.
2008     *
2009     * @param event The event to send.
2010     * @param child The view to send the event to.
2011     * @return {@code true} if the child handled the event.
2012     */
2013    private boolean dispatchTransformedGenericPointerEvent(MotionEvent event, View child) {
2014        final float offsetX = mScrollX - child.mLeft;
2015        final float offsetY = mScrollY - child.mTop;
2016
2017        boolean handled;
2018        if (!child.hasIdentityMatrix()) {
2019            MotionEvent transformedEvent = MotionEvent.obtain(event);
2020            transformedEvent.offsetLocation(offsetX, offsetY);
2021            transformedEvent.transform(child.getInverseMatrix());
2022            handled = child.dispatchGenericMotionEvent(transformedEvent);
2023            transformedEvent.recycle();
2024        } else {
2025            event.offsetLocation(offsetX, offsetY);
2026            handled = child.dispatchGenericMotionEvent(event);
2027            event.offsetLocation(-offsetX, -offsetY);
2028        }
2029        return handled;
2030    }
2031
2032    /**
2033     * {@inheritDoc}
2034     */
2035    @Override
2036    public boolean dispatchTouchEvent(MotionEvent ev) {
2037        if (mInputEventConsistencyVerifier != null) {
2038            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
2039        }
2040
2041        boolean handled = false;
2042        if (onFilterTouchEventForSecurity(ev)) {
2043            final int action = ev.getAction();
2044            final int actionMasked = action & MotionEvent.ACTION_MASK;
2045
2046            // Handle an initial down.
2047            if (actionMasked == MotionEvent.ACTION_DOWN) {
2048                // Throw away all previous state when starting a new touch gesture.
2049                // The framework may have dropped the up or cancel event for the previous gesture
2050                // due to an app switch, ANR, or some other state change.
2051                cancelAndClearTouchTargets(ev);
2052                resetTouchState();
2053            }
2054
2055            // Check for interception.
2056            final boolean intercepted;
2057            if (actionMasked == MotionEvent.ACTION_DOWN
2058                    || mFirstTouchTarget != null) {
2059                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
2060                if (!disallowIntercept) {
2061                    intercepted = onInterceptTouchEvent(ev);
2062                    ev.setAction(action); // restore action in case it was changed
2063                } else {
2064                    intercepted = false;
2065                }
2066            } else {
2067                // There are no touch targets and this action is not an initial down
2068                // so this view group continues to intercept touches.
2069                intercepted = true;
2070            }
2071
2072            // Check for cancelation.
2073            final boolean canceled = resetCancelNextUpFlag(this)
2074                    || actionMasked == MotionEvent.ACTION_CANCEL;
2075
2076            // Update list of touch targets for pointer down, if needed.
2077            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
2078            TouchTarget newTouchTarget = null;
2079            boolean alreadyDispatchedToNewTouchTarget = false;
2080            if (!canceled && !intercepted) {
2081                if (actionMasked == MotionEvent.ACTION_DOWN
2082                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
2083                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
2084                    final int actionIndex = ev.getActionIndex(); // always 0 for down
2085                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
2086                            : TouchTarget.ALL_POINTER_IDS;
2087
2088                    // Clean up earlier touch targets for this pointer id in case they
2089                    // have become out of sync.
2090                    removePointersFromTouchTargets(idBitsToAssign);
2091
2092                    final int childrenCount = mChildrenCount;
2093                    if (newTouchTarget == null && childrenCount != 0) {
2094                        final float x = ev.getX(actionIndex);
2095                        final float y = ev.getY(actionIndex);
2096                        // Find a child that can receive the event.
2097                        // Scan children from front to back.
2098                        final ArrayList<View> preorderedList = buildOrderedChildList();
2099                        final boolean customOrder = preorderedList == null
2100                                && isChildrenDrawingOrderEnabled();
2101                        final View[] children = mChildren;
2102                        for (int i = childrenCount - 1; i >= 0; i--) {
2103                            final int childIndex = customOrder
2104                                    ? getChildDrawingOrder(childrenCount, i) : i;
2105                            final View child = (preorderedList == null)
2106                                    ? children[childIndex] : preorderedList.get(childIndex);
2107                            if (!canViewReceivePointerEvents(child)
2108                                    || !isTransformedTouchPointInView(x, y, child, null)) {
2109                                continue;
2110                            }
2111
2112                            newTouchTarget = getTouchTarget(child);
2113                            if (newTouchTarget != null) {
2114                                // Child is already receiving touch within its bounds.
2115                                // Give it the new pointer in addition to the ones it is handling.
2116                                newTouchTarget.pointerIdBits |= idBitsToAssign;
2117                                break;
2118                            }
2119
2120                            resetCancelNextUpFlag(child);
2121                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
2122                                // Child wants to receive touch within its bounds.
2123                                mLastTouchDownTime = ev.getDownTime();
2124                                if (preorderedList != null) {
2125                                    // childIndex points into presorted list, find original index
2126                                    for (int j = 0; j < childrenCount; j++) {
2127                                        if (children[childIndex] == mChildren[j]) {
2128                                            mLastTouchDownIndex = j;
2129                                            break;
2130                                        }
2131                                    }
2132                                } else {
2133                                    mLastTouchDownIndex = childIndex;
2134                                }
2135                                mLastTouchDownX = ev.getX();
2136                                mLastTouchDownY = ev.getY();
2137                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
2138                                alreadyDispatchedToNewTouchTarget = true;
2139                                break;
2140                            }
2141                        }
2142                        if (preorderedList != null) preorderedList.clear();
2143                    }
2144
2145                    if (newTouchTarget == null && mFirstTouchTarget != null) {
2146                        // Did not find a child to receive the event.
2147                        // Assign the pointer to the least recently added target.
2148                        newTouchTarget = mFirstTouchTarget;
2149                        while (newTouchTarget.next != null) {
2150                            newTouchTarget = newTouchTarget.next;
2151                        }
2152                        newTouchTarget.pointerIdBits |= idBitsToAssign;
2153                    }
2154                }
2155            }
2156
2157            // Dispatch to touch targets.
2158            if (mFirstTouchTarget == null) {
2159                // No touch targets so treat this as an ordinary view.
2160                handled = dispatchTransformedTouchEvent(ev, canceled, null,
2161                        TouchTarget.ALL_POINTER_IDS);
2162            } else {
2163                // Dispatch to touch targets, excluding the new touch target if we already
2164                // dispatched to it.  Cancel touch targets if necessary.
2165                TouchTarget predecessor = null;
2166                TouchTarget target = mFirstTouchTarget;
2167                while (target != null) {
2168                    final TouchTarget next = target.next;
2169                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
2170                        handled = true;
2171                    } else {
2172                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
2173                                || intercepted;
2174                        if (dispatchTransformedTouchEvent(ev, cancelChild,
2175                                target.child, target.pointerIdBits)) {
2176                            handled = true;
2177                        }
2178                        if (cancelChild) {
2179                            if (predecessor == null) {
2180                                mFirstTouchTarget = next;
2181                            } else {
2182                                predecessor.next = next;
2183                            }
2184                            target.recycle();
2185                            target = next;
2186                            continue;
2187                        }
2188                    }
2189                    predecessor = target;
2190                    target = next;
2191                }
2192            }
2193
2194            // Update list of touch targets for pointer up or cancel, if needed.
2195            if (canceled
2196                    || actionMasked == MotionEvent.ACTION_UP
2197                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
2198                resetTouchState();
2199            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
2200                final int actionIndex = ev.getActionIndex();
2201                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
2202                removePointersFromTouchTargets(idBitsToRemove);
2203            }
2204        }
2205
2206        if (!handled && mInputEventConsistencyVerifier != null) {
2207            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
2208        }
2209        return handled;
2210    }
2211
2212    /**
2213     * Resets all touch state in preparation for a new cycle.
2214     */
2215    private void resetTouchState() {
2216        clearTouchTargets();
2217        resetCancelNextUpFlag(this);
2218        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
2219        mNestedScrollAxes = SCROLL_AXIS_NONE;
2220    }
2221
2222    /**
2223     * Resets the cancel next up flag.
2224     * Returns true if the flag was previously set.
2225     */
2226    private static boolean resetCancelNextUpFlag(View view) {
2227        if ((view.mPrivateFlags & PFLAG_CANCEL_NEXT_UP_EVENT) != 0) {
2228            view.mPrivateFlags &= ~PFLAG_CANCEL_NEXT_UP_EVENT;
2229            return true;
2230        }
2231        return false;
2232    }
2233
2234    /**
2235     * Clears all touch targets.
2236     */
2237    private void clearTouchTargets() {
2238        TouchTarget target = mFirstTouchTarget;
2239        if (target != null) {
2240            do {
2241                TouchTarget next = target.next;
2242                target.recycle();
2243                target = next;
2244            } while (target != null);
2245            mFirstTouchTarget = null;
2246        }
2247    }
2248
2249    /**
2250     * Cancels and clears all touch targets.
2251     */
2252    private void cancelAndClearTouchTargets(MotionEvent event) {
2253        if (mFirstTouchTarget != null) {
2254            boolean syntheticEvent = false;
2255            if (event == null) {
2256                final long now = SystemClock.uptimeMillis();
2257                event = MotionEvent.obtain(now, now,
2258                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
2259                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
2260                syntheticEvent = true;
2261            }
2262
2263            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
2264                resetCancelNextUpFlag(target.child);
2265                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
2266            }
2267            clearTouchTargets();
2268
2269            if (syntheticEvent) {
2270                event.recycle();
2271            }
2272        }
2273    }
2274
2275    /**
2276     * Gets the touch target for specified child view.
2277     * Returns null if not found.
2278     */
2279    private TouchTarget getTouchTarget(View child) {
2280        for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
2281            if (target.child == child) {
2282                return target;
2283            }
2284        }
2285        return null;
2286    }
2287
2288    /**
2289     * Adds a touch target for specified child to the beginning of the list.
2290     * Assumes the target child is not already present.
2291     */
2292    private TouchTarget addTouchTarget(View child, int pointerIdBits) {
2293        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
2294        target.next = mFirstTouchTarget;
2295        mFirstTouchTarget = target;
2296        return target;
2297    }
2298
2299    /**
2300     * Removes the pointer ids from consideration.
2301     */
2302    private void removePointersFromTouchTargets(int pointerIdBits) {
2303        TouchTarget predecessor = null;
2304        TouchTarget target = mFirstTouchTarget;
2305        while (target != null) {
2306            final TouchTarget next = target.next;
2307            if ((target.pointerIdBits & pointerIdBits) != 0) {
2308                target.pointerIdBits &= ~pointerIdBits;
2309                if (target.pointerIdBits == 0) {
2310                    if (predecessor == null) {
2311                        mFirstTouchTarget = next;
2312                    } else {
2313                        predecessor.next = next;
2314                    }
2315                    target.recycle();
2316                    target = next;
2317                    continue;
2318                }
2319            }
2320            predecessor = target;
2321            target = next;
2322        }
2323    }
2324
2325    private void cancelTouchTarget(View view) {
2326        TouchTarget predecessor = null;
2327        TouchTarget target = mFirstTouchTarget;
2328        while (target != null) {
2329            final TouchTarget next = target.next;
2330            if (target.child == view) {
2331                if (predecessor == null) {
2332                    mFirstTouchTarget = next;
2333                } else {
2334                    predecessor.next = next;
2335                }
2336                target.recycle();
2337
2338                final long now = SystemClock.uptimeMillis();
2339                MotionEvent event = MotionEvent.obtain(now, now,
2340                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
2341                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
2342                view.dispatchTouchEvent(event);
2343                event.recycle();
2344                return;
2345            }
2346            predecessor = target;
2347            target = next;
2348        }
2349    }
2350
2351    /**
2352     * Returns true if a child view can receive pointer events.
2353     * @hide
2354     */
2355    private static boolean canViewReceivePointerEvents(View child) {
2356        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
2357                || child.getAnimation() != null;
2358    }
2359
2360    /**
2361     * Returns true if a child view contains the specified point when transformed
2362     * into its coordinate space.
2363     * Child must not be null.
2364     * @hide
2365     */
2366    protected boolean isTransformedTouchPointInView(float x, float y, View child,
2367            PointF outLocalPoint) {
2368        float localX = x + mScrollX - child.mLeft;
2369        float localY = y + mScrollY - child.mTop;
2370        if (! child.hasIdentityMatrix() && mAttachInfo != null) {
2371            final float[] localXY = mAttachInfo.mTmpTransformLocation;
2372            localXY[0] = localX;
2373            localXY[1] = localY;
2374            child.getInverseMatrix().mapPoints(localXY);
2375            localX = localXY[0];
2376            localY = localXY[1];
2377        }
2378        final boolean isInView = child.pointInView(localX, localY);
2379        if (isInView && outLocalPoint != null) {
2380            outLocalPoint.set(localX, localY);
2381        }
2382        return isInView;
2383    }
2384
2385    /**
2386     * Transforms a motion event into the coordinate space of a particular child view,
2387     * filters out irrelevant pointer ids, and overrides its action if necessary.
2388     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
2389     */
2390    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
2391            View child, int desiredPointerIdBits) {
2392        final boolean handled;
2393
2394        // Canceling motions is a special case.  We don't need to perform any transformations
2395        // or filtering.  The important part is the action, not the contents.
2396        final int oldAction = event.getAction();
2397        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
2398            event.setAction(MotionEvent.ACTION_CANCEL);
2399            if (child == null) {
2400                handled = super.dispatchTouchEvent(event);
2401            } else {
2402                handled = child.dispatchTouchEvent(event);
2403            }
2404            event.setAction(oldAction);
2405            return handled;
2406        }
2407
2408        // Calculate the number of pointers to deliver.
2409        final int oldPointerIdBits = event.getPointerIdBits();
2410        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
2411
2412        // If for some reason we ended up in an inconsistent state where it looks like we
2413        // might produce a motion event with no pointers in it, then drop the event.
2414        if (newPointerIdBits == 0) {
2415            return false;
2416        }
2417
2418        // If the number of pointers is the same and we don't need to perform any fancy
2419        // irreversible transformations, then we can reuse the motion event for this
2420        // dispatch as long as we are careful to revert any changes we make.
2421        // Otherwise we need to make a copy.
2422        final MotionEvent transformedEvent;
2423        if (newPointerIdBits == oldPointerIdBits) {
2424            if (child == null || child.hasIdentityMatrix()) {
2425                if (child == null) {
2426                    handled = super.dispatchTouchEvent(event);
2427                } else {
2428                    final float offsetX = mScrollX - child.mLeft;
2429                    final float offsetY = mScrollY - child.mTop;
2430                    event.offsetLocation(offsetX, offsetY);
2431
2432                    handled = child.dispatchTouchEvent(event);
2433
2434                    event.offsetLocation(-offsetX, -offsetY);
2435                }
2436                return handled;
2437            }
2438            transformedEvent = MotionEvent.obtain(event);
2439        } else {
2440            transformedEvent = event.split(newPointerIdBits);
2441        }
2442
2443        // Perform any necessary transformations and dispatch.
2444        if (child == null) {
2445            handled = super.dispatchTouchEvent(transformedEvent);
2446        } else {
2447            final float offsetX = mScrollX - child.mLeft;
2448            final float offsetY = mScrollY - child.mTop;
2449            transformedEvent.offsetLocation(offsetX, offsetY);
2450            if (! child.hasIdentityMatrix()) {
2451                transformedEvent.transform(child.getInverseMatrix());
2452            }
2453
2454            handled = child.dispatchTouchEvent(transformedEvent);
2455        }
2456
2457        // Done.
2458        transformedEvent.recycle();
2459        return handled;
2460    }
2461
2462    /**
2463     * Enable or disable the splitting of MotionEvents to multiple children during touch event
2464     * dispatch. This behavior is enabled by default for applications that target an
2465     * SDK version of {@link Build.VERSION_CODES#HONEYCOMB} or newer.
2466     *
2467     * <p>When this option is enabled MotionEvents may be split and dispatched to different child
2468     * views depending on where each pointer initially went down. This allows for user interactions
2469     * such as scrolling two panes of content independently, chording of buttons, and performing
2470     * independent gestures on different pieces of content.
2471     *
2472     * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple
2473     *              child views. <code>false</code> to only allow one child view to be the target of
2474     *              any MotionEvent received by this ViewGroup.
2475     * @attr ref android.R.styleable#ViewGroup_splitMotionEvents
2476     */
2477    public void setMotionEventSplittingEnabled(boolean split) {
2478        // TODO Applications really shouldn't change this setting mid-touch event,
2479        // but perhaps this should handle that case and send ACTION_CANCELs to any child views
2480        // with gestures in progress when this is changed.
2481        if (split) {
2482            mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
2483        } else {
2484            mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
2485        }
2486    }
2487
2488    /**
2489     * Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
2490     * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
2491     */
2492    public boolean isMotionEventSplittingEnabled() {
2493        return (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS;
2494    }
2495
2496    /**
2497     * Returns true if this ViewGroup should be considered as a single entity for removal
2498     * when executing an Activity transition. If this is false, child elements will move
2499     * individually during the transition.
2500     * @return True if the ViewGroup should be acted on together during an Activity transition.
2501     * The default value is false when the background is null and true when the background
2502     * is not null or if {@link #getTransitionName()} is not null.
2503     */
2504    public boolean isTransitionGroup() {
2505        if ((mGroupFlags & FLAG_IS_TRANSITION_GROUP_SET) != 0) {
2506            return ((mGroupFlags & FLAG_IS_TRANSITION_GROUP) != 0);
2507        } else {
2508            return getBackground() != null || getTransitionName() != null;
2509        }
2510    }
2511
2512    /**
2513     * Changes whether or not this ViewGroup should be treated as a single entity during
2514     * Activity Transitions.
2515     * @param isTransitionGroup Whether or not the ViewGroup should be treated as a unit
2516     *                          in Activity transitions. If false, the ViewGroup won't transition,
2517     *                          only its children. If true, the entire ViewGroup will transition
2518     *                          together.
2519     * @see android.app.ActivityOptions#makeSceneTransitionAnimation(android.app.Activity,
2520     * android.util.Pair[])
2521     */
2522    public void setTransitionGroup(boolean isTransitionGroup) {
2523        mGroupFlags |= FLAG_IS_TRANSITION_GROUP_SET;
2524        if (isTransitionGroup) {
2525            mGroupFlags |= FLAG_IS_TRANSITION_GROUP;
2526        } else {
2527            mGroupFlags &= ~FLAG_IS_TRANSITION_GROUP;
2528        }
2529    }
2530
2531    /**
2532     * {@inheritDoc}
2533     */
2534    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2535
2536        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
2537            // We're already in this state, assume our ancestors are too
2538            return;
2539        }
2540
2541        if (disallowIntercept) {
2542            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
2543        } else {
2544            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
2545        }
2546
2547        // Pass it up to our parent
2548        if (mParent != null) {
2549            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
2550        }
2551    }
2552
2553    /**
2554     * Implement this method to intercept all touch screen motion events.  This
2555     * allows you to watch events as they are dispatched to your children, and
2556     * take ownership of the current gesture at any point.
2557     *
2558     * <p>Using this function takes some care, as it has a fairly complicated
2559     * interaction with {@link View#onTouchEvent(MotionEvent)
2560     * View.onTouchEvent(MotionEvent)}, and using it requires implementing
2561     * that method as well as this one in the correct way.  Events will be
2562     * received in the following order:
2563     *
2564     * <ol>
2565     * <li> You will receive the down event here.
2566     * <li> The down event will be handled either by a child of this view
2567     * group, or given to your own onTouchEvent() method to handle; this means
2568     * you should implement onTouchEvent() to return true, so you will
2569     * continue to see the rest of the gesture (instead of looking for
2570     * a parent view to handle it).  Also, by returning true from
2571     * onTouchEvent(), you will not receive any following
2572     * events in onInterceptTouchEvent() and all touch processing must
2573     * happen in onTouchEvent() like normal.
2574     * <li> For as long as you return false from this function, each following
2575     * event (up to and including the final up) will be delivered first here
2576     * and then to the target's onTouchEvent().
2577     * <li> If you return true from here, you will not receive any
2578     * following events: the target view will receive the same event but
2579     * with the action {@link MotionEvent#ACTION_CANCEL}, and all further
2580     * events will be delivered to your onTouchEvent() method and no longer
2581     * appear here.
2582     * </ol>
2583     *
2584     * @param ev The motion event being dispatched down the hierarchy.
2585     * @return Return true to steal motion events from the children and have
2586     * them dispatched to this ViewGroup through onTouchEvent().
2587     * The current target will receive an ACTION_CANCEL event, and no further
2588     * messages will be delivered here.
2589     */
2590    public boolean onInterceptTouchEvent(MotionEvent ev) {
2591        return false;
2592    }
2593
2594    /**
2595     * {@inheritDoc}
2596     *
2597     * Looks for a view to give focus to respecting the setting specified by
2598     * {@link #getDescendantFocusability()}.
2599     *
2600     * Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to
2601     * find focus within the children of this group when appropriate.
2602     *
2603     * @see #FOCUS_BEFORE_DESCENDANTS
2604     * @see #FOCUS_AFTER_DESCENDANTS
2605     * @see #FOCUS_BLOCK_DESCENDANTS
2606     * @see #onRequestFocusInDescendants(int, android.graphics.Rect)
2607     */
2608    @Override
2609    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
2610        if (DBG) {
2611            System.out.println(this + " ViewGroup.requestFocus direction="
2612                    + direction);
2613        }
2614        int descendantFocusability = getDescendantFocusability();
2615
2616        switch (descendantFocusability) {
2617            case FOCUS_BLOCK_DESCENDANTS:
2618                return super.requestFocus(direction, previouslyFocusedRect);
2619            case FOCUS_BEFORE_DESCENDANTS: {
2620                final boolean took = super.requestFocus(direction, previouslyFocusedRect);
2621                return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect);
2622            }
2623            case FOCUS_AFTER_DESCENDANTS: {
2624                final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);
2625                return took ? took : super.requestFocus(direction, previouslyFocusedRect);
2626            }
2627            default:
2628                throw new IllegalStateException("descendant focusability must be "
2629                        + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS "
2630                        + "but is " + descendantFocusability);
2631        }
2632    }
2633
2634    /**
2635     * Look for a descendant to call {@link View#requestFocus} on.
2636     * Called by {@link ViewGroup#requestFocus(int, android.graphics.Rect)}
2637     * when it wants to request focus within its children.  Override this to
2638     * customize how your {@link ViewGroup} requests focus within its children.
2639     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
2640     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
2641     *        to give a finer grained hint about where focus is coming from.  May be null
2642     *        if there is no hint.
2643     * @return Whether focus was taken.
2644     */
2645    @SuppressWarnings({"ConstantConditions"})
2646    protected boolean onRequestFocusInDescendants(int direction,
2647            Rect previouslyFocusedRect) {
2648        int index;
2649        int increment;
2650        int end;
2651        int count = mChildrenCount;
2652        if ((direction & FOCUS_FORWARD) != 0) {
2653            index = 0;
2654            increment = 1;
2655            end = count;
2656        } else {
2657            index = count - 1;
2658            increment = -1;
2659            end = -1;
2660        }
2661        final View[] children = mChildren;
2662        for (int i = index; i != end; i += increment) {
2663            View child = children[i];
2664            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2665                if (child.requestFocus(direction, previouslyFocusedRect)) {
2666                    return true;
2667                }
2668            }
2669        }
2670        return false;
2671    }
2672
2673    /**
2674     * {@inheritDoc}
2675     *
2676     * @hide
2677     */
2678    @Override
2679    public void dispatchStartTemporaryDetach() {
2680        super.dispatchStartTemporaryDetach();
2681        final int count = mChildrenCount;
2682        final View[] children = mChildren;
2683        for (int i = 0; i < count; i++) {
2684            children[i].dispatchStartTemporaryDetach();
2685        }
2686    }
2687
2688    /**
2689     * {@inheritDoc}
2690     *
2691     * @hide
2692     */
2693    @Override
2694    public void dispatchFinishTemporaryDetach() {
2695        super.dispatchFinishTemporaryDetach();
2696        final int count = mChildrenCount;
2697        final View[] children = mChildren;
2698        for (int i = 0; i < count; i++) {
2699            children[i].dispatchFinishTemporaryDetach();
2700        }
2701    }
2702
2703    /**
2704     * {@inheritDoc}
2705     */
2706    @Override
2707    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
2708        mGroupFlags |= FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;
2709        super.dispatchAttachedToWindow(info, visibility);
2710        mGroupFlags &= ~FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;
2711
2712        final int count = mChildrenCount;
2713        final View[] children = mChildren;
2714        for (int i = 0; i < count; i++) {
2715            final View child = children[i];
2716            child.dispatchAttachedToWindow(info,
2717                    visibility | (child.mViewFlags & VISIBILITY_MASK));
2718        }
2719    }
2720
2721    @Override
2722    void dispatchScreenStateChanged(int screenState) {
2723        super.dispatchScreenStateChanged(screenState);
2724
2725        final int count = mChildrenCount;
2726        final View[] children = mChildren;
2727        for (int i = 0; i < count; i++) {
2728            children[i].dispatchScreenStateChanged(screenState);
2729        }
2730    }
2731
2732    @Override
2733    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
2734        boolean handled = false;
2735        if (includeForAccessibility()) {
2736            handled = super.dispatchPopulateAccessibilityEventInternal(event);
2737            if (handled) {
2738                return handled;
2739            }
2740        }
2741        // Let our children have a shot in populating the event.
2742        ChildListForAccessibility children = ChildListForAccessibility.obtain(this, true);
2743        try {
2744            final int childCount = children.getChildCount();
2745            for (int i = 0; i < childCount; i++) {
2746                View child = children.getChildAt(i);
2747                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2748                    handled = child.dispatchPopulateAccessibilityEvent(event);
2749                    if (handled) {
2750                        return handled;
2751                    }
2752                }
2753            }
2754        } finally {
2755            children.recycle();
2756        }
2757        return false;
2758    }
2759
2760    @Override
2761    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
2762        super.onInitializeAccessibilityNodeInfoInternal(info);
2763        if (mAttachInfo != null) {
2764            final ArrayList<View> childrenForAccessibility = mAttachInfo.mTempArrayList;
2765            childrenForAccessibility.clear();
2766            addChildrenForAccessibility(childrenForAccessibility);
2767            final int childrenForAccessibilityCount = childrenForAccessibility.size();
2768            for (int i = 0; i < childrenForAccessibilityCount; i++) {
2769                final View child = childrenForAccessibility.get(i);
2770                info.addChildUnchecked(child);
2771            }
2772            childrenForAccessibility.clear();
2773        }
2774    }
2775
2776    @Override
2777    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
2778        super.onInitializeAccessibilityEventInternal(event);
2779        event.setClassName(ViewGroup.class.getName());
2780    }
2781
2782    @Override
2783    public void notifySubtreeAccessibilityStateChanged(View child, View source, int changeType) {
2784        // If this is a live region, we should send a subtree change event
2785        // from this view. Otherwise, we can let it propagate up.
2786        if (getAccessibilityLiveRegion() != ACCESSIBILITY_LIVE_REGION_NONE) {
2787            notifyViewAccessibilityStateChangedIfNeeded(changeType);
2788        } else if (mParent != null) {
2789            try {
2790                mParent.notifySubtreeAccessibilityStateChanged(this, source, changeType);
2791            } catch (AbstractMethodError e) {
2792                Log.e(VIEW_LOG_TAG, mParent.getClass().getSimpleName() +
2793                        " does not fully implement ViewParent", e);
2794            }
2795        }
2796    }
2797
2798    @Override
2799    void resetSubtreeAccessibilityStateChanged() {
2800        super.resetSubtreeAccessibilityStateChanged();
2801        View[] children = mChildren;
2802        final int childCount = mChildrenCount;
2803        for (int i = 0; i < childCount; i++) {
2804            children[i].resetSubtreeAccessibilityStateChanged();
2805        }
2806    }
2807
2808    /**
2809     * {@inheritDoc}
2810     */
2811    @Override
2812    void dispatchDetachedFromWindow() {
2813        // If we still have a touch target, we are still in the process of
2814        // dispatching motion events to a child; we need to get rid of that
2815        // child to avoid dispatching events to it after the window is torn
2816        // down. To make sure we keep the child in a consistent state, we
2817        // first send it an ACTION_CANCEL motion event.
2818        cancelAndClearTouchTargets(null);
2819
2820        // Similarly, set ACTION_EXIT to all hover targets and clear them.
2821        exitHoverTargets();
2822
2823        // In case view is detached while transition is running
2824        mLayoutCalledWhileSuppressed = false;
2825
2826        // Tear down our drag tracking
2827        mDragNotifiedChildren = null;
2828        if (mCurrentDrag != null) {
2829            mCurrentDrag.recycle();
2830            mCurrentDrag = null;
2831        }
2832
2833        final int count = mChildrenCount;
2834        final View[] children = mChildren;
2835        for (int i = 0; i < count; i++) {
2836            children[i].dispatchDetachedFromWindow();
2837        }
2838        clearDisappearingChildren();
2839        super.dispatchDetachedFromWindow();
2840    }
2841
2842    /**
2843     * @hide
2844     */
2845    @Override
2846    protected void internalSetPadding(int left, int top, int right, int bottom) {
2847        super.internalSetPadding(left, top, right, bottom);
2848
2849        if ((mPaddingLeft | mPaddingTop | mPaddingRight | mPaddingBottom) != 0) {
2850            mGroupFlags |= FLAG_PADDING_NOT_NULL;
2851        } else {
2852            mGroupFlags &= ~FLAG_PADDING_NOT_NULL;
2853        }
2854    }
2855
2856    /**
2857     * {@inheritDoc}
2858     */
2859    @Override
2860    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
2861        super.dispatchSaveInstanceState(container);
2862        final int count = mChildrenCount;
2863        final View[] children = mChildren;
2864        for (int i = 0; i < count; i++) {
2865            View c = children[i];
2866            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
2867                c.dispatchSaveInstanceState(container);
2868            }
2869        }
2870    }
2871
2872    /**
2873     * Perform dispatching of a {@link #saveHierarchyState(android.util.SparseArray)}  freeze()}
2874     * to only this view, not to its children.  For use when overriding
2875     * {@link #dispatchSaveInstanceState(android.util.SparseArray)}  dispatchFreeze()} to allow
2876     * subclasses to freeze their own state but not the state of their children.
2877     *
2878     * @param container the container
2879     */
2880    protected void dispatchFreezeSelfOnly(SparseArray<Parcelable> container) {
2881        super.dispatchSaveInstanceState(container);
2882    }
2883
2884    /**
2885     * {@inheritDoc}
2886     */
2887    @Override
2888    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
2889        super.dispatchRestoreInstanceState(container);
2890        final int count = mChildrenCount;
2891        final View[] children = mChildren;
2892        for (int i = 0; i < count; i++) {
2893            View c = children[i];
2894            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
2895                c.dispatchRestoreInstanceState(container);
2896            }
2897        }
2898    }
2899
2900    /**
2901     * Perform dispatching of a {@link #restoreHierarchyState(android.util.SparseArray)}
2902     * to only this view, not to its children.  For use when overriding
2903     * {@link #dispatchRestoreInstanceState(android.util.SparseArray)} to allow
2904     * subclasses to thaw their own state but not the state of their children.
2905     *
2906     * @param container the container
2907     */
2908    protected void dispatchThawSelfOnly(SparseArray<Parcelable> container) {
2909        super.dispatchRestoreInstanceState(container);
2910    }
2911
2912    /**
2913     * Enables or disables the drawing cache for each child of this view group.
2914     *
2915     * @param enabled true to enable the cache, false to dispose of it
2916     */
2917    protected void setChildrenDrawingCacheEnabled(boolean enabled) {
2918        if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) {
2919            final View[] children = mChildren;
2920            final int count = mChildrenCount;
2921            for (int i = 0; i < count; i++) {
2922                children[i].setDrawingCacheEnabled(enabled);
2923            }
2924        }
2925    }
2926
2927    @Override
2928    protected void onAnimationStart() {
2929        super.onAnimationStart();
2930
2931        // When this ViewGroup's animation starts, build the cache for the children
2932        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2933            final int count = mChildrenCount;
2934            final View[] children = mChildren;
2935            final boolean buildCache = !isHardwareAccelerated();
2936
2937            for (int i = 0; i < count; i++) {
2938                final View child = children[i];
2939                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2940                    child.setDrawingCacheEnabled(true);
2941                    if (buildCache) {
2942                        child.buildDrawingCache(true);
2943                    }
2944                }
2945            }
2946
2947            mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
2948        }
2949    }
2950
2951    @Override
2952    protected void onAnimationEnd() {
2953        super.onAnimationEnd();
2954
2955        // When this ViewGroup's animation ends, destroy the cache of the children
2956        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2957            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
2958
2959            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
2960                setChildrenDrawingCacheEnabled(false);
2961            }
2962        }
2963    }
2964
2965    @Override
2966    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
2967        int count = mChildrenCount;
2968        int[] visibilities = null;
2969
2970        if (skipChildren) {
2971            visibilities = new int[count];
2972            for (int i = 0; i < count; i++) {
2973                View child = getChildAt(i);
2974                visibilities[i] = child.getVisibility();
2975                if (visibilities[i] == View.VISIBLE) {
2976                    child.setVisibility(INVISIBLE);
2977                }
2978            }
2979        }
2980
2981        Bitmap b = super.createSnapshot(quality, backgroundColor, skipChildren);
2982
2983        if (skipChildren) {
2984            for (int i = 0; i < count; i++) {
2985                getChildAt(i).setVisibility(visibilities[i]);
2986            }
2987        }
2988
2989        return b;
2990    }
2991
2992    /** Return true if this ViewGroup is laying out using optical bounds. */
2993    boolean isLayoutModeOptical() {
2994        return mLayoutMode == LAYOUT_MODE_OPTICAL_BOUNDS;
2995    }
2996
2997    Insets computeOpticalInsets() {
2998        if (isLayoutModeOptical()) {
2999            int left = 0;
3000            int top = 0;
3001            int right = 0;
3002            int bottom = 0;
3003            for (int i = 0; i < mChildrenCount; i++) {
3004                View child = getChildAt(i);
3005                if (child.getVisibility() == VISIBLE) {
3006                    Insets insets = child.getOpticalInsets();
3007                    left =   Math.max(left,   insets.left);
3008                    top =    Math.max(top,    insets.top);
3009                    right =  Math.max(right,  insets.right);
3010                    bottom = Math.max(bottom, insets.bottom);
3011                }
3012            }
3013            return Insets.of(left, top, right, bottom);
3014        } else {
3015            return Insets.NONE;
3016        }
3017    }
3018
3019    private static void fillRect(Canvas canvas, Paint paint, int x1, int y1, int x2, int y2) {
3020        if (x1 != x2 && y1 != y2) {
3021            if (x1 > x2) {
3022                int tmp = x1; x1 = x2; x2 = tmp;
3023            }
3024            if (y1 > y2) {
3025                int tmp = y1; y1 = y2; y2 = tmp;
3026            }
3027            canvas.drawRect(x1, y1, x2, y2, paint);
3028        }
3029    }
3030
3031    private static int sign(int x) {
3032        return (x >= 0) ? 1 : -1;
3033    }
3034
3035    private static void drawCorner(Canvas c, Paint paint, int x1, int y1, int dx, int dy, int lw) {
3036        fillRect(c, paint, x1, y1, x1 + dx, y1 + lw * sign(dy));
3037        fillRect(c, paint, x1, y1, x1 + lw * sign(dx), y1 + dy);
3038    }
3039
3040    private int dipsToPixels(int dips) {
3041        float scale = getContext().getResources().getDisplayMetrics().density;
3042        return (int) (dips * scale + 0.5f);
3043    }
3044
3045    private static void drawRectCorners(Canvas canvas, int x1, int y1, int x2, int y2, Paint paint,
3046            int lineLength, int lineWidth) {
3047        drawCorner(canvas, paint, x1, y1, lineLength, lineLength, lineWidth);
3048        drawCorner(canvas, paint, x1, y2, lineLength, -lineLength, lineWidth);
3049        drawCorner(canvas, paint, x2, y1, -lineLength, lineLength, lineWidth);
3050        drawCorner(canvas, paint, x2, y2, -lineLength, -lineLength, lineWidth);
3051    }
3052
3053    private static void fillDifference(Canvas canvas,
3054            int x2, int y2, int x3, int y3,
3055            int dx1, int dy1, int dx2, int dy2, Paint paint) {
3056        int x1 = x2 - dx1;
3057        int y1 = y2 - dy1;
3058
3059        int x4 = x3 + dx2;
3060        int y4 = y3 + dy2;
3061
3062        fillRect(canvas, paint, x1, y1, x4, y2);
3063        fillRect(canvas, paint, x1, y2, x2, y3);
3064        fillRect(canvas, paint, x3, y2, x4, y3);
3065        fillRect(canvas, paint, x1, y3, x4, y4);
3066    }
3067
3068    /**
3069     * @hide
3070     */
3071    protected void onDebugDrawMargins(Canvas canvas, Paint paint) {
3072        for (int i = 0; i < getChildCount(); i++) {
3073            View c = getChildAt(i);
3074            c.getLayoutParams().onDebugDraw(c, canvas, paint);
3075        }
3076    }
3077
3078    /**
3079     * @hide
3080     */
3081    protected void onDebugDraw(Canvas canvas) {
3082        Paint paint = getDebugPaint();
3083
3084        // Draw optical bounds
3085        {
3086            paint.setColor(Color.RED);
3087            paint.setStyle(Paint.Style.STROKE);
3088
3089            for (int i = 0; i < getChildCount(); i++) {
3090                View c = getChildAt(i);
3091                Insets insets = c.getOpticalInsets();
3092
3093                drawRect(canvas, paint,
3094                        c.getLeft()   + insets.left,
3095                        c.getTop()    + insets.top,
3096                        c.getRight()  - insets.right  - 1,
3097                        c.getBottom() - insets.bottom - 1);
3098            }
3099        }
3100
3101        // Draw margins
3102        {
3103            paint.setColor(Color.argb(63, 255, 0, 255));
3104            paint.setStyle(Paint.Style.FILL);
3105
3106            onDebugDrawMargins(canvas, paint);
3107        }
3108
3109        // Draw clip bounds
3110        {
3111            paint.setColor(Color.rgb(63, 127, 255));
3112            paint.setStyle(Paint.Style.FILL);
3113
3114            int lineLength = dipsToPixels(8);
3115            int lineWidth = dipsToPixels(1);
3116            for (int i = 0; i < getChildCount(); i++) {
3117                View c = getChildAt(i);
3118                drawRectCorners(canvas, c.getLeft(), c.getTop(), c.getRight(), c.getBottom(),
3119                        paint, lineLength, lineWidth);
3120            }
3121        }
3122    }
3123
3124    /**
3125     * {@inheritDoc}
3126     */
3127    @Override
3128    protected void dispatchDraw(Canvas canvas) {
3129        boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
3130        final int childrenCount = mChildrenCount;
3131        final View[] children = mChildren;
3132        int flags = mGroupFlags;
3133
3134        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
3135            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
3136
3137            final boolean buildCache = !isHardwareAccelerated();
3138            for (int i = 0; i < childrenCount; i++) {
3139                final View child = children[i];
3140                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
3141                    final LayoutParams params = child.getLayoutParams();
3142                    attachLayoutAnimationParameters(child, params, i, childrenCount);
3143                    bindLayoutAnimation(child);
3144                    if (cache) {
3145                        child.setDrawingCacheEnabled(true);
3146                        if (buildCache) {
3147                            child.buildDrawingCache(true);
3148                        }
3149                    }
3150                }
3151            }
3152
3153            final LayoutAnimationController controller = mLayoutAnimationController;
3154            if (controller.willOverlap()) {
3155                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
3156            }
3157
3158            controller.start();
3159
3160            mGroupFlags &= ~FLAG_RUN_ANIMATION;
3161            mGroupFlags &= ~FLAG_ANIMATION_DONE;
3162
3163            if (cache) {
3164                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
3165            }
3166
3167            if (mAnimationListener != null) {
3168                mAnimationListener.onAnimationStart(controller.getAnimation());
3169            }
3170        }
3171
3172        int clipSaveCount = 0;
3173        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
3174        if (clipToPadding) {
3175            clipSaveCount = canvas.save();
3176            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
3177                    mScrollX + mRight - mLeft - mPaddingRight,
3178                    mScrollY + mBottom - mTop - mPaddingBottom);
3179        }
3180
3181        // We will draw our child's animation, let's reset the flag
3182        mPrivateFlags &= ~PFLAG_DRAW_ANIMATION;
3183        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
3184
3185        boolean more = false;
3186        final long drawingTime = getDrawingTime();
3187
3188        if (usingRenderNodeProperties) canvas.insertReorderBarrier();
3189        // Only use the preordered list if not HW accelerated, since the HW pipeline will do the
3190        // draw reordering internally
3191        final ArrayList<View> preorderedList = usingRenderNodeProperties
3192                ? null : buildOrderedChildList();
3193        final boolean customOrder = preorderedList == null
3194                && isChildrenDrawingOrderEnabled();
3195        for (int i = 0; i < childrenCount; i++) {
3196            int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i;
3197            final View child = (preorderedList == null)
3198                    ? children[childIndex] : preorderedList.get(childIndex);
3199            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
3200                more |= drawChild(canvas, child, drawingTime);
3201            }
3202        }
3203        if (preorderedList != null) preorderedList.clear();
3204
3205        // Draw any disappearing views that have animations
3206        if (mDisappearingChildren != null) {
3207            final ArrayList<View> disappearingChildren = mDisappearingChildren;
3208            final int disappearingCount = disappearingChildren.size() - 1;
3209            // Go backwards -- we may delete as animations finish
3210            for (int i = disappearingCount; i >= 0; i--) {
3211                final View child = disappearingChildren.get(i);
3212                more |= drawChild(canvas, child, drawingTime);
3213            }
3214        }
3215        if (usingRenderNodeProperties) canvas.insertInorderBarrier();
3216
3217        if (debugDraw()) {
3218            onDebugDraw(canvas);
3219        }
3220
3221        if (clipToPadding) {
3222            canvas.restoreToCount(clipSaveCount);
3223        }
3224
3225        // mGroupFlags might have been updated by drawChild()
3226        flags = mGroupFlags;
3227
3228        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
3229            invalidate(true);
3230        }
3231
3232        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
3233                mLayoutAnimationController.isDone() && !more) {
3234            // We want to erase the drawing cache and notify the listener after the
3235            // next frame is drawn because one extra invalidate() is caused by
3236            // drawChild() after the animation is over
3237            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
3238            final Runnable end = new Runnable() {
3239               public void run() {
3240                   notifyAnimationListener();
3241               }
3242            };
3243            post(end);
3244        }
3245    }
3246
3247    /**
3248     * Returns the ViewGroupOverlay for this view group, creating it if it does
3249     * not yet exist. In addition to {@link ViewOverlay}'s support for drawables,
3250     * {@link ViewGroupOverlay} allows views to be added to the overlay. These
3251     * views, like overlay drawables, are visual-only; they do not receive input
3252     * events and should not be used as anything other than a temporary
3253     * representation of a view in a parent container, such as might be used
3254     * by an animation effect.
3255     *
3256     * <p>Note: Overlays do not currently work correctly with {@link
3257     * SurfaceView} or {@link TextureView}; contents in overlays for these
3258     * types of views may not display correctly.</p>
3259     *
3260     * @return The ViewGroupOverlay object for this view.
3261     * @see ViewGroupOverlay
3262     */
3263    @Override
3264    public ViewGroupOverlay getOverlay() {
3265        if (mOverlay == null) {
3266            mOverlay = new ViewGroupOverlay(mContext, this);
3267        }
3268        return (ViewGroupOverlay) mOverlay;
3269    }
3270
3271    /**
3272     * Returns the index of the child to draw for this iteration. Override this
3273     * if you want to change the drawing order of children. By default, it
3274     * returns i.
3275     * <p>
3276     * NOTE: In order for this method to be called, you must enable child ordering
3277     * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}.
3278     *
3279     * @param i The current iteration.
3280     * @return The index of the child to draw this iteration.
3281     *
3282     * @see #setChildrenDrawingOrderEnabled(boolean)
3283     * @see #isChildrenDrawingOrderEnabled()
3284     */
3285    protected int getChildDrawingOrder(int childCount, int i) {
3286        return i;
3287    }
3288
3289    private boolean hasChildWithZ() {
3290        for (int i = 0; i < mChildrenCount; i++) {
3291            if (mChildren[i].getZ() != 0) return true;
3292        }
3293        return false;
3294    }
3295
3296    /**
3297     * Populates (and returns) mPreSortedChildren with a pre-ordered list of the View's children,
3298     * sorted first by Z, then by child drawing order (if applicable). This list must be cleared
3299     * after use to avoid leaking child Views.
3300     *
3301     * Uses a stable, insertion sort which is commonly O(n) for ViewGroups with very few elevated
3302     * children.
3303     */
3304    ArrayList<View> buildOrderedChildList() {
3305        final int count = mChildrenCount;
3306        if (count <= 1 || !hasChildWithZ()) return null;
3307
3308        if (mPreSortedChildren == null) {
3309            mPreSortedChildren = new ArrayList<View>(count);
3310        } else {
3311            mPreSortedChildren.ensureCapacity(count);
3312        }
3313
3314        final boolean useCustomOrder = isChildrenDrawingOrderEnabled();
3315        for (int i = 0; i < mChildrenCount; i++) {
3316            // add next child (in child order) to end of list
3317            int childIndex = useCustomOrder ? getChildDrawingOrder(mChildrenCount, i) : i;
3318            View nextChild = mChildren[childIndex];
3319            float currentZ = nextChild.getZ();
3320
3321            // insert ahead of any Views with greater Z
3322            int insertIndex = i;
3323            while (insertIndex > 0 && mPreSortedChildren.get(insertIndex - 1).getZ() > currentZ) {
3324                insertIndex--;
3325            }
3326            mPreSortedChildren.add(insertIndex, nextChild);
3327        }
3328        return mPreSortedChildren;
3329    }
3330
3331    private void notifyAnimationListener() {
3332        mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER;
3333        mGroupFlags |= FLAG_ANIMATION_DONE;
3334
3335        if (mAnimationListener != null) {
3336           final Runnable end = new Runnable() {
3337               public void run() {
3338                   mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation());
3339               }
3340           };
3341           post(end);
3342        }
3343
3344        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
3345            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
3346            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
3347                setChildrenDrawingCacheEnabled(false);
3348            }
3349        }
3350
3351        invalidate(true);
3352    }
3353
3354    /**
3355     * This method is used to cause children of this ViewGroup to restore or recreate their
3356     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
3357     * to recreate its own display list, which would happen if it went through the normal
3358     * draw/dispatchDraw mechanisms.
3359     *
3360     * @hide
3361     */
3362    @Override
3363    protected void dispatchGetDisplayList() {
3364        final int count = mChildrenCount;
3365        final View[] children = mChildren;
3366        for (int i = 0; i < count; i++) {
3367            final View child = children[i];
3368            if (((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) &&
3369                    child.hasStaticLayer()) {
3370                recreateChildDisplayList(child);
3371            }
3372        }
3373        if (mOverlay != null) {
3374            View overlayView = mOverlay.getOverlayView();
3375            recreateChildDisplayList(overlayView);
3376        }
3377        if (mDisappearingChildren != null) {
3378            final ArrayList<View> disappearingChildren = mDisappearingChildren;
3379            final int disappearingCount = disappearingChildren.size();
3380            for (int i = 0; i < disappearingCount; ++i) {
3381                final View child = disappearingChildren.get(i);
3382                recreateChildDisplayList(child);
3383            }
3384        }
3385    }
3386
3387    private void recreateChildDisplayList(View child) {
3388        child.mRecreateDisplayList = (child.mPrivateFlags & PFLAG_INVALIDATED)
3389                == PFLAG_INVALIDATED;
3390        child.mPrivateFlags &= ~PFLAG_INVALIDATED;
3391        child.getDisplayList();
3392        child.mRecreateDisplayList = false;
3393    }
3394
3395    /**
3396     * Draw one child of this View Group. This method is responsible for getting
3397     * the canvas in the right state. This includes clipping, translating so
3398     * that the child's scrolled origin is at 0, 0, and applying any animation
3399     * transformations.
3400     *
3401     * @param canvas The canvas on which to draw the child
3402     * @param child Who to draw
3403     * @param drawingTime The time at which draw is occurring
3404     * @return True if an invalidate() was issued
3405     */
3406    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3407        return child.draw(canvas, this, drawingTime);
3408    }
3409
3410    /**
3411     * Returns whether this group's children are clipped to their bounds before drawing.
3412     * The default value is true.
3413     * @see #setClipChildren(boolean)
3414     *
3415     * @return True if the group's children will be clipped to their bounds,
3416     * false otherwise.
3417     */
3418    @ViewDebug.ExportedProperty(category = "drawing")
3419    public boolean getClipChildren() {
3420        return ((mGroupFlags & FLAG_CLIP_CHILDREN) != 0);
3421    }
3422
3423    /**
3424     * By default, children are clipped to their bounds before drawing. This
3425     * allows view groups to override this behavior for animations, etc.
3426     *
3427     * @param clipChildren true to clip children to their bounds,
3428     *        false otherwise
3429     * @attr ref android.R.styleable#ViewGroup_clipChildren
3430     */
3431    public void setClipChildren(boolean clipChildren) {
3432        boolean previousValue = (mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN;
3433        if (clipChildren != previousValue) {
3434            setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren);
3435            for (int i = 0; i < mChildrenCount; ++i) {
3436                View child = getChildAt(i);
3437                if (child.mRenderNode != null) {
3438                    child.mRenderNode.setClipToBounds(clipChildren);
3439                }
3440            }
3441            invalidate(true);
3442        }
3443    }
3444
3445    /**
3446     * By default, children are clipped to the padding of the ViewGroup. This
3447     * allows view groups to override this behavior
3448     *
3449     * @param clipToPadding true to clip children to the padding of the
3450     *        group, false otherwise
3451     * @attr ref android.R.styleable#ViewGroup_clipToPadding
3452     */
3453    public void setClipToPadding(boolean clipToPadding) {
3454        if (hasBooleanFlag(FLAG_CLIP_TO_PADDING) != clipToPadding) {
3455            setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
3456            invalidate(true);
3457        }
3458    }
3459
3460    /**
3461     * Check if this ViewGroup is configured to clip child views to its padding.
3462     *
3463     * @return true if this ViewGroup clips children to its padding, false otherwise
3464     *
3465     * @attr ref android.R.styleable#ViewGroup_clipToPadding
3466     */
3467    @ViewDebug.ExportedProperty(category = "drawing")
3468    public boolean getClipToPadding() {
3469        return hasBooleanFlag(FLAG_CLIP_TO_PADDING);
3470    }
3471
3472    /**
3473     * {@inheritDoc}
3474     */
3475    @Override
3476    public void dispatchSetSelected(boolean selected) {
3477        final View[] children = mChildren;
3478        final int count = mChildrenCount;
3479        for (int i = 0; i < count; i++) {
3480            children[i].setSelected(selected);
3481        }
3482    }
3483
3484    /**
3485     * {@inheritDoc}
3486     */
3487    @Override
3488    public void dispatchSetActivated(boolean activated) {
3489        final View[] children = mChildren;
3490        final int count = mChildrenCount;
3491        for (int i = 0; i < count; i++) {
3492            children[i].setActivated(activated);
3493        }
3494    }
3495
3496    @Override
3497    protected void dispatchSetPressed(boolean pressed) {
3498        final View[] children = mChildren;
3499        final int count = mChildrenCount;
3500        for (int i = 0; i < count; i++) {
3501            final View child = children[i];
3502            // Children that are clickable on their own should not
3503            // show a pressed state when their parent view does.
3504            // Clearing a pressed state always propagates.
3505            if (!pressed || (!child.isClickable() && !child.isLongClickable())) {
3506                child.setPressed(pressed);
3507            }
3508        }
3509    }
3510
3511    @Override
3512    void dispatchCancelPendingInputEvents() {
3513        super.dispatchCancelPendingInputEvents();
3514
3515        final View[] children = mChildren;
3516        final int count = mChildrenCount;
3517        for (int i = 0; i < count; i++) {
3518            children[i].dispatchCancelPendingInputEvents();
3519        }
3520    }
3521
3522    /**
3523     * When this property is set to true, this ViewGroup supports static transformations on
3524     * children; this causes
3525     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
3526     * invoked when a child is drawn.
3527     *
3528     * Any subclass overriding
3529     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
3530     * set this property to true.
3531     *
3532     * @param enabled True to enable static transformations on children, false otherwise.
3533     *
3534     * @see #getChildStaticTransformation(View, android.view.animation.Transformation)
3535     */
3536    protected void setStaticTransformationsEnabled(boolean enabled) {
3537        setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled);
3538    }
3539
3540    /**
3541     * Sets  <code>t</code> to be the static transformation of the child, if set, returning a
3542     * boolean to indicate whether a static transform was set. The default implementation
3543     * simply returns <code>false</code>; subclasses may override this method for different
3544     * behavior. {@link #setStaticTransformationsEnabled(boolean)} must be set to true
3545     * for this method to be called.
3546     *
3547     * @param child The child view whose static transform is being requested
3548     * @param t The Transformation which will hold the result
3549     * @return true if the transformation was set, false otherwise
3550     * @see #setStaticTransformationsEnabled(boolean)
3551     */
3552    protected boolean getChildStaticTransformation(View child, Transformation t) {
3553        return false;
3554    }
3555
3556    Transformation getChildTransformation() {
3557        if (mChildTransformation == null) {
3558            mChildTransformation = new Transformation();
3559        }
3560        return mChildTransformation;
3561    }
3562
3563    /**
3564     * {@hide}
3565     */
3566    @Override
3567    protected View findViewTraversal(int id) {
3568        if (id == mID) {
3569            return this;
3570        }
3571
3572        final View[] where = mChildren;
3573        final int len = mChildrenCount;
3574
3575        for (int i = 0; i < len; i++) {
3576            View v = where[i];
3577
3578            if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
3579                v = v.findViewById(id);
3580
3581                if (v != null) {
3582                    return v;
3583                }
3584            }
3585        }
3586
3587        return null;
3588    }
3589
3590    /**
3591     * {@hide}
3592     */
3593    @Override
3594    protected View findViewWithTagTraversal(Object tag) {
3595        if (tag != null && tag.equals(mTag)) {
3596            return this;
3597        }
3598
3599        final View[] where = mChildren;
3600        final int len = mChildrenCount;
3601
3602        for (int i = 0; i < len; i++) {
3603            View v = where[i];
3604
3605            if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
3606                v = v.findViewWithTag(tag);
3607
3608                if (v != null) {
3609                    return v;
3610                }
3611            }
3612        }
3613
3614        return null;
3615    }
3616
3617    /**
3618     * {@hide}
3619     */
3620    @Override
3621    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
3622        if (predicate.apply(this)) {
3623            return this;
3624        }
3625
3626        final View[] where = mChildren;
3627        final int len = mChildrenCount;
3628
3629        for (int i = 0; i < len; i++) {
3630            View v = where[i];
3631
3632            if (v != childToSkip && (v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
3633                v = v.findViewByPredicate(predicate);
3634
3635                if (v != null) {
3636                    return v;
3637                }
3638            }
3639        }
3640
3641        return null;
3642    }
3643
3644    /**
3645     * <p>Adds a child view. If no layout parameters are already set on the child, the
3646     * default parameters for this ViewGroup are set on the child.</p>
3647     *
3648     * <p><strong>Note:</strong> do not invoke this method from
3649     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3650     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3651     *
3652     * @param child the child view to add
3653     *
3654     * @see #generateDefaultLayoutParams()
3655     */
3656    public void addView(View child) {
3657        addView(child, -1);
3658    }
3659
3660    /**
3661     * Adds a child view. If no layout parameters are already set on the child, the
3662     * default parameters for this ViewGroup are set on the child.
3663     *
3664     * <p><strong>Note:</strong> do not invoke this method from
3665     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3666     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3667     *
3668     * @param child the child view to add
3669     * @param index the position at which to add the child
3670     *
3671     * @see #generateDefaultLayoutParams()
3672     */
3673    public void addView(View child, int index) {
3674        LayoutParams params = child.getLayoutParams();
3675        if (params == null) {
3676            params = generateDefaultLayoutParams();
3677            if (params == null) {
3678                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
3679            }
3680        }
3681        addView(child, index, params);
3682    }
3683
3684    /**
3685     * Adds a child view with this ViewGroup's default layout parameters and the
3686     * specified width and height.
3687     *
3688     * <p><strong>Note:</strong> do not invoke this method from
3689     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3690     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3691     *
3692     * @param child the child view to add
3693     */
3694    public void addView(View child, int width, int height) {
3695        final LayoutParams params = generateDefaultLayoutParams();
3696        params.width = width;
3697        params.height = height;
3698        addView(child, -1, params);
3699    }
3700
3701    /**
3702     * Adds a child view with the specified layout parameters.
3703     *
3704     * <p><strong>Note:</strong> do not invoke this method from
3705     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3706     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3707     *
3708     * @param child the child view to add
3709     * @param params the layout parameters to set on the child
3710     */
3711    public void addView(View child, LayoutParams params) {
3712        addView(child, -1, params);
3713    }
3714
3715    /**
3716     * Adds a child view with the specified layout parameters.
3717     *
3718     * <p><strong>Note:</strong> do not invoke this method from
3719     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3720     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3721     *
3722     * @param child the child view to add
3723     * @param index the position at which to add the child
3724     * @param params the layout parameters to set on the child
3725     */
3726    public void addView(View child, int index, LayoutParams params) {
3727        if (DBG) {
3728            System.out.println(this + " addView");
3729        }
3730
3731        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
3732        // therefore, we call requestLayout() on ourselves before, so that the child's request
3733        // will be blocked at our level
3734        requestLayout();
3735        invalidate(true);
3736        addViewInner(child, index, params, false);
3737    }
3738
3739    /**
3740     * {@inheritDoc}
3741     */
3742    public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
3743        if (!checkLayoutParams(params)) {
3744            throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this);
3745        }
3746        if (view.mParent != this) {
3747            throw new IllegalArgumentException("Given view not a child of " + this);
3748        }
3749        view.setLayoutParams(params);
3750    }
3751
3752    /**
3753     * {@inheritDoc}
3754     */
3755    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
3756        return  p != null;
3757    }
3758
3759    /**
3760     * Interface definition for a callback to be invoked when the hierarchy
3761     * within this view changed. The hierarchy changes whenever a child is added
3762     * to or removed from this view.
3763     */
3764    public interface OnHierarchyChangeListener {
3765        /**
3766         * Called when a new child is added to a parent view.
3767         *
3768         * @param parent the view in which a child was added
3769         * @param child the new child view added in the hierarchy
3770         */
3771        void onChildViewAdded(View parent, View child);
3772
3773        /**
3774         * Called when a child is removed from a parent view.
3775         *
3776         * @param parent the view from which the child was removed
3777         * @param child the child removed from the hierarchy
3778         */
3779        void onChildViewRemoved(View parent, View child);
3780    }
3781
3782    /**
3783     * Register a callback to be invoked when a child is added to or removed
3784     * from this view.
3785     *
3786     * @param listener the callback to invoke on hierarchy change
3787     */
3788    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
3789        mOnHierarchyChangeListener = listener;
3790    }
3791
3792    /**
3793     * @hide
3794     */
3795    protected void onViewAdded(View child) {
3796        if (mOnHierarchyChangeListener != null) {
3797            mOnHierarchyChangeListener.onChildViewAdded(this, child);
3798        }
3799    }
3800
3801    /**
3802     * @hide
3803     */
3804    protected void onViewRemoved(View child) {
3805        if (mOnHierarchyChangeListener != null) {
3806            mOnHierarchyChangeListener.onChildViewRemoved(this, child);
3807        }
3808    }
3809
3810    private void clearCachedLayoutMode() {
3811        if (!hasBooleanFlag(FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET)) {
3812           mLayoutMode = LAYOUT_MODE_UNDEFINED;
3813        }
3814    }
3815
3816    @Override
3817    protected void onAttachedToWindow() {
3818        super.onAttachedToWindow();
3819        clearCachedLayoutMode();
3820    }
3821
3822    @Override
3823    protected void onDetachedFromWindow() {
3824        super.onDetachedFromWindow();
3825        clearCachedLayoutMode();
3826    }
3827
3828    /**
3829     * Adds a view during layout. This is useful if in your onLayout() method,
3830     * you need to add more views (as does the list view for example).
3831     *
3832     * If index is negative, it means put it at the end of the list.
3833     *
3834     * @param child the view to add to the group
3835     * @param index the index at which the child must be added
3836     * @param params the layout parameters to associate with the child
3837     * @return true if the child was added, false otherwise
3838     */
3839    protected boolean addViewInLayout(View child, int index, LayoutParams params) {
3840        return addViewInLayout(child, index, params, false);
3841    }
3842
3843    /**
3844     * Adds a view during layout. This is useful if in your onLayout() method,
3845     * you need to add more views (as does the list view for example).
3846     *
3847     * If index is negative, it means put it at the end of the list.
3848     *
3849     * @param child the view to add to the group
3850     * @param index the index at which the child must be added
3851     * @param params the layout parameters to associate with the child
3852     * @param preventRequestLayout if true, calling this method will not trigger a
3853     *        layout request on child
3854     * @return true if the child was added, false otherwise
3855     */
3856    protected boolean addViewInLayout(View child, int index, LayoutParams params,
3857            boolean preventRequestLayout) {
3858        child.mParent = null;
3859        addViewInner(child, index, params, preventRequestLayout);
3860        child.mPrivateFlags = (child.mPrivateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
3861        return true;
3862    }
3863
3864    /**
3865     * Prevents the specified child to be laid out during the next layout pass.
3866     *
3867     * @param child the child on which to perform the cleanup
3868     */
3869    protected void cleanupLayoutState(View child) {
3870        child.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
3871    }
3872
3873    private void addViewInner(View child, int index, LayoutParams params,
3874            boolean preventRequestLayout) {
3875
3876        if (mTransition != null) {
3877            // Don't prevent other add transitions from completing, but cancel remove
3878            // transitions to let them complete the process before we add to the container
3879            mTransition.cancel(LayoutTransition.DISAPPEARING);
3880        }
3881
3882        if (child.getParent() != null) {
3883            throw new IllegalStateException("The specified child already has a parent. " +
3884                    "You must call removeView() on the child's parent first.");
3885        }
3886
3887        if (mTransition != null) {
3888            mTransition.addChild(this, child);
3889        }
3890
3891        if (!checkLayoutParams(params)) {
3892            params = generateLayoutParams(params);
3893        }
3894
3895        if (preventRequestLayout) {
3896            child.mLayoutParams = params;
3897        } else {
3898            child.setLayoutParams(params);
3899        }
3900
3901        if (index < 0) {
3902            index = mChildrenCount;
3903        }
3904
3905        addInArray(child, index);
3906
3907        // tell our children
3908        if (preventRequestLayout) {
3909            child.assignParent(this);
3910        } else {
3911            child.mParent = this;
3912        }
3913
3914        if (child.hasFocus()) {
3915            requestChildFocus(child, child.findFocus());
3916        }
3917
3918        AttachInfo ai = mAttachInfo;
3919        if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
3920            boolean lastKeepOn = ai.mKeepScreenOn;
3921            ai.mKeepScreenOn = false;
3922            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
3923            if (ai.mKeepScreenOn) {
3924                needGlobalAttributesUpdate(true);
3925            }
3926            ai.mKeepScreenOn = lastKeepOn;
3927        }
3928
3929        if (child.isLayoutDirectionInherited()) {
3930            child.resetRtlProperties();
3931        }
3932
3933        onViewAdded(child);
3934
3935        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
3936            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
3937        }
3938
3939        if (child.hasTransientState()) {
3940            childHasTransientStateChanged(child, true);
3941        }
3942
3943        if (child.getVisibility() != View.GONE) {
3944            notifySubtreeAccessibilityStateChangedIfNeeded();
3945        }
3946    }
3947
3948    private void addInArray(View child, int index) {
3949        View[] children = mChildren;
3950        final int count = mChildrenCount;
3951        final int size = children.length;
3952        if (index == count) {
3953            if (size == count) {
3954                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3955                System.arraycopy(children, 0, mChildren, 0, size);
3956                children = mChildren;
3957            }
3958            children[mChildrenCount++] = child;
3959        } else if (index < count) {
3960            if (size == count) {
3961                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3962                System.arraycopy(children, 0, mChildren, 0, index);
3963                System.arraycopy(children, index, mChildren, index + 1, count - index);
3964                children = mChildren;
3965            } else {
3966                System.arraycopy(children, index, children, index + 1, count - index);
3967            }
3968            children[index] = child;
3969            mChildrenCount++;
3970            if (mLastTouchDownIndex >= index) {
3971                mLastTouchDownIndex++;
3972            }
3973        } else {
3974            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
3975        }
3976    }
3977
3978    // This method also sets the child's mParent to null
3979    private void removeFromArray(int index) {
3980        final View[] children = mChildren;
3981        if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
3982            children[index].mParent = null;
3983        }
3984        final int count = mChildrenCount;
3985        if (index == count - 1) {
3986            children[--mChildrenCount] = null;
3987        } else if (index >= 0 && index < count) {
3988            System.arraycopy(children, index + 1, children, index, count - index - 1);
3989            children[--mChildrenCount] = null;
3990        } else {
3991            throw new IndexOutOfBoundsException();
3992        }
3993        if (mLastTouchDownIndex == index) {
3994            mLastTouchDownTime = 0;
3995            mLastTouchDownIndex = -1;
3996        } else if (mLastTouchDownIndex > index) {
3997            mLastTouchDownIndex--;
3998        }
3999    }
4000
4001    // This method also sets the children's mParent to null
4002    private void removeFromArray(int start, int count) {
4003        final View[] children = mChildren;
4004        final int childrenCount = mChildrenCount;
4005
4006        start = Math.max(0, start);
4007        final int end = Math.min(childrenCount, start + count);
4008
4009        if (start == end) {
4010            return;
4011        }
4012
4013        if (end == childrenCount) {
4014            for (int i = start; i < end; i++) {
4015                children[i].mParent = null;
4016                children[i] = null;
4017            }
4018        } else {
4019            for (int i = start; i < end; i++) {
4020                children[i].mParent = null;
4021            }
4022
4023            // Since we're looping above, we might as well do the copy, but is arraycopy()
4024            // faster than the extra 2 bounds checks we would do in the loop?
4025            System.arraycopy(children, end, children, start, childrenCount - end);
4026
4027            for (int i = childrenCount - (end - start); i < childrenCount; i++) {
4028                children[i] = null;
4029            }
4030        }
4031
4032        mChildrenCount -= (end - start);
4033    }
4034
4035    private void bindLayoutAnimation(View child) {
4036        Animation a = mLayoutAnimationController.getAnimationForView(child);
4037        child.setAnimation(a);
4038    }
4039
4040    /**
4041     * Subclasses should override this method to set layout animation
4042     * parameters on the supplied child.
4043     *
4044     * @param child the child to associate with animation parameters
4045     * @param params the child's layout parameters which hold the animation
4046     *        parameters
4047     * @param index the index of the child in the view group
4048     * @param count the number of children in the view group
4049     */
4050    protected void attachLayoutAnimationParameters(View child,
4051            LayoutParams params, int index, int count) {
4052        LayoutAnimationController.AnimationParameters animationParams =
4053                    params.layoutAnimationParameters;
4054        if (animationParams == null) {
4055            animationParams = new LayoutAnimationController.AnimationParameters();
4056            params.layoutAnimationParameters = animationParams;
4057        }
4058
4059        animationParams.count = count;
4060        animationParams.index = index;
4061    }
4062
4063    /**
4064     * {@inheritDoc}
4065     *
4066     * <p><strong>Note:</strong> do not invoke this method from
4067     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
4068     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
4069     */
4070    public void removeView(View view) {
4071        removeViewInternal(view);
4072        requestLayout();
4073        invalidate(true);
4074    }
4075
4076    /**
4077     * Removes a view during layout. This is useful if in your onLayout() method,
4078     * you need to remove more views.
4079     *
4080     * <p><strong>Note:</strong> do not invoke this method from
4081     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
4082     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
4083     *
4084     * @param view the view to remove from the group
4085     */
4086    public void removeViewInLayout(View view) {
4087        removeViewInternal(view);
4088    }
4089
4090    /**
4091     * Removes a range of views during layout. This is useful if in your onLayout() method,
4092     * you need to remove more views.
4093     *
4094     * <p><strong>Note:</strong> do not invoke this method from
4095     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
4096     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
4097     *
4098     * @param start the index of the first view to remove from the group
4099     * @param count the number of views to remove from the group
4100     */
4101    public void removeViewsInLayout(int start, int count) {
4102        removeViewsInternal(start, count);
4103    }
4104
4105    /**
4106     * Removes the view at the specified position in the group.
4107     *
4108     * <p><strong>Note:</strong> do not invoke this method from
4109     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
4110     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
4111     *
4112     * @param index the position in the group of the view to remove
4113     */
4114    public void removeViewAt(int index) {
4115        removeViewInternal(index, getChildAt(index));
4116        requestLayout();
4117        invalidate(true);
4118    }
4119
4120    /**
4121     * Removes the specified range of views from the group.
4122     *
4123     * <p><strong>Note:</strong> do not invoke this method from
4124     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
4125     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
4126     *
4127     * @param start the first position in the group of the range of views to remove
4128     * @param count the number of views to remove
4129     */
4130    public void removeViews(int start, int count) {
4131        removeViewsInternal(start, count);
4132        requestLayout();
4133        invalidate(true);
4134    }
4135
4136    private void removeViewInternal(View view) {
4137        final int index = indexOfChild(view);
4138        if (index >= 0) {
4139            removeViewInternal(index, view);
4140        }
4141    }
4142
4143    private void removeViewInternal(int index, View view) {
4144
4145        if (mTransition != null) {
4146            mTransition.removeChild(this, view);
4147        }
4148
4149        boolean clearChildFocus = false;
4150        if (view == mFocused) {
4151            view.unFocus(null);
4152            clearChildFocus = true;
4153        }
4154
4155        if (view.isAccessibilityFocused()) {
4156            view.clearAccessibilityFocus();
4157        }
4158
4159        cancelTouchTarget(view);
4160        cancelHoverTarget(view);
4161
4162        if (view.getAnimation() != null ||
4163                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
4164            addDisappearingView(view);
4165        } else if (view.mAttachInfo != null) {
4166           view.dispatchDetachedFromWindow();
4167        }
4168
4169        if (view.hasTransientState()) {
4170            childHasTransientStateChanged(view, false);
4171        }
4172
4173        needGlobalAttributesUpdate(false);
4174
4175        removeFromArray(index);
4176
4177        if (clearChildFocus) {
4178            clearChildFocus(view);
4179            if (!rootViewRequestFocus()) {
4180                notifyGlobalFocusCleared(this);
4181            }
4182        }
4183
4184        onViewRemoved(view);
4185
4186        if (view.getVisibility() != View.GONE) {
4187            notifySubtreeAccessibilityStateChangedIfNeeded();
4188        }
4189    }
4190
4191    /**
4192     * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
4193     * not null, changes in layout which occur because of children being added to or removed from
4194     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
4195     * object. By default, the transition object is null (so layout changes are not animated).
4196     *
4197     * <p>Replacing a non-null transition will cause that previous transition to be
4198     * canceled, if it is currently running, to restore this container to
4199     * its correct post-transition state.</p>
4200     *
4201     * @param transition The LayoutTransition object that will animated changes in layout. A value
4202     * of <code>null</code> means no transition will run on layout changes.
4203     * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
4204     */
4205    public void setLayoutTransition(LayoutTransition transition) {
4206        if (mTransition != null) {
4207            LayoutTransition previousTransition = mTransition;
4208            previousTransition.cancel();
4209            previousTransition.removeTransitionListener(mLayoutTransitionListener);
4210        }
4211        mTransition = transition;
4212        if (mTransition != null) {
4213            mTransition.addTransitionListener(mLayoutTransitionListener);
4214        }
4215    }
4216
4217    /**
4218     * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
4219     * not null, changes in layout which occur because of children being added to or removed from
4220     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
4221     * object. By default, the transition object is null (so layout changes are not animated).
4222     *
4223     * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
4224     * A value of <code>null</code> means no transition will run on layout changes.
4225     */
4226    public LayoutTransition getLayoutTransition() {
4227        return mTransition;
4228    }
4229
4230    private void removeViewsInternal(int start, int count) {
4231        final View focused = mFocused;
4232        final boolean detach = mAttachInfo != null;
4233        boolean clearChildFocus = false;
4234
4235        final View[] children = mChildren;
4236        final int end = start + count;
4237
4238        for (int i = start; i < end; i++) {
4239            final View view = children[i];
4240
4241            if (mTransition != null) {
4242                mTransition.removeChild(this, view);
4243            }
4244
4245            if (view == focused) {
4246                view.unFocus(null);
4247                clearChildFocus = true;
4248            }
4249
4250            if (view.isAccessibilityFocused()) {
4251                view.clearAccessibilityFocus();
4252            }
4253
4254            cancelTouchTarget(view);
4255            cancelHoverTarget(view);
4256
4257            if (view.getAnimation() != null ||
4258                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
4259                addDisappearingView(view);
4260            } else if (detach) {
4261               view.dispatchDetachedFromWindow();
4262            }
4263
4264            if (view.hasTransientState()) {
4265                childHasTransientStateChanged(view, false);
4266            }
4267
4268            needGlobalAttributesUpdate(false);
4269
4270            onViewRemoved(view);
4271        }
4272
4273        removeFromArray(start, count);
4274
4275        if (clearChildFocus) {
4276            clearChildFocus(focused);
4277            if (!rootViewRequestFocus()) {
4278                notifyGlobalFocusCleared(focused);
4279            }
4280        }
4281    }
4282
4283    /**
4284     * Call this method to remove all child views from the
4285     * ViewGroup.
4286     *
4287     * <p><strong>Note:</strong> do not invoke this method from
4288     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
4289     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
4290     */
4291    public void removeAllViews() {
4292        removeAllViewsInLayout();
4293        requestLayout();
4294        invalidate(true);
4295    }
4296
4297    /**
4298     * Called by a ViewGroup subclass to remove child views from itself,
4299     * when it must first know its size on screen before it can calculate how many
4300     * child views it will render. An example is a Gallery or a ListView, which
4301     * may "have" 50 children, but actually only render the number of children
4302     * that can currently fit inside the object on screen. Do not call
4303     * this method unless you are extending ViewGroup and understand the
4304     * view measuring and layout pipeline.
4305     *
4306     * <p><strong>Note:</strong> do not invoke this method from
4307     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
4308     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
4309     */
4310    public void removeAllViewsInLayout() {
4311        final int count = mChildrenCount;
4312        if (count <= 0) {
4313            return;
4314        }
4315
4316        final View[] children = mChildren;
4317        mChildrenCount = 0;
4318
4319        final View focused = mFocused;
4320        final boolean detach = mAttachInfo != null;
4321        boolean clearChildFocus = false;
4322
4323        needGlobalAttributesUpdate(false);
4324
4325        for (int i = count - 1; i >= 0; i--) {
4326            final View view = children[i];
4327
4328            if (mTransition != null) {
4329                mTransition.removeChild(this, view);
4330            }
4331
4332            if (view == focused) {
4333                view.unFocus(null);
4334                clearChildFocus = true;
4335            }
4336
4337            if (view.isAccessibilityFocused()) {
4338                view.clearAccessibilityFocus();
4339            }
4340
4341            cancelTouchTarget(view);
4342            cancelHoverTarget(view);
4343
4344            if (view.getAnimation() != null ||
4345                    (mTransitioningViews != null && mTransitioningViews.contains(view))) {
4346                addDisappearingView(view);
4347            } else if (detach) {
4348               view.dispatchDetachedFromWindow();
4349            }
4350
4351            if (view.hasTransientState()) {
4352                childHasTransientStateChanged(view, false);
4353            }
4354
4355            onViewRemoved(view);
4356
4357            view.mParent = null;
4358            children[i] = null;
4359        }
4360
4361        if (clearChildFocus) {
4362            clearChildFocus(focused);
4363            if (!rootViewRequestFocus()) {
4364                notifyGlobalFocusCleared(focused);
4365            }
4366        }
4367    }
4368
4369    /**
4370     * Finishes the removal of a detached view. This method will dispatch the detached from
4371     * window event and notify the hierarchy change listener.
4372     * <p>
4373     * This method is intended to be lightweight and makes no assumptions about whether the
4374     * parent or child should be redrawn. Proper use of this method will include also making
4375     * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls.
4376     * For example, callers can {@link #post(Runnable) post} a {@link Runnable}
4377     * which performs a {@link #requestLayout()} on the next frame, after all detach/remove
4378     * calls are finished, causing layout to be run prior to redrawing the view hierarchy.
4379     *
4380     * @param child the child to be definitely removed from the view hierarchy
4381     * @param animate if true and the view has an animation, the view is placed in the
4382     *                disappearing views list, otherwise, it is detached from the window
4383     *
4384     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4385     * @see #detachAllViewsFromParent()
4386     * @see #detachViewFromParent(View)
4387     * @see #detachViewFromParent(int)
4388     */
4389    protected void removeDetachedView(View child, boolean animate) {
4390        if (mTransition != null) {
4391            mTransition.removeChild(this, child);
4392        }
4393
4394        if (child == mFocused) {
4395            child.clearFocus();
4396        }
4397
4398        child.clearAccessibilityFocus();
4399
4400        cancelTouchTarget(child);
4401        cancelHoverTarget(child);
4402
4403        if ((animate && child.getAnimation() != null) ||
4404                (mTransitioningViews != null && mTransitioningViews.contains(child))) {
4405            addDisappearingView(child);
4406        } else if (child.mAttachInfo != null) {
4407            child.dispatchDetachedFromWindow();
4408        }
4409
4410        if (child.hasTransientState()) {
4411            childHasTransientStateChanged(child, false);
4412        }
4413
4414        onViewRemoved(child);
4415    }
4416
4417    /**
4418     * Attaches a view to this view group. Attaching a view assigns this group as the parent,
4419     * sets the layout parameters and puts the view in the list of children so that
4420     * it can be retrieved by calling {@link #getChildAt(int)}.
4421     * <p>
4422     * This method is intended to be lightweight and makes no assumptions about whether the
4423     * parent or child should be redrawn. Proper use of this method will include also making
4424     * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls.
4425     * For example, callers can {@link #post(Runnable) post} a {@link Runnable}
4426     * which performs a {@link #requestLayout()} on the next frame, after all detach/attach
4427     * calls are finished, causing layout to be run prior to redrawing the view hierarchy.
4428     * <p>
4429     * This method should be called only for views which were detached from their parent.
4430     *
4431     * @param child the child to attach
4432     * @param index the index at which the child should be attached
4433     * @param params the layout parameters of the child
4434     *
4435     * @see #removeDetachedView(View, boolean)
4436     * @see #detachAllViewsFromParent()
4437     * @see #detachViewFromParent(View)
4438     * @see #detachViewFromParent(int)
4439     */
4440    protected void attachViewToParent(View child, int index, LayoutParams params) {
4441        child.mLayoutParams = params;
4442
4443        if (index < 0) {
4444            index = mChildrenCount;
4445        }
4446
4447        addInArray(child, index);
4448
4449        child.mParent = this;
4450        child.mPrivateFlags = (child.mPrivateFlags & ~PFLAG_DIRTY_MASK
4451                        & ~PFLAG_DRAWING_CACHE_VALID)
4452                | PFLAG_DRAWN | PFLAG_INVALIDATED;
4453        this.mPrivateFlags |= PFLAG_INVALIDATED;
4454
4455        if (child.hasFocus()) {
4456            requestChildFocus(child, child.findFocus());
4457        }
4458    }
4459
4460    /**
4461     * Detaches a view from its parent. Detaching a view should be followed
4462     * either by a call to
4463     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4464     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4465     * temporary; reattachment or removal should happen within the same drawing cycle as
4466     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4467     * call to {@link #getChildAt(int)}.
4468     *
4469     * @param child the child to detach
4470     *
4471     * @see #detachViewFromParent(int)
4472     * @see #detachViewsFromParent(int, int)
4473     * @see #detachAllViewsFromParent()
4474     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4475     * @see #removeDetachedView(View, boolean)
4476     */
4477    protected void detachViewFromParent(View child) {
4478        removeFromArray(indexOfChild(child));
4479    }
4480
4481    /**
4482     * Detaches a view from its parent. Detaching a view should be followed
4483     * either by a call to
4484     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4485     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4486     * temporary; reattachment or removal should happen within the same drawing cycle as
4487     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4488     * call to {@link #getChildAt(int)}.
4489     *
4490     * @param index the index of the child to detach
4491     *
4492     * @see #detachViewFromParent(View)
4493     * @see #detachAllViewsFromParent()
4494     * @see #detachViewsFromParent(int, int)
4495     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4496     * @see #removeDetachedView(View, boolean)
4497     */
4498    protected void detachViewFromParent(int index) {
4499        removeFromArray(index);
4500    }
4501
4502    /**
4503     * Detaches a range of views from their parents. Detaching a view should be followed
4504     * either by a call to
4505     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4506     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4507     * temporary; reattachment or removal should happen within the same drawing cycle as
4508     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4509     * call to {@link #getChildAt(int)}.
4510     *
4511     * @param start the first index of the childrend range to detach
4512     * @param count the number of children to detach
4513     *
4514     * @see #detachViewFromParent(View)
4515     * @see #detachViewFromParent(int)
4516     * @see #detachAllViewsFromParent()
4517     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4518     * @see #removeDetachedView(View, boolean)
4519     */
4520    protected void detachViewsFromParent(int start, int count) {
4521        removeFromArray(start, count);
4522    }
4523
4524    /**
4525     * Detaches all views from the parent. Detaching a view should be followed
4526     * either by a call to
4527     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4528     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4529     * temporary; reattachment or removal should happen within the same drawing cycle as
4530     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4531     * call to {@link #getChildAt(int)}.
4532     *
4533     * @see #detachViewFromParent(View)
4534     * @see #detachViewFromParent(int)
4535     * @see #detachViewsFromParent(int, int)
4536     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4537     * @see #removeDetachedView(View, boolean)
4538     */
4539    protected void detachAllViewsFromParent() {
4540        final int count = mChildrenCount;
4541        if (count <= 0) {
4542            return;
4543        }
4544
4545        final View[] children = mChildren;
4546        mChildrenCount = 0;
4547
4548        for (int i = count - 1; i >= 0; i--) {
4549            children[i].mParent = null;
4550            children[i] = null;
4551        }
4552    }
4553
4554    /**
4555     * Don't call or override this method. It is used for the implementation of
4556     * the view hierarchy.
4557     */
4558    public final void invalidateChild(View child, final Rect dirty) {
4559        ViewParent parent = this;
4560
4561        final AttachInfo attachInfo = mAttachInfo;
4562        if (attachInfo != null) {
4563            // If the child is drawing an animation, we want to copy this flag onto
4564            // ourselves and the parent to make sure the invalidate request goes
4565            // through
4566            final boolean drawAnimation = (child.mPrivateFlags & PFLAG_DRAW_ANIMATION)
4567                    == PFLAG_DRAW_ANIMATION;
4568
4569            // Check whether the child that requests the invalidate is fully opaque
4570            // Views being animated or transformed are not considered opaque because we may
4571            // be invalidating their old position and need the parent to paint behind them.
4572            Matrix childMatrix = child.getMatrix();
4573            final boolean isOpaque = child.isOpaque() && !drawAnimation &&
4574                    child.getAnimation() == null && childMatrix.isIdentity();
4575            // Mark the child as dirty, using the appropriate flag
4576            // Make sure we do not set both flags at the same time
4577            int opaqueFlag = isOpaque ? PFLAG_DIRTY_OPAQUE : PFLAG_DIRTY;
4578
4579            if (child.mLayerType != LAYER_TYPE_NONE) {
4580                mPrivateFlags |= PFLAG_INVALIDATED;
4581                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
4582            }
4583
4584            final int[] location = attachInfo.mInvalidateChildLocation;
4585            location[CHILD_LEFT_INDEX] = child.mLeft;
4586            location[CHILD_TOP_INDEX] = child.mTop;
4587            if (!childMatrix.isIdentity() ||
4588                    (mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
4589                RectF boundingRect = attachInfo.mTmpTransformRect;
4590                boundingRect.set(dirty);
4591                Matrix transformMatrix;
4592                if ((mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
4593                    Transformation t = attachInfo.mTmpTransformation;
4594                    boolean transformed = getChildStaticTransformation(child, t);
4595                    if (transformed) {
4596                        transformMatrix = attachInfo.mTmpMatrix;
4597                        transformMatrix.set(t.getMatrix());
4598                        if (!childMatrix.isIdentity()) {
4599                            transformMatrix.preConcat(childMatrix);
4600                        }
4601                    } else {
4602                        transformMatrix = childMatrix;
4603                    }
4604                } else {
4605                    transformMatrix = childMatrix;
4606                }
4607                transformMatrix.mapRect(boundingRect);
4608                dirty.set((int) (boundingRect.left - 0.5f),
4609                        (int) (boundingRect.top - 0.5f),
4610                        (int) (boundingRect.right + 0.5f),
4611                        (int) (boundingRect.bottom + 0.5f));
4612            }
4613
4614            do {
4615                View view = null;
4616                if (parent instanceof View) {
4617                    view = (View) parent;
4618                }
4619
4620                if (drawAnimation) {
4621                    if (view != null) {
4622                        view.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
4623                    } else if (parent instanceof ViewRootImpl) {
4624                        ((ViewRootImpl) parent).mIsAnimating = true;
4625                    }
4626                }
4627
4628                // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
4629                // flag coming from the child that initiated the invalidate
4630                if (view != null) {
4631                    if ((view.mViewFlags & FADING_EDGE_MASK) != 0 &&
4632                            view.getSolidColor() == 0) {
4633                        opaqueFlag = PFLAG_DIRTY;
4634                    }
4635                    if ((view.mPrivateFlags & PFLAG_DIRTY_MASK) != PFLAG_DIRTY) {
4636                        view.mPrivateFlags = (view.mPrivateFlags & ~PFLAG_DIRTY_MASK) | opaqueFlag;
4637                    }
4638                }
4639
4640                parent = parent.invalidateChildInParent(location, dirty);
4641                if (view != null) {
4642                    // Account for transform on current parent
4643                    Matrix m = view.getMatrix();
4644                    if (!m.isIdentity()) {
4645                        RectF boundingRect = attachInfo.mTmpTransformRect;
4646                        boundingRect.set(dirty);
4647                        m.mapRect(boundingRect);
4648                        dirty.set((int) (boundingRect.left - 0.5f),
4649                                (int) (boundingRect.top - 0.5f),
4650                                (int) (boundingRect.right + 0.5f),
4651                                (int) (boundingRect.bottom + 0.5f));
4652                    }
4653                }
4654            } while (parent != null);
4655        }
4656    }
4657
4658    /**
4659     * Don't call or override this method. It is used for the implementation of
4660     * the view hierarchy.
4661     *
4662     * This implementation returns null if this ViewGroup does not have a parent,
4663     * if this ViewGroup is already fully invalidated or if the dirty rectangle
4664     * does not intersect with this ViewGroup's bounds.
4665     */
4666    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
4667        if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN ||
4668                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) {
4669            if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
4670                        FLAG_OPTIMIZE_INVALIDATE) {
4671                dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
4672                        location[CHILD_TOP_INDEX] - mScrollY);
4673                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0) {
4674                    dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
4675                }
4676
4677                final int left = mLeft;
4678                final int top = mTop;
4679
4680                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
4681                    if (!dirty.intersect(0, 0, mRight - left, mBottom - top)) {
4682                        dirty.setEmpty();
4683                    }
4684                }
4685                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
4686
4687                location[CHILD_LEFT_INDEX] = left;
4688                location[CHILD_TOP_INDEX] = top;
4689
4690                if (mLayerType != LAYER_TYPE_NONE) {
4691                    mPrivateFlags |= PFLAG_INVALIDATED;
4692                }
4693
4694                return mParent;
4695
4696            } else {
4697                mPrivateFlags &= ~PFLAG_DRAWN & ~PFLAG_DRAWING_CACHE_VALID;
4698
4699                location[CHILD_LEFT_INDEX] = mLeft;
4700                location[CHILD_TOP_INDEX] = mTop;
4701                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
4702                    dirty.set(0, 0, mRight - mLeft, mBottom - mTop);
4703                } else {
4704                    // in case the dirty rect extends outside the bounds of this container
4705                    dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
4706                }
4707
4708                if (mLayerType != LAYER_TYPE_NONE) {
4709                    mPrivateFlags |= PFLAG_INVALIDATED;
4710                }
4711
4712                return mParent;
4713            }
4714        }
4715
4716        return null;
4717    }
4718
4719    /**
4720     * Native-calculated damage path
4721     * Returns false if this path was unable to complete successfully. This means
4722     * it hit a ViewParent it doesn't recognize and needs to fall back to calculating
4723     * damage area
4724     * @hide
4725     */
4726    public boolean damageChildDeferred(View child) {
4727        ViewParent parent = getParent();
4728        while (parent != null) {
4729            if (parent instanceof ViewGroup) {
4730                parent = parent.getParent();
4731            } else if (parent instanceof ViewRootImpl) {
4732                ((ViewRootImpl) parent).invalidate();
4733                return true;
4734            } else {
4735                parent = null;
4736            }
4737        }
4738        return false;
4739    }
4740
4741    /**
4742     * Quick invalidation method called by View.invalidateViewProperty. This doesn't set the
4743     * DRAWN flags and doesn't handle the Animation logic that the default invalidation methods
4744     * do; all we want to do here is schedule a traversal with the appropriate dirty rect.
4745     *
4746     * @hide
4747     */
4748    public void damageChild(View child, final Rect dirty) {
4749        if (damageChildDeferred(child)) {
4750            return;
4751        }
4752
4753        ViewParent parent = this;
4754
4755        final AttachInfo attachInfo = mAttachInfo;
4756        if (attachInfo != null) {
4757            int left = child.mLeft;
4758            int top = child.mTop;
4759            if (!child.getMatrix().isIdentity()) {
4760                child.transformRect(dirty);
4761            }
4762
4763            do {
4764                if (parent instanceof ViewGroup) {
4765                    ViewGroup parentVG = (ViewGroup) parent;
4766                    if (parentVG.mLayerType != LAYER_TYPE_NONE) {
4767                        // Layered parents should be recreated, not just re-issued
4768                        parentVG.invalidate();
4769                        parent = null;
4770                    } else {
4771                        parent = parentVG.damageChildInParent(left, top, dirty);
4772                        left = parentVG.mLeft;
4773                        top = parentVG.mTop;
4774                    }
4775                } else {
4776                    // Reached the top; this calls into the usual invalidate method in
4777                    // ViewRootImpl, which schedules a traversal
4778                    final int[] location = attachInfo.mInvalidateChildLocation;
4779                    location[0] = left;
4780                    location[1] = top;
4781                    parent = parent.invalidateChildInParent(location, dirty);
4782                }
4783            } while (parent != null);
4784        }
4785    }
4786
4787    /**
4788     * Quick invalidation method that simply transforms the dirty rect into the parent's
4789     * coordinate system, pruning the invalidation if the parent has already been invalidated.
4790     *
4791     * @hide
4792     */
4793    protected ViewParent damageChildInParent(int left, int top, final Rect dirty) {
4794        if ((mPrivateFlags & PFLAG_DRAWN) != 0
4795                || (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) != 0) {
4796            dirty.offset(left - mScrollX, top - mScrollY);
4797            if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0) {
4798                dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
4799            }
4800
4801            if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0 ||
4802                    dirty.intersect(0, 0, mRight - mLeft, mBottom - mTop)) {
4803
4804                if (!getMatrix().isIdentity()) {
4805                    transformRect(dirty);
4806                }
4807
4808                return mParent;
4809            }
4810        }
4811
4812        return null;
4813    }
4814
4815    /**
4816     * Offset a rectangle that is in a descendant's coordinate
4817     * space into our coordinate space.
4818     * @param descendant A descendant of this view
4819     * @param rect A rectangle defined in descendant's coordinate space.
4820     */
4821    public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) {
4822        offsetRectBetweenParentAndChild(descendant, rect, true, false);
4823    }
4824
4825    /**
4826     * Offset a rectangle that is in our coordinate space into an ancestor's
4827     * coordinate space.
4828     * @param descendant A descendant of this view
4829     * @param rect A rectangle defined in descendant's coordinate space.
4830     */
4831    public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) {
4832        offsetRectBetweenParentAndChild(descendant, rect, false, false);
4833    }
4834
4835    /**
4836     * Helper method that offsets a rect either from parent to descendant or
4837     * descendant to parent.
4838     */
4839    void offsetRectBetweenParentAndChild(View descendant, Rect rect,
4840            boolean offsetFromChildToParent, boolean clipToBounds) {
4841
4842        // already in the same coord system :)
4843        if (descendant == this) {
4844            return;
4845        }
4846
4847        ViewParent theParent = descendant.mParent;
4848
4849        // search and offset up to the parent
4850        while ((theParent != null)
4851                && (theParent instanceof View)
4852                && (theParent != this)) {
4853
4854            if (offsetFromChildToParent) {
4855                rect.offset(descendant.mLeft - descendant.mScrollX,
4856                        descendant.mTop - descendant.mScrollY);
4857                if (clipToBounds) {
4858                    View p = (View) theParent;
4859                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4860                }
4861            } else {
4862                if (clipToBounds) {
4863                    View p = (View) theParent;
4864                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4865                }
4866                rect.offset(descendant.mScrollX - descendant.mLeft,
4867                        descendant.mScrollY - descendant.mTop);
4868            }
4869
4870            descendant = (View) theParent;
4871            theParent = descendant.mParent;
4872        }
4873
4874        // now that we are up to this view, need to offset one more time
4875        // to get into our coordinate space
4876        if (theParent == this) {
4877            if (offsetFromChildToParent) {
4878                rect.offset(descendant.mLeft - descendant.mScrollX,
4879                        descendant.mTop - descendant.mScrollY);
4880            } else {
4881                rect.offset(descendant.mScrollX - descendant.mLeft,
4882                        descendant.mScrollY - descendant.mTop);
4883            }
4884        } else {
4885            throw new IllegalArgumentException("parameter must be a descendant of this view");
4886        }
4887    }
4888
4889    /**
4890     * Offset the vertical location of all children of this view by the specified number of pixels.
4891     *
4892     * @param offset the number of pixels to offset
4893     *
4894     * @hide
4895     */
4896    public void offsetChildrenTopAndBottom(int offset) {
4897        final int count = mChildrenCount;
4898        final View[] children = mChildren;
4899        boolean invalidate = false;
4900
4901        for (int i = 0; i < count; i++) {
4902            final View v = children[i];
4903            v.mTop += offset;
4904            v.mBottom += offset;
4905            if (v.mRenderNode != null) {
4906                invalidate = true;
4907                v.mRenderNode.offsetTopAndBottom(offset);
4908            }
4909        }
4910
4911        if (invalidate) {
4912            invalidateViewProperty(false, false);
4913        }
4914        notifySubtreeAccessibilityStateChangedIfNeeded();
4915    }
4916
4917    /**
4918     * {@inheritDoc}
4919     */
4920    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
4921        // It doesn't make a whole lot of sense to call this on a view that isn't attached,
4922        // but for some simple tests it can be useful. If we don't have attach info this
4923        // will allocate memory.
4924        final RectF rect = mAttachInfo != null ? mAttachInfo.mTmpTransformRect : new RectF();
4925        rect.set(r);
4926
4927        if (!child.hasIdentityMatrix()) {
4928           child.getMatrix().mapRect(rect);
4929        }
4930
4931        int dx = child.mLeft - mScrollX;
4932        int dy = child.mTop - mScrollY;
4933
4934        rect.offset(dx, dy);
4935
4936        if (offset != null) {
4937            if (!child.hasIdentityMatrix()) {
4938                float[] position = mAttachInfo != null ? mAttachInfo.mTmpTransformLocation
4939                        : new float[2];
4940                position[0] = offset.x;
4941                position[1] = offset.y;
4942                child.getMatrix().mapPoints(position);
4943                offset.x = (int) (position[0] + 0.5f);
4944                offset.y = (int) (position[1] + 0.5f);
4945            }
4946            offset.x += dx;
4947            offset.y += dy;
4948        }
4949
4950        if (rect.intersect(0, 0, mRight - mLeft, mBottom - mTop)) {
4951            if (mParent == null) return true;
4952            r.set((int) (rect.left + 0.5f), (int) (rect.top + 0.5f),
4953                    (int) (rect.right + 0.5f), (int) (rect.bottom + 0.5f));
4954            return mParent.getChildVisibleRect(this, r, offset);
4955        }
4956
4957        return false;
4958    }
4959
4960    /**
4961     * {@inheritDoc}
4962     */
4963    @Override
4964    public final void layout(int l, int t, int r, int b) {
4965        if (!mSuppressLayout && (mTransition == null || !mTransition.isChangingLayout())) {
4966            if (mTransition != null) {
4967                mTransition.layoutChange(this);
4968            }
4969            super.layout(l, t, r, b);
4970        } else {
4971            // record the fact that we noop'd it; request layout when transition finishes
4972            mLayoutCalledWhileSuppressed = true;
4973        }
4974    }
4975
4976    /**
4977     * {@inheritDoc}
4978     */
4979    @Override
4980    protected abstract void onLayout(boolean changed,
4981            int l, int t, int r, int b);
4982
4983    /**
4984     * Indicates whether the view group has the ability to animate its children
4985     * after the first layout.
4986     *
4987     * @return true if the children can be animated, false otherwise
4988     */
4989    protected boolean canAnimate() {
4990        return mLayoutAnimationController != null;
4991    }
4992
4993    /**
4994     * Runs the layout animation. Calling this method triggers a relayout of
4995     * this view group.
4996     */
4997    public void startLayoutAnimation() {
4998        if (mLayoutAnimationController != null) {
4999            mGroupFlags |= FLAG_RUN_ANIMATION;
5000            requestLayout();
5001        }
5002    }
5003
5004    /**
5005     * Schedules the layout animation to be played after the next layout pass
5006     * of this view group. This can be used to restart the layout animation
5007     * when the content of the view group changes or when the activity is
5008     * paused and resumed.
5009     */
5010    public void scheduleLayoutAnimation() {
5011        mGroupFlags |= FLAG_RUN_ANIMATION;
5012    }
5013
5014    /**
5015     * Sets the layout animation controller used to animate the group's
5016     * children after the first layout.
5017     *
5018     * @param controller the animation controller
5019     */
5020    public void setLayoutAnimation(LayoutAnimationController controller) {
5021        mLayoutAnimationController = controller;
5022        if (mLayoutAnimationController != null) {
5023            mGroupFlags |= FLAG_RUN_ANIMATION;
5024        }
5025    }
5026
5027    /**
5028     * Returns the layout animation controller used to animate the group's
5029     * children.
5030     *
5031     * @return the current animation controller
5032     */
5033    public LayoutAnimationController getLayoutAnimation() {
5034        return mLayoutAnimationController;
5035    }
5036
5037    /**
5038     * Indicates whether the children's drawing cache is used during a layout
5039     * animation. By default, the drawing cache is enabled but this will prevent
5040     * nested layout animations from working. To nest animations, you must disable
5041     * the cache.
5042     *
5043     * @return true if the animation cache is enabled, false otherwise
5044     *
5045     * @see #setAnimationCacheEnabled(boolean)
5046     * @see View#setDrawingCacheEnabled(boolean)
5047     */
5048    @ViewDebug.ExportedProperty
5049    public boolean isAnimationCacheEnabled() {
5050        return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
5051    }
5052
5053    /**
5054     * Enables or disables the children's drawing cache during a layout animation.
5055     * By default, the drawing cache is enabled but this will prevent nested
5056     * layout animations from working. To nest animations, you must disable the
5057     * cache.
5058     *
5059     * @param enabled true to enable the animation cache, false otherwise
5060     *
5061     * @see #isAnimationCacheEnabled()
5062     * @see View#setDrawingCacheEnabled(boolean)
5063     */
5064    public void setAnimationCacheEnabled(boolean enabled) {
5065        setBooleanFlag(FLAG_ANIMATION_CACHE, enabled);
5066    }
5067
5068    /**
5069     * Indicates whether this ViewGroup will always try to draw its children using their
5070     * drawing cache. By default this property is enabled.
5071     *
5072     * @return true if the animation cache is enabled, false otherwise
5073     *
5074     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
5075     * @see #setChildrenDrawnWithCacheEnabled(boolean)
5076     * @see View#setDrawingCacheEnabled(boolean)
5077     */
5078    @ViewDebug.ExportedProperty(category = "drawing")
5079    public boolean isAlwaysDrawnWithCacheEnabled() {
5080        return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE;
5081    }
5082
5083    /**
5084     * Indicates whether this ViewGroup will always try to draw its children using their
5085     * drawing cache. This property can be set to true when the cache rendering is
5086     * slightly different from the children's normal rendering. Renderings can be different,
5087     * for instance, when the cache's quality is set to low.
5088     *
5089     * When this property is disabled, the ViewGroup will use the drawing cache of its
5090     * children only when asked to. It's usually the task of subclasses to tell ViewGroup
5091     * when to start using the drawing cache and when to stop using it.
5092     *
5093     * @param always true to always draw with the drawing cache, false otherwise
5094     *
5095     * @see #isAlwaysDrawnWithCacheEnabled()
5096     * @see #setChildrenDrawnWithCacheEnabled(boolean)
5097     * @see View#setDrawingCacheEnabled(boolean)
5098     * @see View#setDrawingCacheQuality(int)
5099     */
5100    public void setAlwaysDrawnWithCacheEnabled(boolean always) {
5101        setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always);
5102    }
5103
5104    /**
5105     * Indicates whether the ViewGroup is currently drawing its children using
5106     * their drawing cache.
5107     *
5108     * @return true if children should be drawn with their cache, false otherwise
5109     *
5110     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
5111     * @see #setChildrenDrawnWithCacheEnabled(boolean)
5112     */
5113    @ViewDebug.ExportedProperty(category = "drawing")
5114    protected boolean isChildrenDrawnWithCacheEnabled() {
5115        return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE;
5116    }
5117
5118    /**
5119     * Tells the ViewGroup to draw its children using their drawing cache. This property
5120     * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache
5121     * will be used only if it has been enabled.
5122     *
5123     * Subclasses should call this method to start and stop using the drawing cache when
5124     * they perform performance sensitive operations, like scrolling or animating.
5125     *
5126     * @param enabled true if children should be drawn with their cache, false otherwise
5127     *
5128     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
5129     * @see #isChildrenDrawnWithCacheEnabled()
5130     */
5131    protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
5132        setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled);
5133    }
5134
5135    /**
5136     * Indicates whether the ViewGroup is drawing its children in the order defined by
5137     * {@link #getChildDrawingOrder(int, int)}.
5138     *
5139     * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)},
5140     *         false otherwise
5141     *
5142     * @see #setChildrenDrawingOrderEnabled(boolean)
5143     * @see #getChildDrawingOrder(int, int)
5144     */
5145    @ViewDebug.ExportedProperty(category = "drawing")
5146    protected boolean isChildrenDrawingOrderEnabled() {
5147        return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER;
5148    }
5149
5150    /**
5151     * Tells the ViewGroup whether to draw its children in the order defined by the method
5152     * {@link #getChildDrawingOrder(int, int)}.
5153     * <p>
5154     * Note that {@link View#getZ() Z} reordering, done by {@link #dispatchDraw(Canvas)},
5155     * will override custom child ordering done via this method.
5156     *
5157     * @param enabled true if the order of the children when drawing is determined by
5158     *        {@link #getChildDrawingOrder(int, int)}, false otherwise
5159     *
5160     * @see #isChildrenDrawingOrderEnabled()
5161     * @see #getChildDrawingOrder(int, int)
5162     */
5163    protected void setChildrenDrawingOrderEnabled(boolean enabled) {
5164        setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled);
5165    }
5166
5167    private boolean hasBooleanFlag(int flag) {
5168        return (mGroupFlags & flag) == flag;
5169    }
5170
5171    private void setBooleanFlag(int flag, boolean value) {
5172        if (value) {
5173            mGroupFlags |= flag;
5174        } else {
5175            mGroupFlags &= ~flag;
5176        }
5177    }
5178
5179    /**
5180     * Returns an integer indicating what types of drawing caches are kept in memory.
5181     *
5182     * @see #setPersistentDrawingCache(int)
5183     * @see #setAnimationCacheEnabled(boolean)
5184     *
5185     * @return one or a combination of {@link #PERSISTENT_NO_CACHE},
5186     *         {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
5187     *         and {@link #PERSISTENT_ALL_CACHES}
5188     */
5189    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
5190        @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE,        to = "NONE"),
5191        @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"),
5192        @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"),
5193        @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES,      to = "ALL")
5194    })
5195    public int getPersistentDrawingCache() {
5196        return mPersistentDrawingCache;
5197    }
5198
5199    /**
5200     * Indicates what types of drawing caches should be kept in memory after
5201     * they have been created.
5202     *
5203     * @see #getPersistentDrawingCache()
5204     * @see #setAnimationCacheEnabled(boolean)
5205     *
5206     * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE},
5207     *        {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
5208     *        and {@link #PERSISTENT_ALL_CACHES}
5209     */
5210    public void setPersistentDrawingCache(int drawingCacheToKeep) {
5211        mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES;
5212    }
5213
5214    private void setLayoutMode(int layoutMode, boolean explicitly) {
5215        mLayoutMode = layoutMode;
5216        setBooleanFlag(FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET, explicitly);
5217    }
5218
5219    /**
5220     * Recursively traverse the view hierarchy, resetting the layoutMode of any
5221     * descendants that had inherited a different layoutMode from a previous parent.
5222     * Recursion terminates when a descendant's mode is:
5223     * <ul>
5224     *     <li>Undefined</li>
5225     *     <li>The same as the root node's</li>
5226     *     <li>A mode that had been explicitly set</li>
5227     * <ul/>
5228     * The first two clauses are optimizations.
5229     * @param layoutModeOfRoot
5230     */
5231    @Override
5232    void invalidateInheritedLayoutMode(int layoutModeOfRoot) {
5233        if (mLayoutMode == LAYOUT_MODE_UNDEFINED ||
5234            mLayoutMode == layoutModeOfRoot ||
5235            hasBooleanFlag(FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET)) {
5236            return;
5237        }
5238        setLayoutMode(LAYOUT_MODE_UNDEFINED, false);
5239
5240        // apply recursively
5241        for (int i = 0, N = getChildCount(); i < N; i++) {
5242            getChildAt(i).invalidateInheritedLayoutMode(layoutModeOfRoot);
5243        }
5244    }
5245
5246    /**
5247     * Returns the basis of alignment during layout operations on this ViewGroup:
5248     * either {@link #LAYOUT_MODE_CLIP_BOUNDS} or {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
5249     * <p>
5250     * If no layoutMode was explicitly set, either programmatically or in an XML resource,
5251     * the method returns the layoutMode of the view's parent ViewGroup if such a parent exists,
5252     * otherwise the method returns a default value of {@link #LAYOUT_MODE_CLIP_BOUNDS}.
5253     *
5254     * @return the layout mode to use during layout operations
5255     *
5256     * @see #setLayoutMode(int)
5257     */
5258    public int getLayoutMode() {
5259        if (mLayoutMode == LAYOUT_MODE_UNDEFINED) {
5260            int inheritedLayoutMode = (mParent instanceof ViewGroup) ?
5261                    ((ViewGroup) mParent).getLayoutMode() : LAYOUT_MODE_DEFAULT;
5262            setLayoutMode(inheritedLayoutMode, false);
5263        }
5264        return mLayoutMode;
5265    }
5266
5267    /**
5268     * Sets the basis of alignment during the layout of this ViewGroup.
5269     * Valid values are either {@link #LAYOUT_MODE_CLIP_BOUNDS} or
5270     * {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
5271     *
5272     * @param layoutMode the layout mode to use during layout operations
5273     *
5274     * @see #getLayoutMode()
5275     * @attr ref android.R.styleable#ViewGroup_layoutMode
5276     */
5277    public void setLayoutMode(int layoutMode) {
5278        if (mLayoutMode != layoutMode) {
5279            invalidateInheritedLayoutMode(layoutMode);
5280            setLayoutMode(layoutMode, layoutMode != LAYOUT_MODE_UNDEFINED);
5281            requestLayout();
5282        }
5283    }
5284
5285    /**
5286     * Returns a new set of layout parameters based on the supplied attributes set.
5287     *
5288     * @param attrs the attributes to build the layout parameters from
5289     *
5290     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
5291     *         of its descendants
5292     */
5293    public LayoutParams generateLayoutParams(AttributeSet attrs) {
5294        return new LayoutParams(getContext(), attrs);
5295    }
5296
5297    /**
5298     * Returns a safe set of layout parameters based on the supplied layout params.
5299     * When a ViewGroup is passed a View whose layout params do not pass the test of
5300     * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
5301     * is invoked. This method should return a new set of layout params suitable for
5302     * this ViewGroup, possibly by copying the appropriate attributes from the
5303     * specified set of layout params.
5304     *
5305     * @param p The layout parameters to convert into a suitable set of layout parameters
5306     *          for this ViewGroup.
5307     *
5308     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
5309     *         of its descendants
5310     */
5311    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
5312        return p;
5313    }
5314
5315    /**
5316     * Returns a set of default layout parameters. These parameters are requested
5317     * when the View passed to {@link #addView(View)} has no layout parameters
5318     * already set. If null is returned, an exception is thrown from addView.
5319     *
5320     * @return a set of default layout parameters or null
5321     */
5322    protected LayoutParams generateDefaultLayoutParams() {
5323        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
5324    }
5325
5326    /**
5327     * {@inheritDoc}
5328     */
5329    @Override
5330    protected void debug(int depth) {
5331        super.debug(depth);
5332        String output;
5333
5334        if (mFocused != null) {
5335            output = debugIndent(depth);
5336            output += "mFocused";
5337            Log.d(VIEW_LOG_TAG, output);
5338        }
5339        if (mChildrenCount != 0) {
5340            output = debugIndent(depth);
5341            output += "{";
5342            Log.d(VIEW_LOG_TAG, output);
5343        }
5344        int count = mChildrenCount;
5345        for (int i = 0; i < count; i++) {
5346            View child = mChildren[i];
5347            child.debug(depth + 1);
5348        }
5349
5350        if (mChildrenCount != 0) {
5351            output = debugIndent(depth);
5352            output += "}";
5353            Log.d(VIEW_LOG_TAG, output);
5354        }
5355    }
5356
5357    /**
5358     * Returns the position in the group of the specified child view.
5359     *
5360     * @param child the view for which to get the position
5361     * @return a positive integer representing the position of the view in the
5362     *         group, or -1 if the view does not exist in the group
5363     */
5364    public int indexOfChild(View child) {
5365        final int count = mChildrenCount;
5366        final View[] children = mChildren;
5367        for (int i = 0; i < count; i++) {
5368            if (children[i] == child) {
5369                return i;
5370            }
5371        }
5372        return -1;
5373    }
5374
5375    /**
5376     * Returns the number of children in the group.
5377     *
5378     * @return a positive integer representing the number of children in
5379     *         the group
5380     */
5381    public int getChildCount() {
5382        return mChildrenCount;
5383    }
5384
5385    /**
5386     * Returns the view at the specified position in the group.
5387     *
5388     * @param index the position at which to get the view from
5389     * @return the view at the specified position or null if the position
5390     *         does not exist within the group
5391     */
5392    public View getChildAt(int index) {
5393        if (index < 0 || index >= mChildrenCount) {
5394            return null;
5395        }
5396        return mChildren[index];
5397    }
5398
5399    /**
5400     * Ask all of the children of this view to measure themselves, taking into
5401     * account both the MeasureSpec requirements for this view and its padding.
5402     * We skip children that are in the GONE state The heavy lifting is done in
5403     * getChildMeasureSpec.
5404     *
5405     * @param widthMeasureSpec The width requirements for this view
5406     * @param heightMeasureSpec The height requirements for this view
5407     */
5408    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
5409        final int size = mChildrenCount;
5410        final View[] children = mChildren;
5411        for (int i = 0; i < size; ++i) {
5412            final View child = children[i];
5413            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
5414                measureChild(child, widthMeasureSpec, heightMeasureSpec);
5415            }
5416        }
5417    }
5418
5419    /**
5420     * Ask one of the children of this view to measure itself, taking into
5421     * account both the MeasureSpec requirements for this view and its padding.
5422     * The heavy lifting is done in getChildMeasureSpec.
5423     *
5424     * @param child The child to measure
5425     * @param parentWidthMeasureSpec The width requirements for this view
5426     * @param parentHeightMeasureSpec The height requirements for this view
5427     */
5428    protected void measureChild(View child, int parentWidthMeasureSpec,
5429            int parentHeightMeasureSpec) {
5430        final LayoutParams lp = child.getLayoutParams();
5431
5432        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
5433                mPaddingLeft + mPaddingRight, lp.width);
5434        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
5435                mPaddingTop + mPaddingBottom, lp.height);
5436
5437        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
5438    }
5439
5440    /**
5441     * Ask one of the children of this view to measure itself, taking into
5442     * account both the MeasureSpec requirements for this view and its padding
5443     * and margins. The child must have MarginLayoutParams The heavy lifting is
5444     * done in getChildMeasureSpec.
5445     *
5446     * @param child The child to measure
5447     * @param parentWidthMeasureSpec The width requirements for this view
5448     * @param widthUsed Extra space that has been used up by the parent
5449     *        horizontally (possibly by other children of the parent)
5450     * @param parentHeightMeasureSpec The height requirements for this view
5451     * @param heightUsed Extra space that has been used up by the parent
5452     *        vertically (possibly by other children of the parent)
5453     */
5454    protected void measureChildWithMargins(View child,
5455            int parentWidthMeasureSpec, int widthUsed,
5456            int parentHeightMeasureSpec, int heightUsed) {
5457        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
5458
5459        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
5460                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
5461                        + widthUsed, lp.width);
5462        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
5463                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
5464                        + heightUsed, lp.height);
5465
5466        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
5467    }
5468
5469    /**
5470     * Does the hard part of measureChildren: figuring out the MeasureSpec to
5471     * pass to a particular child. This method figures out the right MeasureSpec
5472     * for one dimension (height or width) of one child view.
5473     *
5474     * The goal is to combine information from our MeasureSpec with the
5475     * LayoutParams of the child to get the best possible results. For example,
5476     * if the this view knows its size (because its MeasureSpec has a mode of
5477     * EXACTLY), and the child has indicated in its LayoutParams that it wants
5478     * to be the same size as the parent, the parent should ask the child to
5479     * layout given an exact size.
5480     *
5481     * @param spec The requirements for this view
5482     * @param padding The padding of this view for the current dimension and
5483     *        margins, if applicable
5484     * @param childDimension How big the child wants to be in the current
5485     *        dimension
5486     * @return a MeasureSpec integer for the child
5487     */
5488    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
5489        int specMode = MeasureSpec.getMode(spec);
5490        int specSize = MeasureSpec.getSize(spec);
5491
5492        int size = Math.max(0, specSize - padding);
5493
5494        int resultSize = 0;
5495        int resultMode = 0;
5496
5497        switch (specMode) {
5498        // Parent has imposed an exact size on us
5499        case MeasureSpec.EXACTLY:
5500            if (childDimension >= 0) {
5501                resultSize = childDimension;
5502                resultMode = MeasureSpec.EXACTLY;
5503            } else if (childDimension == LayoutParams.MATCH_PARENT) {
5504                // Child wants to be our size. So be it.
5505                resultSize = size;
5506                resultMode = MeasureSpec.EXACTLY;
5507            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
5508                // Child wants to determine its own size. It can't be
5509                // bigger than us.
5510                resultSize = size;
5511                resultMode = MeasureSpec.AT_MOST;
5512            }
5513            break;
5514
5515        // Parent has imposed a maximum size on us
5516        case MeasureSpec.AT_MOST:
5517            if (childDimension >= 0) {
5518                // Child wants a specific size... so be it
5519                resultSize = childDimension;
5520                resultMode = MeasureSpec.EXACTLY;
5521            } else if (childDimension == LayoutParams.MATCH_PARENT) {
5522                // Child wants to be our size, but our size is not fixed.
5523                // Constrain child to not be bigger than us.
5524                resultSize = size;
5525                resultMode = MeasureSpec.AT_MOST;
5526            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
5527                // Child wants to determine its own size. It can't be
5528                // bigger than us.
5529                resultSize = size;
5530                resultMode = MeasureSpec.AT_MOST;
5531            }
5532            break;
5533
5534        // Parent asked to see how big we want to be
5535        case MeasureSpec.UNSPECIFIED:
5536            if (childDimension >= 0) {
5537                // Child wants a specific size... let him have it
5538                resultSize = childDimension;
5539                resultMode = MeasureSpec.EXACTLY;
5540            } else if (childDimension == LayoutParams.MATCH_PARENT) {
5541                // Child wants to be our size... find out how big it should
5542                // be
5543                resultSize = 0;
5544                resultMode = MeasureSpec.UNSPECIFIED;
5545            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
5546                // Child wants to determine its own size.... find out how
5547                // big it should be
5548                resultSize = 0;
5549                resultMode = MeasureSpec.UNSPECIFIED;
5550            }
5551            break;
5552        }
5553        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
5554    }
5555
5556
5557    /**
5558     * Removes any pending animations for views that have been removed. Call
5559     * this if you don't want animations for exiting views to stack up.
5560     */
5561    public void clearDisappearingChildren() {
5562        final ArrayList<View> disappearingChildren = mDisappearingChildren;
5563        if (disappearingChildren != null) {
5564            final int count = disappearingChildren.size();
5565            for (int i = 0; i < count; i++) {
5566                final View view = disappearingChildren.get(i);
5567                if (view.mAttachInfo != null) {
5568                    view.dispatchDetachedFromWindow();
5569                }
5570                view.clearAnimation();
5571            }
5572            disappearingChildren.clear();
5573            invalidate();
5574        }
5575    }
5576
5577    /**
5578     * Add a view which is removed from mChildren but still needs animation
5579     *
5580     * @param v View to add
5581     */
5582    private void addDisappearingView(View v) {
5583        ArrayList<View> disappearingChildren = mDisappearingChildren;
5584
5585        if (disappearingChildren == null) {
5586            disappearingChildren = mDisappearingChildren = new ArrayList<View>();
5587        }
5588
5589        disappearingChildren.add(v);
5590    }
5591
5592    /**
5593     * Cleanup a view when its animation is done. This may mean removing it from
5594     * the list of disappearing views.
5595     *
5596     * @param view The view whose animation has finished
5597     * @param animation The animation, cannot be null
5598     */
5599    void finishAnimatingView(final View view, Animation animation) {
5600        final ArrayList<View> disappearingChildren = mDisappearingChildren;
5601        if (disappearingChildren != null) {
5602            if (disappearingChildren.contains(view)) {
5603                disappearingChildren.remove(view);
5604
5605                if (view.mAttachInfo != null) {
5606                    view.dispatchDetachedFromWindow();
5607                }
5608
5609                view.clearAnimation();
5610                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
5611            }
5612        }
5613
5614        if (animation != null && !animation.getFillAfter()) {
5615            view.clearAnimation();
5616        }
5617
5618        if ((view.mPrivateFlags & PFLAG_ANIMATION_STARTED) == PFLAG_ANIMATION_STARTED) {
5619            view.onAnimationEnd();
5620            // Should be performed by onAnimationEnd() but this avoid an infinite loop,
5621            // so we'd rather be safe than sorry
5622            view.mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
5623            // Draw one more frame after the animation is done
5624            mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
5625        }
5626    }
5627
5628    /**
5629     * Utility function called by View during invalidation to determine whether a view that
5630     * is invisible or gone should still be invalidated because it is being transitioned (and
5631     * therefore still needs to be drawn).
5632     */
5633    boolean isViewTransitioning(View view) {
5634        return (mTransitioningViews != null && mTransitioningViews.contains(view));
5635    }
5636
5637    /**
5638     * This method tells the ViewGroup that the given View object, which should have this
5639     * ViewGroup as its parent,
5640     * should be kept around  (re-displayed when the ViewGroup draws its children) even if it
5641     * is removed from its parent. This allows animations, such as those used by
5642     * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate
5643     * the removal of views. A call to this method should always be accompanied by a later call
5644     * to {@link #endViewTransition(View)}, such as after an animation on the View has finished,
5645     * so that the View finally gets removed.
5646     *
5647     * @param view The View object to be kept visible even if it gets removed from its parent.
5648     */
5649    public void startViewTransition(View view) {
5650        if (view.mParent == this) {
5651            if (mTransitioningViews == null) {
5652                mTransitioningViews = new ArrayList<View>();
5653            }
5654            mTransitioningViews.add(view);
5655        }
5656    }
5657
5658    /**
5659     * This method should always be called following an earlier call to
5660     * {@link #startViewTransition(View)}. The given View is finally removed from its parent
5661     * and will no longer be displayed. Note that this method does not perform the functionality
5662     * of removing a view from its parent; it just discontinues the display of a View that
5663     * has previously been removed.
5664     *
5665     * @return view The View object that has been removed but is being kept around in the visible
5666     * hierarchy by an earlier call to {@link #startViewTransition(View)}.
5667     */
5668    public void endViewTransition(View view) {
5669        if (mTransitioningViews != null) {
5670            mTransitioningViews.remove(view);
5671            final ArrayList<View> disappearingChildren = mDisappearingChildren;
5672            if (disappearingChildren != null && disappearingChildren.contains(view)) {
5673                disappearingChildren.remove(view);
5674                if (mVisibilityChangingChildren != null &&
5675                        mVisibilityChangingChildren.contains(view)) {
5676                    mVisibilityChangingChildren.remove(view);
5677                } else {
5678                    if (view.mAttachInfo != null) {
5679                        view.dispatchDetachedFromWindow();
5680                    }
5681                    if (view.mParent != null) {
5682                        view.mParent = null;
5683                    }
5684                }
5685                invalidate();
5686            }
5687        }
5688    }
5689
5690    private LayoutTransition.TransitionListener mLayoutTransitionListener =
5691            new LayoutTransition.TransitionListener() {
5692        @Override
5693        public void startTransition(LayoutTransition transition, ViewGroup container,
5694                View view, int transitionType) {
5695            // We only care about disappearing items, since we need special logic to keep
5696            // those items visible after they've been 'removed'
5697            if (transitionType == LayoutTransition.DISAPPEARING) {
5698                startViewTransition(view);
5699            }
5700        }
5701
5702        @Override
5703        public void endTransition(LayoutTransition transition, ViewGroup container,
5704                View view, int transitionType) {
5705            if (mLayoutCalledWhileSuppressed && !transition.isChangingLayout()) {
5706                requestLayout();
5707                mLayoutCalledWhileSuppressed = false;
5708            }
5709            if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
5710                endViewTransition(view);
5711            }
5712        }
5713    };
5714
5715    /**
5716     * Tells this ViewGroup to suppress all layout() calls until layout
5717     * suppression is disabled with a later call to suppressLayout(false).
5718     * When layout suppression is disabled, a requestLayout() call is sent
5719     * if layout() was attempted while layout was being suppressed.
5720     *
5721     * @hide
5722     */
5723    public void suppressLayout(boolean suppress) {
5724        mSuppressLayout = suppress;
5725        if (!suppress) {
5726            if (mLayoutCalledWhileSuppressed) {
5727                requestLayout();
5728                mLayoutCalledWhileSuppressed = false;
5729            }
5730        }
5731    }
5732
5733    /**
5734     * Returns whether layout calls on this container are currently being
5735     * suppressed, due to an earlier call to {@link #suppressLayout(boolean)}.
5736     *
5737     * @return true if layout calls are currently suppressed, false otherwise.
5738     *
5739     * @hide
5740     */
5741    public boolean isLayoutSuppressed() {
5742        return mSuppressLayout;
5743    }
5744
5745    /**
5746     * {@inheritDoc}
5747     */
5748    @Override
5749    public boolean gatherTransparentRegion(Region region) {
5750        // If no transparent regions requested, we are always opaque.
5751        final boolean meOpaque = (mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0;
5752        if (meOpaque && region == null) {
5753            // The caller doesn't care about the region, so stop now.
5754            return true;
5755        }
5756        super.gatherTransparentRegion(region);
5757        final View[] children = mChildren;
5758        final int count = mChildrenCount;
5759        boolean noneOfTheChildrenAreTransparent = true;
5760        for (int i = 0; i < count; i++) {
5761            final View child = children[i];
5762            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
5763                if (!child.gatherTransparentRegion(region)) {
5764                    noneOfTheChildrenAreTransparent = false;
5765                }
5766            }
5767        }
5768        return meOpaque || noneOfTheChildrenAreTransparent;
5769    }
5770
5771    /**
5772     * {@inheritDoc}
5773     */
5774    public void requestTransparentRegion(View child) {
5775        if (child != null) {
5776            child.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
5777            if (mParent != null) {
5778                mParent.requestTransparentRegion(this);
5779            }
5780        }
5781    }
5782
5783    @Override
5784    public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {
5785        insets = super.dispatchApplyWindowInsets(insets);
5786        if (!insets.isConsumed()) {
5787            final int count = getChildCount();
5788            for (int i = 0; i < count; i++) {
5789                insets = getChildAt(i).dispatchApplyWindowInsets(insets);
5790                if (insets.isConsumed()) {
5791                    break;
5792                }
5793            }
5794        }
5795        return insets;
5796    }
5797
5798    /**
5799     * Returns the animation listener to which layout animation events are
5800     * sent.
5801     *
5802     * @return an {@link android.view.animation.Animation.AnimationListener}
5803     */
5804    public Animation.AnimationListener getLayoutAnimationListener() {
5805        return mAnimationListener;
5806    }
5807
5808    @Override
5809    protected void drawableStateChanged() {
5810        super.drawableStateChanged();
5811
5812        if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
5813            if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5814                throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
5815                        + " child has duplicateParentState set to true");
5816            }
5817
5818            final View[] children = mChildren;
5819            final int count = mChildrenCount;
5820
5821            for (int i = 0; i < count; i++) {
5822                final View child = children[i];
5823                if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
5824                    child.refreshDrawableState();
5825                }
5826            }
5827        }
5828    }
5829
5830    @Override
5831    public void jumpDrawablesToCurrentState() {
5832        super.jumpDrawablesToCurrentState();
5833        final View[] children = mChildren;
5834        final int count = mChildrenCount;
5835        for (int i = 0; i < count; i++) {
5836            children[i].jumpDrawablesToCurrentState();
5837        }
5838    }
5839
5840    @Override
5841    public void drawableHotspotChanged(float x, float y) {
5842        super.drawableHotspotChanged(x, y);
5843
5844        if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
5845            if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5846                throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
5847                        + " child has duplicateParentState set to true");
5848            }
5849
5850            final View[] children = mChildren;
5851            final int count = mChildrenCount;
5852
5853            for (int i = 0; i < count; i++) {
5854                final View child = children[i];
5855                if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
5856                    child.drawableHotspotChanged(x, y);
5857                }
5858            }
5859        }
5860    }
5861
5862    @Override
5863    protected int[] onCreateDrawableState(int extraSpace) {
5864        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) {
5865            return super.onCreateDrawableState(extraSpace);
5866        }
5867
5868        int need = 0;
5869        int n = getChildCount();
5870        for (int i = 0; i < n; i++) {
5871            int[] childState = getChildAt(i).getDrawableState();
5872
5873            if (childState != null) {
5874                need += childState.length;
5875            }
5876        }
5877
5878        int[] state = super.onCreateDrawableState(extraSpace + need);
5879
5880        for (int i = 0; i < n; i++) {
5881            int[] childState = getChildAt(i).getDrawableState();
5882
5883            if (childState != null) {
5884                state = mergeDrawableStates(state, childState);
5885            }
5886        }
5887
5888        return state;
5889    }
5890
5891    /**
5892     * Sets whether this ViewGroup's drawable states also include
5893     * its children's drawable states.  This is used, for example, to
5894     * make a group appear to be focused when its child EditText or button
5895     * is focused.
5896     */
5897    public void setAddStatesFromChildren(boolean addsStates) {
5898        if (addsStates) {
5899            mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN;
5900        } else {
5901            mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN;
5902        }
5903
5904        refreshDrawableState();
5905    }
5906
5907    /**
5908     * Returns whether this ViewGroup's drawable states also include
5909     * its children's drawable states.  This is used, for example, to
5910     * make a group appear to be focused when its child EditText or button
5911     * is focused.
5912     */
5913    public boolean addStatesFromChildren() {
5914        return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0;
5915    }
5916
5917    /**
5918     * If {@link #addStatesFromChildren} is true, refreshes this group's
5919     * drawable state (to include the states from its children).
5920     */
5921    public void childDrawableStateChanged(View child) {
5922        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5923            refreshDrawableState();
5924        }
5925    }
5926
5927    /**
5928     * Specifies the animation listener to which layout animation events must
5929     * be sent. Only
5930     * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)}
5931     * and
5932     * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)}
5933     * are invoked.
5934     *
5935     * @param animationListener the layout animation listener
5936     */
5937    public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
5938        mAnimationListener = animationListener;
5939    }
5940
5941    /**
5942     * This method is called by LayoutTransition when there are 'changing' animations that need
5943     * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who
5944     * starts all pending transitions prior to the drawing phase in the current traversal.
5945     *
5946     * @param transition The LayoutTransition to be started on the next traversal.
5947     *
5948     * @hide
5949     */
5950    public void requestTransitionStart(LayoutTransition transition) {
5951        ViewRootImpl viewAncestor = getViewRootImpl();
5952        if (viewAncestor != null) {
5953            viewAncestor.requestTransitionStart(transition);
5954        }
5955    }
5956
5957    /**
5958     * @hide
5959     */
5960    @Override
5961    public boolean resolveRtlPropertiesIfNeeded() {
5962        final boolean result = super.resolveRtlPropertiesIfNeeded();
5963        // We dont need to resolve the children RTL properties if nothing has changed for the parent
5964        if (result) {
5965            int count = getChildCount();
5966            for (int i = 0; i < count; i++) {
5967                final View child = getChildAt(i);
5968                if (child.isLayoutDirectionInherited()) {
5969                    child.resolveRtlPropertiesIfNeeded();
5970                }
5971            }
5972        }
5973        return result;
5974    }
5975
5976    /**
5977     * @hide
5978     */
5979    @Override
5980    public boolean resolveLayoutDirection() {
5981        final boolean result = super.resolveLayoutDirection();
5982        if (result) {
5983            int count = getChildCount();
5984            for (int i = 0; i < count; i++) {
5985                final View child = getChildAt(i);
5986                if (child.isLayoutDirectionInherited()) {
5987                    child.resolveLayoutDirection();
5988                }
5989            }
5990        }
5991        return result;
5992    }
5993
5994    /**
5995     * @hide
5996     */
5997    @Override
5998    public boolean resolveTextDirection() {
5999        final boolean result = super.resolveTextDirection();
6000        if (result) {
6001            int count = getChildCount();
6002            for (int i = 0; i < count; i++) {
6003                final View child = getChildAt(i);
6004                if (child.isTextDirectionInherited()) {
6005                    child.resolveTextDirection();
6006                }
6007            }
6008        }
6009        return result;
6010    }
6011
6012    /**
6013     * @hide
6014     */
6015    @Override
6016    public boolean resolveTextAlignment() {
6017        final boolean result = super.resolveTextAlignment();
6018        if (result) {
6019            int count = getChildCount();
6020            for (int i = 0; i < count; i++) {
6021                final View child = getChildAt(i);
6022                if (child.isTextAlignmentInherited()) {
6023                    child.resolveTextAlignment();
6024                }
6025            }
6026        }
6027        return result;
6028    }
6029
6030    /**
6031     * @hide
6032     */
6033    @Override
6034    public void resolvePadding() {
6035        super.resolvePadding();
6036        int count = getChildCount();
6037        for (int i = 0; i < count; i++) {
6038            final View child = getChildAt(i);
6039            if (child.isLayoutDirectionInherited()) {
6040                child.resolvePadding();
6041            }
6042        }
6043    }
6044
6045    /**
6046     * @hide
6047     */
6048    @Override
6049    protected void resolveDrawables() {
6050        super.resolveDrawables();
6051        int count = getChildCount();
6052        for (int i = 0; i < count; i++) {
6053            final View child = getChildAt(i);
6054            if (child.isLayoutDirectionInherited()) {
6055                child.resolveDrawables();
6056            }
6057        }
6058    }
6059
6060    /**
6061     * @hide
6062     */
6063    @Override
6064    public void resolveLayoutParams() {
6065        super.resolveLayoutParams();
6066        int count = getChildCount();
6067        for (int i = 0; i < count; i++) {
6068            final View child = getChildAt(i);
6069            child.resolveLayoutParams();
6070        }
6071    }
6072
6073    /**
6074     * @hide
6075     */
6076    @Override
6077    public void resetResolvedLayoutDirection() {
6078        super.resetResolvedLayoutDirection();
6079
6080        int count = getChildCount();
6081        for (int i = 0; i < count; i++) {
6082            final View child = getChildAt(i);
6083            if (child.isLayoutDirectionInherited()) {
6084                child.resetResolvedLayoutDirection();
6085            }
6086        }
6087    }
6088
6089    /**
6090     * @hide
6091     */
6092    @Override
6093    public void resetResolvedTextDirection() {
6094        super.resetResolvedTextDirection();
6095
6096        int count = getChildCount();
6097        for (int i = 0; i < count; i++) {
6098            final View child = getChildAt(i);
6099            if (child.isTextDirectionInherited()) {
6100                child.resetResolvedTextDirection();
6101            }
6102        }
6103    }
6104
6105    /**
6106     * @hide
6107     */
6108    @Override
6109    public void resetResolvedTextAlignment() {
6110        super.resetResolvedTextAlignment();
6111
6112        int count = getChildCount();
6113        for (int i = 0; i < count; i++) {
6114            final View child = getChildAt(i);
6115            if (child.isTextAlignmentInherited()) {
6116                child.resetResolvedTextAlignment();
6117            }
6118        }
6119    }
6120
6121    /**
6122     * @hide
6123     */
6124    @Override
6125    public void resetResolvedPadding() {
6126        super.resetResolvedPadding();
6127
6128        int count = getChildCount();
6129        for (int i = 0; i < count; i++) {
6130            final View child = getChildAt(i);
6131            if (child.isLayoutDirectionInherited()) {
6132                child.resetResolvedPadding();
6133            }
6134        }
6135    }
6136
6137    /**
6138     * @hide
6139     */
6140    @Override
6141    protected void resetResolvedDrawables() {
6142        super.resetResolvedDrawables();
6143
6144        int count = getChildCount();
6145        for (int i = 0; i < count; i++) {
6146            final View child = getChildAt(i);
6147            if (child.isLayoutDirectionInherited()) {
6148                child.resetResolvedDrawables();
6149            }
6150        }
6151    }
6152
6153    /**
6154     * Return true if the pressed state should be delayed for children or descendants of this
6155     * ViewGroup. Generally, this should be done for containers that can scroll, such as a List.
6156     * This prevents the pressed state from appearing when the user is actually trying to scroll
6157     * the content.
6158     *
6159     * The default implementation returns true for compatibility reasons. Subclasses that do
6160     * not scroll should generally override this method and return false.
6161     */
6162    public boolean shouldDelayChildPressedState() {
6163        return true;
6164    }
6165
6166    /**
6167     * @inheritDoc
6168     */
6169    @Override
6170    public boolean onStartNestedScroll(View child, View target, int nestedScrollAxes) {
6171        return false;
6172    }
6173
6174    /**
6175     * @inheritDoc
6176     */
6177    @Override
6178    public void onNestedScrollAccepted(View child, View target, int axes) {
6179        mNestedScrollAxes = axes;
6180    }
6181
6182    /**
6183     * @inheritDoc
6184     *
6185     * <p>The default implementation of onStopNestedScroll calls
6186     * {@link #stopNestedScroll()} to halt any recursive nested scrolling in progress.</p>
6187     */
6188    @Override
6189    public void onStopNestedScroll(View child) {
6190        // Stop any recursive nested scrolling.
6191        stopNestedScroll();
6192    }
6193
6194    /**
6195     * @inheritDoc
6196     */
6197    @Override
6198    public void onNestedScroll(View target, int dxConsumed, int dyConsumed,
6199            int dxUnconsumed, int dyUnconsumed) {
6200        // Do nothing
6201    }
6202
6203    /**
6204     * @inheritDoc
6205     */
6206    @Override
6207    public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) {
6208        // Do nothing
6209    }
6210
6211    /**
6212     * @inheritDoc
6213     */
6214    @Override
6215    public boolean onNestedFling(View target, float velocityX, float velocityY, boolean consumed) {
6216        return false;
6217    }
6218
6219    /**
6220     * @inheritDoc
6221     */
6222    @Override
6223    public boolean onNestedPreFling(View target, float velocityX, float velocityY) {
6224        return false;
6225    }
6226
6227    /**
6228     * Return the current axes of nested scrolling for this ViewGroup.
6229     *
6230     * <p>A ViewGroup returning something other than {@link #SCROLL_AXIS_NONE} is currently
6231     * acting as a nested scrolling parent for one or more descendant views in the hierarchy.</p>
6232     *
6233     * @return Flags indicating the current axes of nested scrolling
6234     * @see #SCROLL_AXIS_HORIZONTAL
6235     * @see #SCROLL_AXIS_VERTICAL
6236     * @see #SCROLL_AXIS_NONE
6237     */
6238    public int getNestedScrollAxes() {
6239        return mNestedScrollAxes;
6240    }
6241
6242    /** @hide */
6243    protected void onSetLayoutParams(View child, LayoutParams layoutParams) {
6244    }
6245
6246    /** @hide */
6247    @Override
6248    public void captureTransitioningViews(List<View> transitioningViews) {
6249        if (getVisibility() != View.VISIBLE) {
6250            return;
6251        }
6252        if (isTransitionGroup()) {
6253            transitioningViews.add(this);
6254        } else {
6255            int count = getChildCount();
6256            for (int i = 0; i < count; i++) {
6257                View child = getChildAt(i);
6258                child.captureTransitioningViews(transitioningViews);
6259            }
6260        }
6261    }
6262
6263    /** @hide */
6264    @Override
6265    public void findNamedViews(Map<String, View> namedElements) {
6266        if (getVisibility() != VISIBLE && mGhostView == null) {
6267            return;
6268        }
6269        super.findNamedViews(namedElements);
6270        int count = getChildCount();
6271        for (int i = 0; i < count; i++) {
6272            View child = getChildAt(i);
6273            child.findNamedViews(namedElements);
6274        }
6275    }
6276
6277    /**
6278     * LayoutParams are used by views to tell their parents how they want to be
6279     * laid out. See
6280     * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes}
6281     * for a list of all child view attributes that this class supports.
6282     *
6283     * <p>
6284     * The base LayoutParams class just describes how big the view wants to be
6285     * for both width and height. For each dimension, it can specify one of:
6286     * <ul>
6287     * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
6288     * means that the view wants to be as big as its parent (minus padding)
6289     * <li> WRAP_CONTENT, which means that the view wants to be just big enough
6290     * to enclose its content (plus padding)
6291     * <li> an exact number
6292     * </ul>
6293     * There are subclasses of LayoutParams for different subclasses of
6294     * ViewGroup. For example, AbsoluteLayout has its own subclass of
6295     * LayoutParams which adds an X and Y value.</p>
6296     *
6297     * <div class="special reference">
6298     * <h3>Developer Guides</h3>
6299     * <p>For more information about creating user interface layouts, read the
6300     * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer
6301     * guide.</p></div>
6302     *
6303     * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
6304     * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
6305     */
6306    public static class LayoutParams {
6307        /**
6308         * Special value for the height or width requested by a View.
6309         * FILL_PARENT means that the view wants to be as big as its parent,
6310         * minus the parent's padding, if any. This value is deprecated
6311         * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
6312         */
6313        @SuppressWarnings({"UnusedDeclaration"})
6314        @Deprecated
6315        public static final int FILL_PARENT = -1;
6316
6317        /**
6318         * Special value for the height or width requested by a View.
6319         * MATCH_PARENT means that the view wants to be as big as its parent,
6320         * minus the parent's padding, if any. Introduced in API Level 8.
6321         */
6322        public static final int MATCH_PARENT = -1;
6323
6324        /**
6325         * Special value for the height or width requested by a View.
6326         * WRAP_CONTENT means that the view wants to be just large enough to fit
6327         * its own internal content, taking its own padding into account.
6328         */
6329        public static final int WRAP_CONTENT = -2;
6330
6331        /**
6332         * Information about how wide the view wants to be. Can be one of the
6333         * constants FILL_PARENT (replaced by MATCH_PARENT ,
6334         * in API Level 8) or WRAP_CONTENT. or an exact size.
6335         */
6336        @ViewDebug.ExportedProperty(category = "layout", mapping = {
6337            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
6338            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
6339        })
6340        public int width;
6341
6342        /**
6343         * Information about how tall the view wants to be. Can be one of the
6344         * constants FILL_PARENT (replaced by MATCH_PARENT ,
6345         * in API Level 8) or WRAP_CONTENT. or an exact size.
6346         */
6347        @ViewDebug.ExportedProperty(category = "layout", mapping = {
6348            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
6349            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
6350        })
6351        public int height;
6352
6353        /**
6354         * Used to animate layouts.
6355         */
6356        public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
6357
6358        /**
6359         * Creates a new set of layout parameters. The values are extracted from
6360         * the supplied attributes set and context. The XML attributes mapped
6361         * to this set of layout parameters are:
6362         *
6363         * <ul>
6364         *   <li><code>layout_width</code>: the width, either an exact value,
6365         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
6366         *   {@link #MATCH_PARENT} in API Level 8)</li>
6367         *   <li><code>layout_height</code>: the height, either an exact value,
6368         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
6369         *   {@link #MATCH_PARENT} in API Level 8)</li>
6370         * </ul>
6371         *
6372         * @param c the application environment
6373         * @param attrs the set of attributes from which to extract the layout
6374         *              parameters' values
6375         */
6376        public LayoutParams(Context c, AttributeSet attrs) {
6377            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
6378            setBaseAttributes(a,
6379                    R.styleable.ViewGroup_Layout_layout_width,
6380                    R.styleable.ViewGroup_Layout_layout_height);
6381            a.recycle();
6382        }
6383
6384        /**
6385         * Creates a new set of layout parameters with the specified width
6386         * and height.
6387         *
6388         * @param width the width, either {@link #WRAP_CONTENT},
6389         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
6390         *        API Level 8), or a fixed size in pixels
6391         * @param height the height, either {@link #WRAP_CONTENT},
6392         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
6393         *        API Level 8), or a fixed size in pixels
6394         */
6395        public LayoutParams(int width, int height) {
6396            this.width = width;
6397            this.height = height;
6398        }
6399
6400        /**
6401         * Copy constructor. Clones the width and height values of the source.
6402         *
6403         * @param source The layout params to copy from.
6404         */
6405        public LayoutParams(LayoutParams source) {
6406            this.width = source.width;
6407            this.height = source.height;
6408        }
6409
6410        /**
6411         * Used internally by MarginLayoutParams.
6412         * @hide
6413         */
6414        LayoutParams() {
6415        }
6416
6417        /**
6418         * Extracts the layout parameters from the supplied attributes.
6419         *
6420         * @param a the style attributes to extract the parameters from
6421         * @param widthAttr the identifier of the width attribute
6422         * @param heightAttr the identifier of the height attribute
6423         */
6424        protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
6425            width = a.getLayoutDimension(widthAttr, "layout_width");
6426            height = a.getLayoutDimension(heightAttr, "layout_height");
6427        }
6428
6429        /**
6430         * Resolve layout parameters depending on the layout direction. Subclasses that care about
6431         * layoutDirection changes should override this method. The default implementation does
6432         * nothing.
6433         *
6434         * @param layoutDirection the direction of the layout
6435         *
6436         * {@link View#LAYOUT_DIRECTION_LTR}
6437         * {@link View#LAYOUT_DIRECTION_RTL}
6438         */
6439        public void resolveLayoutDirection(int layoutDirection) {
6440        }
6441
6442        /**
6443         * Returns a String representation of this set of layout parameters.
6444         *
6445         * @param output the String to prepend to the internal representation
6446         * @return a String with the following format: output +
6447         *         "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }"
6448         *
6449         * @hide
6450         */
6451        public String debug(String output) {
6452            return output + "ViewGroup.LayoutParams={ width="
6453                    + sizeToString(width) + ", height=" + sizeToString(height) + " }";
6454        }
6455
6456        /**
6457         * Use {@code canvas} to draw suitable debugging annotations for these LayoutParameters.
6458         *
6459         * @param view the view that contains these layout parameters
6460         * @param canvas the canvas on which to draw
6461         *
6462         * @hide
6463         */
6464        public void onDebugDraw(View view, Canvas canvas, Paint paint) {
6465        }
6466
6467        /**
6468         * Converts the specified size to a readable String.
6469         *
6470         * @param size the size to convert
6471         * @return a String instance representing the supplied size
6472         *
6473         * @hide
6474         */
6475        protected static String sizeToString(int size) {
6476            if (size == WRAP_CONTENT) {
6477                return "wrap-content";
6478            }
6479            if (size == MATCH_PARENT) {
6480                return "match-parent";
6481            }
6482            return String.valueOf(size);
6483        }
6484    }
6485
6486    /**
6487     * Per-child layout information for layouts that support margins.
6488     * See
6489     * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes}
6490     * for a list of all child view attributes that this class supports.
6491     */
6492    public static class MarginLayoutParams extends ViewGroup.LayoutParams {
6493        /**
6494         * The left margin in pixels of the child.
6495         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
6496         * to this field.
6497         */
6498        @ViewDebug.ExportedProperty(category = "layout")
6499        public int leftMargin;
6500
6501        /**
6502         * The top margin in pixels of the child.
6503         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
6504         * to this field.
6505         */
6506        @ViewDebug.ExportedProperty(category = "layout")
6507        public int topMargin;
6508
6509        /**
6510         * The right margin in pixels of the child.
6511         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
6512         * to this field.
6513         */
6514        @ViewDebug.ExportedProperty(category = "layout")
6515        public int rightMargin;
6516
6517        /**
6518         * The bottom margin in pixels of the child.
6519         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
6520         * to this field.
6521         */
6522        @ViewDebug.ExportedProperty(category = "layout")
6523        public int bottomMargin;
6524
6525        /**
6526         * The start margin in pixels of the child.
6527         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
6528         * to this field.
6529         */
6530        @ViewDebug.ExportedProperty(category = "layout")
6531        private int startMargin = DEFAULT_MARGIN_RELATIVE;
6532
6533        /**
6534         * The end margin in pixels of the child.
6535         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
6536         * to this field.
6537         */
6538        @ViewDebug.ExportedProperty(category = "layout")
6539        private int endMargin = DEFAULT_MARGIN_RELATIVE;
6540
6541        /**
6542         * The default start and end margin.
6543         * @hide
6544         */
6545        public static final int DEFAULT_MARGIN_RELATIVE = Integer.MIN_VALUE;
6546
6547        /**
6548         * Bit  0: layout direction
6549         * Bit  1: layout direction
6550         * Bit  2: left margin undefined
6551         * Bit  3: right margin undefined
6552         * Bit  4: is RTL compatibility mode
6553         * Bit  5: need resolution
6554         *
6555         * Bit 6 to 7 not used
6556         *
6557         * @hide
6558         */
6559        @ViewDebug.ExportedProperty(category = "layout", flagMapping = {
6560                @ViewDebug.FlagToString(mask = LAYOUT_DIRECTION_MASK,
6561                        equals = LAYOUT_DIRECTION_MASK, name = "LAYOUT_DIRECTION"),
6562                @ViewDebug.FlagToString(mask = LEFT_MARGIN_UNDEFINED_MASK,
6563                        equals = LEFT_MARGIN_UNDEFINED_MASK, name = "LEFT_MARGIN_UNDEFINED_MASK"),
6564                @ViewDebug.FlagToString(mask = RIGHT_MARGIN_UNDEFINED_MASK,
6565                        equals = RIGHT_MARGIN_UNDEFINED_MASK, name = "RIGHT_MARGIN_UNDEFINED_MASK"),
6566                @ViewDebug.FlagToString(mask = RTL_COMPATIBILITY_MODE_MASK,
6567                        equals = RTL_COMPATIBILITY_MODE_MASK, name = "RTL_COMPATIBILITY_MODE_MASK"),
6568                @ViewDebug.FlagToString(mask = NEED_RESOLUTION_MASK,
6569                        equals = NEED_RESOLUTION_MASK, name = "NEED_RESOLUTION_MASK")
6570        }, formatToHexString = true)
6571        byte mMarginFlags;
6572
6573        private static final int LAYOUT_DIRECTION_MASK = 0x00000003;
6574        private static final int LEFT_MARGIN_UNDEFINED_MASK = 0x00000004;
6575        private static final int RIGHT_MARGIN_UNDEFINED_MASK = 0x00000008;
6576        private static final int RTL_COMPATIBILITY_MODE_MASK = 0x00000010;
6577        private static final int NEED_RESOLUTION_MASK = 0x00000020;
6578
6579        private static final int DEFAULT_MARGIN_RESOLVED = 0;
6580        private static final int UNDEFINED_MARGIN = DEFAULT_MARGIN_RELATIVE;
6581
6582        /**
6583         * Creates a new set of layout parameters. The values are extracted from
6584         * the supplied attributes set and context.
6585         *
6586         * @param c the application environment
6587         * @param attrs the set of attributes from which to extract the layout
6588         *              parameters' values
6589         */
6590        public MarginLayoutParams(Context c, AttributeSet attrs) {
6591            super();
6592
6593            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
6594            setBaseAttributes(a,
6595                    R.styleable.ViewGroup_MarginLayout_layout_width,
6596                    R.styleable.ViewGroup_MarginLayout_layout_height);
6597
6598            int margin = a.getDimensionPixelSize(
6599                    com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
6600            if (margin >= 0) {
6601                leftMargin = margin;
6602                topMargin = margin;
6603                rightMargin= margin;
6604                bottomMargin = margin;
6605            } else {
6606                leftMargin = a.getDimensionPixelSize(
6607                        R.styleable.ViewGroup_MarginLayout_layout_marginLeft,
6608                        UNDEFINED_MARGIN);
6609                if (leftMargin == UNDEFINED_MARGIN) {
6610                    mMarginFlags |= LEFT_MARGIN_UNDEFINED_MASK;
6611                    leftMargin = DEFAULT_MARGIN_RESOLVED;
6612                }
6613                rightMargin = a.getDimensionPixelSize(
6614                        R.styleable.ViewGroup_MarginLayout_layout_marginRight,
6615                        UNDEFINED_MARGIN);
6616                if (rightMargin == UNDEFINED_MARGIN) {
6617                    mMarginFlags |= RIGHT_MARGIN_UNDEFINED_MASK;
6618                    rightMargin = DEFAULT_MARGIN_RESOLVED;
6619                }
6620
6621                topMargin = a.getDimensionPixelSize(
6622                        R.styleable.ViewGroup_MarginLayout_layout_marginTop,
6623                        DEFAULT_MARGIN_RESOLVED);
6624                bottomMargin = a.getDimensionPixelSize(
6625                        R.styleable.ViewGroup_MarginLayout_layout_marginBottom,
6626                        DEFAULT_MARGIN_RESOLVED);
6627
6628                startMargin = a.getDimensionPixelSize(
6629                        R.styleable.ViewGroup_MarginLayout_layout_marginStart,
6630                        DEFAULT_MARGIN_RELATIVE);
6631                endMargin = a.getDimensionPixelSize(
6632                        R.styleable.ViewGroup_MarginLayout_layout_marginEnd,
6633                        DEFAULT_MARGIN_RELATIVE);
6634
6635                if (isMarginRelative()) {
6636                   mMarginFlags |= NEED_RESOLUTION_MASK;
6637                }
6638            }
6639
6640            final boolean hasRtlSupport = c.getApplicationInfo().hasRtlSupport();
6641            final int targetSdkVersion = c.getApplicationInfo().targetSdkVersion;
6642            if (targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport) {
6643                mMarginFlags |= RTL_COMPATIBILITY_MODE_MASK;
6644            }
6645
6646            // Layout direction is LTR by default
6647            mMarginFlags |= LAYOUT_DIRECTION_LTR;
6648
6649            a.recycle();
6650        }
6651
6652        /**
6653         * {@inheritDoc}
6654         */
6655        public MarginLayoutParams(int width, int height) {
6656            super(width, height);
6657
6658            mMarginFlags |= LEFT_MARGIN_UNDEFINED_MASK;
6659            mMarginFlags |= RIGHT_MARGIN_UNDEFINED_MASK;
6660
6661            mMarginFlags &= ~NEED_RESOLUTION_MASK;
6662            mMarginFlags &= ~RTL_COMPATIBILITY_MODE_MASK;
6663        }
6664
6665        /**
6666         * Copy constructor. Clones the width, height and margin values of the source.
6667         *
6668         * @param source The layout params to copy from.
6669         */
6670        public MarginLayoutParams(MarginLayoutParams source) {
6671            this.width = source.width;
6672            this.height = source.height;
6673
6674            this.leftMargin = source.leftMargin;
6675            this.topMargin = source.topMargin;
6676            this.rightMargin = source.rightMargin;
6677            this.bottomMargin = source.bottomMargin;
6678            this.startMargin = source.startMargin;
6679            this.endMargin = source.endMargin;
6680
6681            this.mMarginFlags = source.mMarginFlags;
6682        }
6683
6684        /**
6685         * {@inheritDoc}
6686         */
6687        public MarginLayoutParams(LayoutParams source) {
6688            super(source);
6689
6690            mMarginFlags |= LEFT_MARGIN_UNDEFINED_MASK;
6691            mMarginFlags |= RIGHT_MARGIN_UNDEFINED_MASK;
6692
6693            mMarginFlags &= ~NEED_RESOLUTION_MASK;
6694            mMarginFlags &= ~RTL_COMPATIBILITY_MODE_MASK;
6695        }
6696
6697        /**
6698         * @hide Used internally.
6699         */
6700        public final void copyMarginsFrom(MarginLayoutParams source) {
6701            this.leftMargin = source.leftMargin;
6702            this.topMargin = source.topMargin;
6703            this.rightMargin = source.rightMargin;
6704            this.bottomMargin = source.bottomMargin;
6705            this.startMargin = source.startMargin;
6706            this.endMargin = source.endMargin;
6707
6708            this.mMarginFlags = source.mMarginFlags;
6709        }
6710
6711        /**
6712         * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs
6713         * to be done so that the new margins are taken into account. Left and right margins may be
6714         * overriden by {@link android.view.View#requestLayout()} depending on layout direction.
6715         *
6716         * @param left the left margin size
6717         * @param top the top margin size
6718         * @param right the right margin size
6719         * @param bottom the bottom margin size
6720         *
6721         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
6722         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
6723         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
6724         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
6725         */
6726        public void setMargins(int left, int top, int right, int bottom) {
6727            leftMargin = left;
6728            topMargin = top;
6729            rightMargin = right;
6730            bottomMargin = bottom;
6731            mMarginFlags &= ~LEFT_MARGIN_UNDEFINED_MASK;
6732            mMarginFlags &= ~RIGHT_MARGIN_UNDEFINED_MASK;
6733            if (isMarginRelative()) {
6734                mMarginFlags |= NEED_RESOLUTION_MASK;
6735            } else {
6736                mMarginFlags &= ~NEED_RESOLUTION_MASK;
6737            }
6738        }
6739
6740        /**
6741         * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()}
6742         * needs to be done so that the new relative margins are taken into account. Left and right
6743         * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout
6744         * direction.
6745         *
6746         * @param start the start margin size
6747         * @param top the top margin size
6748         * @param end the right margin size
6749         * @param bottom the bottom margin size
6750         *
6751         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
6752         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
6753         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
6754         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
6755         *
6756         * @hide
6757         */
6758        public void setMarginsRelative(int start, int top, int end, int bottom) {
6759            startMargin = start;
6760            topMargin = top;
6761            endMargin = end;
6762            bottomMargin = bottom;
6763            mMarginFlags |= NEED_RESOLUTION_MASK;
6764        }
6765
6766        /**
6767         * Sets the relative start margin.
6768         *
6769         * @param start the start margin size
6770         *
6771         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
6772         */
6773        public void setMarginStart(int start) {
6774            startMargin = start;
6775            mMarginFlags |= NEED_RESOLUTION_MASK;
6776        }
6777
6778        /**
6779         * Returns the start margin in pixels.
6780         *
6781         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
6782         *
6783         * @return the start margin in pixels.
6784         */
6785        public int getMarginStart() {
6786            if (startMargin != DEFAULT_MARGIN_RELATIVE) return startMargin;
6787            if ((mMarginFlags & NEED_RESOLUTION_MASK) == NEED_RESOLUTION_MASK) {
6788                doResolveMargins();
6789            }
6790            switch(mMarginFlags & LAYOUT_DIRECTION_MASK) {
6791                case View.LAYOUT_DIRECTION_RTL:
6792                    return rightMargin;
6793                case View.LAYOUT_DIRECTION_LTR:
6794                default:
6795                    return leftMargin;
6796            }
6797        }
6798
6799        /**
6800         * Sets the relative end margin.
6801         *
6802         * @param end the end margin size
6803         *
6804         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
6805         */
6806        public void setMarginEnd(int end) {
6807            endMargin = end;
6808            mMarginFlags |= NEED_RESOLUTION_MASK;
6809        }
6810
6811        /**
6812         * Returns the end margin in pixels.
6813         *
6814         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
6815         *
6816         * @return the end margin in pixels.
6817         */
6818        public int getMarginEnd() {
6819            if (endMargin != DEFAULT_MARGIN_RELATIVE) return endMargin;
6820            if ((mMarginFlags & NEED_RESOLUTION_MASK) == NEED_RESOLUTION_MASK) {
6821                doResolveMargins();
6822            }
6823            switch(mMarginFlags & LAYOUT_DIRECTION_MASK) {
6824                case View.LAYOUT_DIRECTION_RTL:
6825                    return leftMargin;
6826                case View.LAYOUT_DIRECTION_LTR:
6827                default:
6828                    return rightMargin;
6829            }
6830        }
6831
6832        /**
6833         * Check if margins are relative.
6834         *
6835         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
6836         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
6837         *
6838         * @return true if either marginStart or marginEnd has been set.
6839         */
6840        public boolean isMarginRelative() {
6841            return (startMargin != DEFAULT_MARGIN_RELATIVE || endMargin != DEFAULT_MARGIN_RELATIVE);
6842        }
6843
6844        /**
6845         * Set the layout direction
6846         * @param layoutDirection the layout direction.
6847         *        Should be either {@link View#LAYOUT_DIRECTION_LTR}
6848         *                     or {@link View#LAYOUT_DIRECTION_RTL}.
6849         */
6850        public void setLayoutDirection(int layoutDirection) {
6851            if (layoutDirection != View.LAYOUT_DIRECTION_LTR &&
6852                    layoutDirection != View.LAYOUT_DIRECTION_RTL) return;
6853            if (layoutDirection != (mMarginFlags & LAYOUT_DIRECTION_MASK)) {
6854                mMarginFlags &= ~LAYOUT_DIRECTION_MASK;
6855                mMarginFlags |= (layoutDirection & LAYOUT_DIRECTION_MASK);
6856                if (isMarginRelative()) {
6857                    mMarginFlags |= NEED_RESOLUTION_MASK;
6858                } else {
6859                    mMarginFlags &= ~NEED_RESOLUTION_MASK;
6860                }
6861            }
6862        }
6863
6864        /**
6865         * Retuns the layout direction. Can be either {@link View#LAYOUT_DIRECTION_LTR} or
6866         * {@link View#LAYOUT_DIRECTION_RTL}.
6867         *
6868         * @return the layout direction.
6869         */
6870        public int getLayoutDirection() {
6871            return (mMarginFlags & LAYOUT_DIRECTION_MASK);
6872        }
6873
6874        /**
6875         * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins
6876         * may be overridden depending on layout direction.
6877         */
6878        @Override
6879        public void resolveLayoutDirection(int layoutDirection) {
6880            setLayoutDirection(layoutDirection);
6881
6882            // No relative margin or pre JB-MR1 case or no need to resolve, just dont do anything
6883            // Will use the left and right margins if no relative margin is defined.
6884            if (!isMarginRelative() ||
6885                    (mMarginFlags & NEED_RESOLUTION_MASK) != NEED_RESOLUTION_MASK) return;
6886
6887            // Proceed with resolution
6888            doResolveMargins();
6889        }
6890
6891        private void doResolveMargins() {
6892            if ((mMarginFlags & RTL_COMPATIBILITY_MODE_MASK) == RTL_COMPATIBILITY_MODE_MASK) {
6893                // if left or right margins are not defined and if we have some start or end margin
6894                // defined then use those start and end margins.
6895                if ((mMarginFlags & LEFT_MARGIN_UNDEFINED_MASK) == LEFT_MARGIN_UNDEFINED_MASK
6896                        && startMargin > DEFAULT_MARGIN_RELATIVE) {
6897                    leftMargin = startMargin;
6898                }
6899                if ((mMarginFlags & RIGHT_MARGIN_UNDEFINED_MASK) == RIGHT_MARGIN_UNDEFINED_MASK
6900                        && endMargin > DEFAULT_MARGIN_RELATIVE) {
6901                    rightMargin = endMargin;
6902                }
6903            } else {
6904                // We have some relative margins (either the start one or the end one or both). So use
6905                // them and override what has been defined for left and right margins. If either start
6906                // or end margin is not defined, just set it to default "0".
6907                switch(mMarginFlags & LAYOUT_DIRECTION_MASK) {
6908                    case View.LAYOUT_DIRECTION_RTL:
6909                        leftMargin = (endMargin > DEFAULT_MARGIN_RELATIVE) ?
6910                                endMargin : DEFAULT_MARGIN_RESOLVED;
6911                        rightMargin = (startMargin > DEFAULT_MARGIN_RELATIVE) ?
6912                                startMargin : DEFAULT_MARGIN_RESOLVED;
6913                        break;
6914                    case View.LAYOUT_DIRECTION_LTR:
6915                    default:
6916                        leftMargin = (startMargin > DEFAULT_MARGIN_RELATIVE) ?
6917                                startMargin : DEFAULT_MARGIN_RESOLVED;
6918                        rightMargin = (endMargin > DEFAULT_MARGIN_RELATIVE) ?
6919                                endMargin : DEFAULT_MARGIN_RESOLVED;
6920                        break;
6921                }
6922            }
6923            mMarginFlags &= ~NEED_RESOLUTION_MASK;
6924        }
6925
6926        /**
6927         * @hide
6928         */
6929        public boolean isLayoutRtl() {
6930            return ((mMarginFlags & LAYOUT_DIRECTION_MASK) == View.LAYOUT_DIRECTION_RTL);
6931        }
6932
6933        /**
6934         * @hide
6935         */
6936        @Override
6937        public void onDebugDraw(View view, Canvas canvas, Paint paint) {
6938            Insets oi = isLayoutModeOptical(view.mParent) ? view.getOpticalInsets() : Insets.NONE;
6939
6940            fillDifference(canvas,
6941                    view.getLeft()   + oi.left,
6942                    view.getTop()    + oi.top,
6943                    view.getRight()  - oi.right,
6944                    view.getBottom() - oi.bottom,
6945                    leftMargin,
6946                    topMargin,
6947                    rightMargin,
6948                    bottomMargin,
6949                    paint);
6950        }
6951    }
6952
6953    /* Describes a touched view and the ids of the pointers that it has captured.
6954     *
6955     * This code assumes that pointer ids are always in the range 0..31 such that
6956     * it can use a bitfield to track which pointer ids are present.
6957     * As it happens, the lower layers of the input dispatch pipeline also use the
6958     * same trick so the assumption should be safe here...
6959     */
6960    private static final class TouchTarget {
6961        private static final int MAX_RECYCLED = 32;
6962        private static final Object sRecycleLock = new Object[0];
6963        private static TouchTarget sRecycleBin;
6964        private static int sRecycledCount;
6965
6966        public static final int ALL_POINTER_IDS = -1; // all ones
6967
6968        // The touched child view.
6969        public View child;
6970
6971        // The combined bit mask of pointer ids for all pointers captured by the target.
6972        public int pointerIdBits;
6973
6974        // The next target in the target list.
6975        public TouchTarget next;
6976
6977        private TouchTarget() {
6978        }
6979
6980        public static TouchTarget obtain(View child, int pointerIdBits) {
6981            final TouchTarget target;
6982            synchronized (sRecycleLock) {
6983                if (sRecycleBin == null) {
6984                    target = new TouchTarget();
6985                } else {
6986                    target = sRecycleBin;
6987                    sRecycleBin = target.next;
6988                     sRecycledCount--;
6989                    target.next = null;
6990                }
6991            }
6992            target.child = child;
6993            target.pointerIdBits = pointerIdBits;
6994            return target;
6995        }
6996
6997        public void recycle() {
6998            synchronized (sRecycleLock) {
6999                if (sRecycledCount < MAX_RECYCLED) {
7000                    next = sRecycleBin;
7001                    sRecycleBin = this;
7002                    sRecycledCount += 1;
7003                } else {
7004                    next = null;
7005                }
7006                child = null;
7007            }
7008        }
7009    }
7010
7011    /* Describes a hovered view. */
7012    private static final class HoverTarget {
7013        private static final int MAX_RECYCLED = 32;
7014        private static final Object sRecycleLock = new Object[0];
7015        private static HoverTarget sRecycleBin;
7016        private static int sRecycledCount;
7017
7018        // The hovered child view.
7019        public View child;
7020
7021        // The next target in the target list.
7022        public HoverTarget next;
7023
7024        private HoverTarget() {
7025        }
7026
7027        public static HoverTarget obtain(View child) {
7028            final HoverTarget target;
7029            synchronized (sRecycleLock) {
7030                if (sRecycleBin == null) {
7031                    target = new HoverTarget();
7032                } else {
7033                    target = sRecycleBin;
7034                    sRecycleBin = target.next;
7035                     sRecycledCount--;
7036                    target.next = null;
7037                }
7038            }
7039            target.child = child;
7040            return target;
7041        }
7042
7043        public void recycle() {
7044            synchronized (sRecycleLock) {
7045                if (sRecycledCount < MAX_RECYCLED) {
7046                    next = sRecycleBin;
7047                    sRecycleBin = this;
7048                    sRecycledCount += 1;
7049                } else {
7050                    next = null;
7051                }
7052                child = null;
7053            }
7054        }
7055    }
7056
7057    /**
7058     * Pooled class that orderes the children of a ViewGroup from start
7059     * to end based on how they are laid out and the layout direction.
7060     */
7061    static class ChildListForAccessibility {
7062
7063        private static final int MAX_POOL_SIZE = 32;
7064
7065        private static final SynchronizedPool<ChildListForAccessibility> sPool =
7066                new SynchronizedPool<ChildListForAccessibility>(MAX_POOL_SIZE);
7067
7068        private final ArrayList<View> mChildren = new ArrayList<View>();
7069
7070        private final ArrayList<ViewLocationHolder> mHolders = new ArrayList<ViewLocationHolder>();
7071
7072        public static ChildListForAccessibility obtain(ViewGroup parent, boolean sort) {
7073            ChildListForAccessibility list = sPool.acquire();
7074            if (list == null) {
7075                list = new ChildListForAccessibility();
7076            }
7077            list.init(parent, sort);
7078            return list;
7079        }
7080
7081        public void recycle() {
7082            clear();
7083            sPool.release(this);
7084        }
7085
7086        public int getChildCount() {
7087            return mChildren.size();
7088        }
7089
7090        public View getChildAt(int index) {
7091            return mChildren.get(index);
7092        }
7093
7094        public int getChildIndex(View child) {
7095            return mChildren.indexOf(child);
7096        }
7097
7098        private void init(ViewGroup parent, boolean sort) {
7099            ArrayList<View> children = mChildren;
7100            final int childCount = parent.getChildCount();
7101            for (int i = 0; i < childCount; i++) {
7102                View child = parent.getChildAt(i);
7103                children.add(child);
7104            }
7105            if (sort) {
7106                ArrayList<ViewLocationHolder> holders = mHolders;
7107                for (int i = 0; i < childCount; i++) {
7108                    View child = children.get(i);
7109                    ViewLocationHolder holder = ViewLocationHolder.obtain(parent, child);
7110                    holders.add(holder);
7111                }
7112                Collections.sort(holders);
7113                for (int i = 0; i < childCount; i++) {
7114                    ViewLocationHolder holder = holders.get(i);
7115                    children.set(i, holder.mView);
7116                    holder.recycle();
7117                }
7118                holders.clear();
7119            }
7120        }
7121
7122        private void clear() {
7123            mChildren.clear();
7124        }
7125    }
7126
7127    /**
7128     * Pooled class that holds a View and its location with respect to
7129     * a specified root. This enables sorting of views based on their
7130     * coordinates without recomputing the position relative to the root
7131     * on every comparison.
7132     */
7133    static class ViewLocationHolder implements Comparable<ViewLocationHolder> {
7134
7135        private static final int MAX_POOL_SIZE = 32;
7136
7137        private static final SynchronizedPool<ViewLocationHolder> sPool =
7138                new SynchronizedPool<ViewLocationHolder>(MAX_POOL_SIZE);
7139
7140        private final Rect mLocation = new Rect();
7141
7142        public View mView;
7143
7144        private int mLayoutDirection;
7145
7146        public static ViewLocationHolder obtain(ViewGroup root, View view) {
7147            ViewLocationHolder holder = sPool.acquire();
7148            if (holder == null) {
7149                holder = new ViewLocationHolder();
7150            }
7151            holder.init(root, view);
7152            return holder;
7153        }
7154
7155        public void recycle() {
7156            clear();
7157            sPool.release(this);
7158        }
7159
7160        @Override
7161        public int compareTo(ViewLocationHolder another) {
7162            // This instance is greater than an invalid argument.
7163            if (another == null) {
7164                return 1;
7165            }
7166            // We are ordering left-to-right, top-to-bottom.
7167            if (mLayoutDirection == LAYOUT_DIRECTION_LTR) {
7168                final int leftDifference = mLocation.left - another.mLocation.left;
7169                if (leftDifference != 0) {
7170                    return leftDifference;
7171                }
7172            } else { // RTL
7173                final int rightDifference = mLocation.right - another.mLocation.right;
7174                if (rightDifference != 0) {
7175                    return -rightDifference;
7176                }
7177            }
7178            // We are ordering left-to-right, top-to-bottom.
7179            final int topDifference = mLocation.top - another.mLocation.top;
7180            if (topDifference != 0) {
7181                return topDifference;
7182            }
7183            // Break tie by height.
7184            final int heightDiference = mLocation.height() - another.mLocation.height();
7185            if (heightDiference != 0) {
7186                return -heightDiference;
7187            }
7188            // Break tie by width.
7189            final int widthDiference = mLocation.width() - another.mLocation.width();
7190            if (widthDiference != 0) {
7191                return -widthDiference;
7192            }
7193            // Just break the tie somehow. The accessibliity ids are unique
7194            // and stable, hence this is deterministic tie breaking.
7195            return mView.getAccessibilityViewId() - another.mView.getAccessibilityViewId();
7196        }
7197
7198        private void init(ViewGroup root, View view) {
7199            Rect viewLocation = mLocation;
7200            view.getDrawingRect(viewLocation);
7201            root.offsetDescendantRectToMyCoords(view, viewLocation);
7202            mView = view;
7203            mLayoutDirection = root.getLayoutDirection();
7204        }
7205
7206        private void clear() {
7207            mView = null;
7208            mLocation.set(0, 0, 0, 0);
7209        }
7210    }
7211
7212    private static Paint getDebugPaint() {
7213        if (sDebugPaint == null) {
7214            sDebugPaint = new Paint();
7215            sDebugPaint.setAntiAlias(false);
7216        }
7217        return sDebugPaint;
7218    }
7219
7220    private static void drawRect(Canvas canvas, Paint paint, int x1, int y1, int x2, int y2) {
7221        if (sDebugLines== null) {
7222            // TODO: This won't work with multiple UI threads in a single process
7223            sDebugLines = new float[16];
7224        }
7225
7226        sDebugLines[0] = x1;
7227        sDebugLines[1] = y1;
7228        sDebugLines[2] = x2;
7229        sDebugLines[3] = y1;
7230
7231        sDebugLines[4] = x2;
7232        sDebugLines[5] = y1;
7233        sDebugLines[6] = x2;
7234        sDebugLines[7] = y2;
7235
7236        sDebugLines[8] = x2;
7237        sDebugLines[9] = y2;
7238        sDebugLines[10] = x1;
7239        sDebugLines[11] = y2;
7240
7241        sDebugLines[12] = x1;
7242        sDebugLines[13] = y2;
7243        sDebugLines[14] = x1;
7244        sDebugLines[15] = y1;
7245
7246        canvas.drawLines(sDebugLines, paint);
7247    }
7248}
7249