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