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