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