ViewGroup.java revision 604f440dfd6e5ee857f1e71d12c635d4ee1afcbc
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    private static Paint DEBUG_PAINT;
386
387    private static Paint getDebugPaint() {
388         if (DEBUG_PAINT == null) {
389             DEBUG_PAINT = new Paint();
390             DEBUG_PAINT.setStyle(Paint.Style.STROKE);
391         }
392         return DEBUG_PAINT;
393    }
394
395    // Used to draw cached views
396    Paint mCachePaint;
397
398    // Used to animate add/remove changes in layout
399    private LayoutTransition mTransition;
400
401    // The set of views that are currently being transitioned. This list is used to track views
402    // being removed that should not actually be removed from the parent yet because they are
403    // being animated.
404    private ArrayList<View> mTransitioningViews;
405
406    // List of children changing visibility. This is used to potentially keep rendering
407    // views during a transition when they otherwise would have become gone/invisible
408    private ArrayList<View> mVisibilityChangingChildren;
409
410    // Indicates whether this container will use its children layers to draw
411    @ViewDebug.ExportedProperty(category = "drawing")
412    boolean mDrawLayers = true;
413
414    // Indicates how many of this container's child subtrees contain transient state
415    @ViewDebug.ExportedProperty(category = "layout")
416    private int mChildCountWithTransientState = 0;
417
418    public ViewGroup(Context context) {
419        super(context);
420        initViewGroup();
421    }
422
423    public ViewGroup(Context context, AttributeSet attrs) {
424        super(context, attrs);
425        initViewGroup();
426        initFromAttributes(context, attrs);
427    }
428
429    public ViewGroup(Context context, AttributeSet attrs, int defStyle) {
430        super(context, attrs, defStyle);
431        initViewGroup();
432        initFromAttributes(context, attrs);
433    }
434
435    private boolean debugDraw() {
436        return mAttachInfo != null && mAttachInfo.mDebugLayout;
437    }
438
439    private void initViewGroup() {
440        // ViewGroup doesn't draw by default
441        if (!debugDraw()) {
442            setFlags(WILL_NOT_DRAW, DRAW_MASK);
443        }
444        mGroupFlags |= FLAG_CLIP_CHILDREN;
445        mGroupFlags |= FLAG_CLIP_TO_PADDING;
446        mGroupFlags |= FLAG_ANIMATION_DONE;
447        mGroupFlags |= FLAG_ANIMATION_CACHE;
448        mGroupFlags |= FLAG_ALWAYS_DRAWN_WITH_CACHE;
449
450        if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
451            mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
452        }
453
454        setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS);
455
456        mChildren = new View[ARRAY_INITIAL_CAPACITY];
457        mChildrenCount = 0;
458
459        mPersistentDrawingCache = PERSISTENT_SCROLLING_CACHE;
460    }
461
462    private void initFromAttributes(Context context, AttributeSet attrs) {
463        TypedArray a = context.obtainStyledAttributes(attrs,
464                R.styleable.ViewGroup);
465
466        final int N = a.getIndexCount();
467        for (int i = 0; i < N; i++) {
468            int attr = a.getIndex(i);
469            switch (attr) {
470                case R.styleable.ViewGroup_clipChildren:
471                    setClipChildren(a.getBoolean(attr, true));
472                    break;
473                case R.styleable.ViewGroup_clipToPadding:
474                    setClipToPadding(a.getBoolean(attr, true));
475                    break;
476                case R.styleable.ViewGroup_animationCache:
477                    setAnimationCacheEnabled(a.getBoolean(attr, true));
478                    break;
479                case R.styleable.ViewGroup_persistentDrawingCache:
480                    setPersistentDrawingCache(a.getInt(attr, PERSISTENT_SCROLLING_CACHE));
481                    break;
482                case R.styleable.ViewGroup_addStatesFromChildren:
483                    setAddStatesFromChildren(a.getBoolean(attr, false));
484                    break;
485                case R.styleable.ViewGroup_alwaysDrawnWithCache:
486                    setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true));
487                    break;
488                case R.styleable.ViewGroup_layoutAnimation:
489                    int id = a.getResourceId(attr, -1);
490                    if (id > 0) {
491                        setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id));
492                    }
493                    break;
494                case R.styleable.ViewGroup_descendantFocusability:
495                    setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]);
496                    break;
497                case R.styleable.ViewGroup_splitMotionEvents:
498                    setMotionEventSplittingEnabled(a.getBoolean(attr, false));
499                    break;
500                case R.styleable.ViewGroup_animateLayoutChanges:
501                    boolean animateLayoutChanges = a.getBoolean(attr, false);
502                    if (animateLayoutChanges) {
503                        setLayoutTransition(new LayoutTransition());
504                    }
505                    break;
506            }
507        }
508
509        a.recycle();
510    }
511
512    /**
513     * Gets the descendant focusability of this view group.  The descendant
514     * focusability defines the relationship between this view group and its
515     * descendants when looking for a view to take focus in
516     * {@link #requestFocus(int, android.graphics.Rect)}.
517     *
518     * @return one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
519     *   {@link #FOCUS_BLOCK_DESCENDANTS}.
520     */
521    @ViewDebug.ExportedProperty(category = "focus", mapping = {
522        @ViewDebug.IntToString(from = FOCUS_BEFORE_DESCENDANTS, to = "FOCUS_BEFORE_DESCENDANTS"),
523        @ViewDebug.IntToString(from = FOCUS_AFTER_DESCENDANTS, to = "FOCUS_AFTER_DESCENDANTS"),
524        @ViewDebug.IntToString(from = FOCUS_BLOCK_DESCENDANTS, to = "FOCUS_BLOCK_DESCENDANTS")
525    })
526    public int getDescendantFocusability() {
527        return mGroupFlags & FLAG_MASK_FOCUSABILITY;
528    }
529
530    /**
531     * Set the descendant focusability of this view group. This defines the relationship
532     * between this view group and its descendants when looking for a view to
533     * take focus in {@link #requestFocus(int, android.graphics.Rect)}.
534     *
535     * @param focusability one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
536     *   {@link #FOCUS_BLOCK_DESCENDANTS}.
537     */
538    public void setDescendantFocusability(int focusability) {
539        switch (focusability) {
540            case FOCUS_BEFORE_DESCENDANTS:
541            case FOCUS_AFTER_DESCENDANTS:
542            case FOCUS_BLOCK_DESCENDANTS:
543                break;
544            default:
545                throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, "
546                        + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS");
547        }
548        mGroupFlags &= ~FLAG_MASK_FOCUSABILITY;
549        mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY);
550    }
551
552    /**
553     * {@inheritDoc}
554     */
555    @Override
556    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
557        if (mFocused != null) {
558            mFocused.unFocus();
559            mFocused = null;
560        }
561        super.handleFocusGainInternal(direction, previouslyFocusedRect);
562    }
563
564    /**
565     * {@inheritDoc}
566     */
567    public void requestChildFocus(View child, View focused) {
568        if (DBG) {
569            System.out.println(this + " requestChildFocus()");
570        }
571        if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
572            return;
573        }
574
575        // Unfocus us, if necessary
576        super.unFocus();
577
578        // We had a previous notion of who had focus. Clear it.
579        if (mFocused != child) {
580            if (mFocused != null) {
581                mFocused.unFocus();
582            }
583
584            mFocused = child;
585        }
586        if (mParent != null) {
587            mParent.requestChildFocus(this, focused);
588        }
589    }
590
591    /**
592     * {@inheritDoc}
593     */
594    public void focusableViewAvailable(View v) {
595        if (mParent != null
596                // shortcut: don't report a new focusable view if we block our descendants from
597                // getting focus
598                && (getDescendantFocusability() != FOCUS_BLOCK_DESCENDANTS)
599                // shortcut: don't report a new focusable view if we already are focused
600                // (and we don't prefer our descendants)
601                //
602                // note: knowing that mFocused is non-null is not a good enough reason
603                // to break the traversal since in that case we'd actually have to find
604                // the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and
605                // an ancestor of v; this will get checked for at ViewAncestor
606                && !(isFocused() && getDescendantFocusability() != FOCUS_AFTER_DESCENDANTS)) {
607            mParent.focusableViewAvailable(v);
608        }
609    }
610
611    /**
612     * {@inheritDoc}
613     */
614    public boolean showContextMenuForChild(View originalView) {
615        return mParent != null && mParent.showContextMenuForChild(originalView);
616    }
617
618    /**
619     * {@inheritDoc}
620     */
621    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
622        return mParent != null ? mParent.startActionModeForChild(originalView, callback) : null;
623    }
624
625    /**
626     * Find the nearest view in the specified direction that wants to take
627     * focus.
628     *
629     * @param focused The view that currently has focus
630     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and
631     *        FOCUS_RIGHT, or 0 for not applicable.
632     */
633    public View focusSearch(View focused, int direction) {
634        if (isRootNamespace()) {
635            // root namespace means we should consider ourselves the top of the
636            // tree for focus searching; otherwise we could be focus searching
637            // into other tabs.  see LocalActivityManager and TabHost for more info
638            return FocusFinder.getInstance().findNextFocus(this, focused, direction);
639        } else if (mParent != null) {
640            return mParent.focusSearch(focused, direction);
641        }
642        return null;
643    }
644
645    /**
646     * {@inheritDoc}
647     */
648    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
649        return false;
650    }
651
652    /**
653     * {@inheritDoc}
654     */
655    @Override
656    public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) {
657        ViewParent parent = mParent;
658        if (parent == null) {
659            return false;
660        }
661        final boolean propagate = onRequestSendAccessibilityEvent(child, event);
662        if (!propagate) {
663            return false;
664        }
665        return parent.requestSendAccessibilityEvent(this, event);
666    }
667
668    /**
669     * Called when a child has requested sending an {@link AccessibilityEvent} and
670     * gives an opportunity to its parent to augment the event.
671     * <p>
672     * If an {@link android.view.View.AccessibilityDelegate} has been specified via calling
673     * {@link android.view.View#setAccessibilityDelegate(android.view.View.AccessibilityDelegate)} its
674     * {@link android.view.View.AccessibilityDelegate#onRequestSendAccessibilityEvent(ViewGroup, View, AccessibilityEvent)}
675     * is responsible for handling this call.
676     * </p>
677     *
678     * @param child The child which requests sending the event.
679     * @param event The event to be sent.
680     * @return True if the event should be sent.
681     *
682     * @see #requestSendAccessibilityEvent(View, AccessibilityEvent)
683     */
684    public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) {
685        if (mAccessibilityDelegate != null) {
686            return mAccessibilityDelegate.onRequestSendAccessibilityEvent(this, child, event);
687        } else {
688            return onRequestSendAccessibilityEventInternal(child, event);
689        }
690    }
691
692    /**
693     * @see #onRequestSendAccessibilityEvent(View, AccessibilityEvent)
694     *
695     * Note: Called from the default {@link View.AccessibilityDelegate}.
696     */
697    boolean onRequestSendAccessibilityEventInternal(View child, AccessibilityEvent event) {
698        return true;
699    }
700
701    /**
702     * Called when a child view has changed whether or not it is tracking transient state.
703     *
704     * @hide
705     */
706    public void childHasTransientStateChanged(View child, boolean childHasTransientState) {
707        final boolean oldHasTransientState = hasTransientState();
708        if (childHasTransientState) {
709            mChildCountWithTransientState++;
710        } else {
711            mChildCountWithTransientState--;
712        }
713
714        final boolean newHasTransientState = hasTransientState();
715        if (mParent != null && oldHasTransientState != newHasTransientState) {
716            try {
717                mParent.childHasTransientStateChanged(this, newHasTransientState);
718            } catch (AbstractMethodError e) {
719                Log.e(TAG, mParent.getClass().getSimpleName() +
720                        " does not fully implement ViewParent", e);
721            }
722        }
723    }
724
725    /**
726     * @hide
727     */
728    @Override
729    public boolean hasTransientState() {
730        return mChildCountWithTransientState > 0 || super.hasTransientState();
731    }
732
733    /**
734     * {@inheritDoc}
735     */
736    @Override
737    public boolean dispatchUnhandledMove(View focused, int direction) {
738        return mFocused != null &&
739                mFocused.dispatchUnhandledMove(focused, direction);
740    }
741
742    /**
743     * {@inheritDoc}
744     */
745    public void clearChildFocus(View child) {
746        if (DBG) {
747            System.out.println(this + " clearChildFocus()");
748        }
749
750        mFocused = null;
751        if (mParent != null) {
752            mParent.clearChildFocus(this);
753        }
754    }
755
756    /**
757     * {@inheritDoc}
758     */
759    @Override
760    public void clearFocus() {
761        if (DBG) {
762            System.out.println(this + " clearFocus()");
763        }
764        if (mFocused == null) {
765            super.clearFocus();
766        } else {
767            mFocused.clearFocus();
768            mFocused = null;
769        }
770    }
771
772    /**
773     * {@inheritDoc}
774     */
775    @Override
776    void unFocus() {
777        if (DBG) {
778            System.out.println(this + " unFocus()");
779        }
780        if (mFocused == null) {
781            super.unFocus();
782        } else {
783            mFocused.unFocus();
784            mFocused = null;
785        }
786    }
787
788    /**
789     * Returns the focused child of this view, if any. The child may have focus
790     * or contain focus.
791     *
792     * @return the focused child or null.
793     */
794    public View getFocusedChild() {
795        return mFocused;
796    }
797
798    /**
799     * Returns true if this view has or contains focus
800     *
801     * @return true if this view has or contains focus
802     */
803    @Override
804    public boolean hasFocus() {
805        return (mPrivateFlags & FOCUSED) != 0 || mFocused != null;
806    }
807
808    /*
809     * (non-Javadoc)
810     *
811     * @see android.view.View#findFocus()
812     */
813    @Override
814    public View findFocus() {
815        if (DBG) {
816            System.out.println("Find focus in " + this + ": flags="
817                    + isFocused() + ", child=" + mFocused);
818        }
819
820        if (isFocused()) {
821            return this;
822        }
823
824        if (mFocused != null) {
825            return mFocused.findFocus();
826        }
827        return null;
828    }
829
830    /**
831     * {@inheritDoc}
832     */
833    @Override
834    public boolean hasFocusable() {
835        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
836            return false;
837        }
838
839        if (isFocusable()) {
840            return true;
841        }
842
843        final int descendantFocusability = getDescendantFocusability();
844        if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
845            final int count = mChildrenCount;
846            final View[] children = mChildren;
847
848            for (int i = 0; i < count; i++) {
849                final View child = children[i];
850                if (child.hasFocusable()) {
851                    return true;
852                }
853            }
854        }
855
856        return false;
857    }
858
859    /**
860     * {@inheritDoc}
861     */
862    @Override
863    public void addFocusables(ArrayList<View> views, int direction) {
864        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
865    }
866
867    /**
868     * {@inheritDoc}
869     */
870    @Override
871    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
872        final int focusableCount = views.size();
873
874        final int descendantFocusability = getDescendantFocusability();
875
876        if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
877            final int count = mChildrenCount;
878            final View[] children = mChildren;
879
880            for (int i = 0; i < count; i++) {
881                final View child = children[i];
882                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
883                    child.addFocusables(views, direction, focusableMode);
884                }
885            }
886        }
887
888        // we add ourselves (if focusable) in all cases except for when we are
889        // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable.  this is
890        // to avoid the focus search finding layouts when a more precise search
891        // among the focusable children would be more interesting.
892        if (
893            descendantFocusability != FOCUS_AFTER_DESCENDANTS ||
894                // No focusable descendants
895                (focusableCount == views.size())) {
896            super.addFocusables(views, direction, focusableMode);
897        }
898    }
899
900    @Override
901    public void findViewsWithText(ArrayList<View> outViews, CharSequence text, int flags) {
902        super.findViewsWithText(outViews, text, flags);
903        final int childrenCount = mChildrenCount;
904        final View[] children = mChildren;
905        for (int i = 0; i < childrenCount; i++) {
906            View child = children[i];
907            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
908                    && (child.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
909                child.findViewsWithText(outViews, text, flags);
910            }
911        }
912    }
913
914    @Override
915    View findViewByAccessibilityIdTraversal(int accessibilityId) {
916        View foundView = super.findViewByAccessibilityIdTraversal(accessibilityId);
917        if (foundView != null) {
918            return foundView;
919        }
920        final int childrenCount = mChildrenCount;
921        final View[] children = mChildren;
922        for (int i = 0; i < childrenCount; i++) {
923            View child = children[i];
924            foundView = child.findViewByAccessibilityIdTraversal(accessibilityId);
925            if (foundView != null) {
926                return foundView;
927            }
928        }
929        return null;
930    }
931
932    /**
933     * {@inheritDoc}
934     */
935    @Override
936    public void dispatchWindowFocusChanged(boolean hasFocus) {
937        super.dispatchWindowFocusChanged(hasFocus);
938        final int count = mChildrenCount;
939        final View[] children = mChildren;
940        for (int i = 0; i < count; i++) {
941            children[i].dispatchWindowFocusChanged(hasFocus);
942        }
943    }
944
945    /**
946     * {@inheritDoc}
947     */
948    @Override
949    public void addTouchables(ArrayList<View> views) {
950        super.addTouchables(views);
951
952        final int count = mChildrenCount;
953        final View[] children = mChildren;
954
955        for (int i = 0; i < count; i++) {
956            final View child = children[i];
957            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
958                child.addTouchables(views);
959            }
960        }
961    }
962
963    /**
964     * @hide
965     */
966    @Override
967    public void makeOptionalFitsSystemWindows() {
968        super.makeOptionalFitsSystemWindows();
969        final int count = mChildrenCount;
970        final View[] children = mChildren;
971        for (int i = 0; i < count; i++) {
972            children[i].makeOptionalFitsSystemWindows();
973        }
974    }
975
976    /**
977     * {@inheritDoc}
978     */
979    @Override
980    public void dispatchDisplayHint(int hint) {
981        super.dispatchDisplayHint(hint);
982        final int count = mChildrenCount;
983        final View[] children = mChildren;
984        for (int i = 0; i < count; i++) {
985            children[i].dispatchDisplayHint(hint);
986        }
987    }
988
989    /**
990     * Called when a view's visibility has changed. Notify the parent to take any appropriate
991     * action.
992     *
993     * @param child The view whose visibility has changed
994     * @param oldVisibility The previous visibility value (GONE, INVISIBLE, or VISIBLE).
995     * @param newVisibility The new visibility value (GONE, INVISIBLE, or VISIBLE).
996     * @hide
997     */
998    protected void onChildVisibilityChanged(View child, int oldVisibility, int newVisibility) {
999        if (mTransition != null) {
1000            if (newVisibility == VISIBLE) {
1001                mTransition.showChild(this, child, oldVisibility);
1002            } else {
1003                mTransition.hideChild(this, child, newVisibility);
1004                // Only track this on disappearing views - appearing views are already visible
1005                // and don't need special handling during drawChild()
1006                if (mVisibilityChangingChildren == null) {
1007                    mVisibilityChangingChildren = new ArrayList<View>();
1008                }
1009                mVisibilityChangingChildren.add(child);
1010                if (mTransitioningViews != null && mTransitioningViews.contains(child)) {
1011                    addDisappearingView(child);
1012                }
1013            }
1014        }
1015
1016        // in all cases, for drags
1017        if (mCurrentDrag != null) {
1018            if (newVisibility == VISIBLE) {
1019                notifyChildOfDrag(child);
1020            }
1021        }
1022    }
1023
1024    /**
1025     * {@inheritDoc}
1026     */
1027    @Override
1028    protected void dispatchVisibilityChanged(View changedView, int visibility) {
1029        super.dispatchVisibilityChanged(changedView, visibility);
1030        final int count = mChildrenCount;
1031        final View[] children = mChildren;
1032        for (int i = 0; i < count; i++) {
1033            children[i].dispatchVisibilityChanged(changedView, visibility);
1034        }
1035    }
1036
1037    /**
1038     * {@inheritDoc}
1039     */
1040    @Override
1041    public void dispatchWindowVisibilityChanged(int visibility) {
1042        super.dispatchWindowVisibilityChanged(visibility);
1043        final int count = mChildrenCount;
1044        final View[] children = mChildren;
1045        for (int i = 0; i < count; i++) {
1046            children[i].dispatchWindowVisibilityChanged(visibility);
1047        }
1048    }
1049
1050    /**
1051     * {@inheritDoc}
1052     */
1053    @Override
1054    public void dispatchConfigurationChanged(Configuration newConfig) {
1055        super.dispatchConfigurationChanged(newConfig);
1056        final int count = mChildrenCount;
1057        final View[] children = mChildren;
1058        for (int i = 0; i < count; i++) {
1059            children[i].dispatchConfigurationChanged(newConfig);
1060        }
1061    }
1062
1063    /**
1064     * {@inheritDoc}
1065     */
1066    public void recomputeViewAttributes(View child) {
1067        if (mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) {
1068            ViewParent parent = mParent;
1069            if (parent != null) parent.recomputeViewAttributes(this);
1070        }
1071    }
1072
1073    @Override
1074    void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) {
1075        if ((visibility & VISIBILITY_MASK) == VISIBLE) {
1076            super.dispatchCollectViewAttributes(attachInfo, visibility);
1077            final int count = mChildrenCount;
1078            final View[] children = mChildren;
1079            for (int i = 0; i < count; i++) {
1080                final View child = children[i];
1081                child.dispatchCollectViewAttributes(attachInfo,
1082                        visibility | (child.mViewFlags&VISIBILITY_MASK));
1083            }
1084        }
1085    }
1086
1087    /**
1088     * {@inheritDoc}
1089     */
1090    public void bringChildToFront(View child) {
1091        int index = indexOfChild(child);
1092        if (index >= 0) {
1093            removeFromArray(index);
1094            addInArray(child, mChildrenCount);
1095            child.mParent = this;
1096        }
1097    }
1098
1099    /**
1100     * {@inheritDoc}
1101     */
1102    // TODO: Write real docs
1103    @Override
1104    public boolean dispatchDragEvent(DragEvent event) {
1105        boolean retval = false;
1106        final float tx = event.mX;
1107        final float ty = event.mY;
1108
1109        ViewRootImpl root = getViewRootImpl();
1110
1111        // Dispatch down the view hierarchy
1112        switch (event.mAction) {
1113        case DragEvent.ACTION_DRAG_STARTED: {
1114            // clear state to recalculate which views we drag over
1115            mCurrentDragView = null;
1116
1117            // Set up our tracking of drag-started notifications
1118            mCurrentDrag = DragEvent.obtain(event);
1119            if (mDragNotifiedChildren == null) {
1120                mDragNotifiedChildren = new HashSet<View>();
1121            } else {
1122                mDragNotifiedChildren.clear();
1123            }
1124
1125            // Now dispatch down to our children, caching the responses
1126            mChildAcceptsDrag = false;
1127            final int count = mChildrenCount;
1128            final View[] children = mChildren;
1129            for (int i = 0; i < count; i++) {
1130                final View child = children[i];
1131                child.mPrivateFlags2 &= ~View.DRAG_MASK;
1132                if (child.getVisibility() == VISIBLE) {
1133                    final boolean handled = notifyChildOfDrag(children[i]);
1134                    if (handled) {
1135                        mChildAcceptsDrag = true;
1136                    }
1137                }
1138            }
1139
1140            // Return HANDLED if one of our children can accept the drag
1141            if (mChildAcceptsDrag) {
1142                retval = true;
1143            }
1144        } break;
1145
1146        case DragEvent.ACTION_DRAG_ENDED: {
1147            // Release the bookkeeping now that the drag lifecycle has ended
1148            if (mDragNotifiedChildren != null) {
1149                for (View child : mDragNotifiedChildren) {
1150                    // If a child was notified about an ongoing drag, it's told that it's over
1151                    child.dispatchDragEvent(event);
1152                    child.mPrivateFlags2 &= ~View.DRAG_MASK;
1153                    child.refreshDrawableState();
1154                }
1155
1156                mDragNotifiedChildren.clear();
1157                mCurrentDrag.recycle();
1158                mCurrentDrag = null;
1159            }
1160
1161            // We consider drag-ended to have been handled if one of our children
1162            // had offered to handle the drag.
1163            if (mChildAcceptsDrag) {
1164                retval = true;
1165            }
1166        } break;
1167
1168        case DragEvent.ACTION_DRAG_LOCATION: {
1169            // Find the [possibly new] drag target
1170            final View target = findFrontmostDroppableChildAt(event.mX, event.mY, mLocalPoint);
1171
1172            // If we've changed apparent drag target, tell the view root which view
1173            // we're over now [for purposes of the eventual drag-recipient-changed
1174            // notifications to the framework] and tell the new target that the drag
1175            // has entered its bounds.  The root will see setDragFocus() calls all
1176            // the way down to the final leaf view that is handling the LOCATION event
1177            // before reporting the new potential recipient to the framework.
1178            if (mCurrentDragView != target) {
1179                root.setDragFocus(target);
1180
1181                final int action = event.mAction;
1182                // If we've dragged off of a child view, send it the EXITED message
1183                if (mCurrentDragView != null) {
1184                    final View view = mCurrentDragView;
1185                    event.mAction = DragEvent.ACTION_DRAG_EXITED;
1186                    view.dispatchDragEvent(event);
1187                    view.mPrivateFlags2 &= ~View.DRAG_HOVERED;
1188                    view.refreshDrawableState();
1189                }
1190                mCurrentDragView = target;
1191
1192                // If we've dragged over a new child view, send it the ENTERED message
1193                if (target != null) {
1194                    event.mAction = DragEvent.ACTION_DRAG_ENTERED;
1195                    target.dispatchDragEvent(event);
1196                    target.mPrivateFlags2 |= View.DRAG_HOVERED;
1197                    target.refreshDrawableState();
1198                }
1199                event.mAction = action;  // restore the event's original state
1200            }
1201
1202            // Dispatch the actual drag location notice, localized into its coordinates
1203            if (target != null) {
1204                event.mX = mLocalPoint.x;
1205                event.mY = mLocalPoint.y;
1206
1207                retval = target.dispatchDragEvent(event);
1208
1209                event.mX = tx;
1210                event.mY = ty;
1211            }
1212        } break;
1213
1214        /* Entered / exited dispatch
1215         *
1216         * DRAG_ENTERED is not dispatched downwards from ViewGroup.  The reason for this is
1217         * that we're about to get the corresponding LOCATION event, which we will use to
1218         * determine which of our children is the new target; at that point we will
1219         * push a DRAG_ENTERED down to the new target child [which may itself be a ViewGroup].
1220         *
1221         * DRAG_EXITED *is* dispatched all the way down immediately: once we know the
1222         * drag has left this ViewGroup, we know by definition that every contained subview
1223         * is also no longer under the drag point.
1224         */
1225
1226        case DragEvent.ACTION_DRAG_EXITED: {
1227            if (mCurrentDragView != null) {
1228                final View view = mCurrentDragView;
1229                view.dispatchDragEvent(event);
1230                view.mPrivateFlags2 &= ~View.DRAG_HOVERED;
1231                view.refreshDrawableState();
1232
1233                mCurrentDragView = null;
1234            }
1235        } break;
1236
1237        case DragEvent.ACTION_DROP: {
1238            if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, "Drop event: " + event);
1239            View target = findFrontmostDroppableChildAt(event.mX, event.mY, mLocalPoint);
1240            if (target != null) {
1241                if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, "   dispatch drop to " + target);
1242                event.mX = mLocalPoint.x;
1243                event.mY = mLocalPoint.y;
1244                retval = target.dispatchDragEvent(event);
1245                event.mX = tx;
1246                event.mY = ty;
1247            } else {
1248                if (ViewDebug.DEBUG_DRAG) {
1249                    Log.d(View.VIEW_LOG_TAG, "   not dropped on an accepting view");
1250                }
1251            }
1252        } break;
1253        }
1254
1255        // If none of our children could handle the event, try here
1256        if (!retval) {
1257            // Call up to the View implementation that dispatches to installed listeners
1258            retval = super.dispatchDragEvent(event);
1259        }
1260        return retval;
1261    }
1262
1263    // Find the frontmost child view that lies under the given point, and calculate
1264    // the position within its own local coordinate system.
1265    View findFrontmostDroppableChildAt(float x, float y, PointF outLocalPoint) {
1266        final int count = mChildrenCount;
1267        final View[] children = mChildren;
1268        for (int i = count - 1; i >= 0; i--) {
1269            final View child = children[i];
1270            if (!child.canAcceptDrag()) {
1271                continue;
1272            }
1273
1274            if (isTransformedTouchPointInView(x, y, child, outLocalPoint)) {
1275                return child;
1276            }
1277        }
1278        return null;
1279    }
1280
1281    boolean notifyChildOfDrag(View child) {
1282        if (ViewDebug.DEBUG_DRAG) {
1283            Log.d(View.VIEW_LOG_TAG, "Sending drag-started to view: " + child);
1284        }
1285
1286        boolean canAccept = false;
1287        if (! mDragNotifiedChildren.contains(child)) {
1288            mDragNotifiedChildren.add(child);
1289            canAccept = child.dispatchDragEvent(mCurrentDrag);
1290            if (canAccept && !child.canAcceptDrag()) {
1291                child.mPrivateFlags2 |= View.DRAG_CAN_ACCEPT;
1292                child.refreshDrawableState();
1293            }
1294        }
1295        return canAccept;
1296    }
1297
1298    @Override
1299    public void dispatchWindowSystemUiVisiblityChanged(int visible) {
1300        super.dispatchWindowSystemUiVisiblityChanged(visible);
1301
1302        final int count = mChildrenCount;
1303        final View[] children = mChildren;
1304        for (int i=0; i <count; i++) {
1305            final View child = children[i];
1306            child.dispatchWindowSystemUiVisiblityChanged(visible);
1307        }
1308    }
1309
1310    @Override
1311    public void dispatchSystemUiVisibilityChanged(int visible) {
1312        super.dispatchSystemUiVisibilityChanged(visible);
1313
1314        final int count = mChildrenCount;
1315        final View[] children = mChildren;
1316        for (int i=0; i <count; i++) {
1317            final View child = children[i];
1318            child.dispatchSystemUiVisibilityChanged(visible);
1319        }
1320    }
1321
1322    @Override
1323    void updateLocalSystemUiVisibility(int localValue, int localChanges) {
1324        super.updateLocalSystemUiVisibility(localValue, localChanges);
1325
1326        final int count = mChildrenCount;
1327        final View[] children = mChildren;
1328        for (int i=0; i <count; i++) {
1329            final View child = children[i];
1330            child.updateLocalSystemUiVisibility(localValue, localChanges);
1331        }
1332    }
1333
1334    /**
1335     * {@inheritDoc}
1336     */
1337    @Override
1338    public boolean dispatchKeyEventPreIme(KeyEvent event) {
1339        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
1340            return super.dispatchKeyEventPreIme(event);
1341        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
1342            return mFocused.dispatchKeyEventPreIme(event);
1343        }
1344        return false;
1345    }
1346
1347    /**
1348     * {@inheritDoc}
1349     */
1350    @Override
1351    public boolean dispatchKeyEvent(KeyEvent event) {
1352        if (mInputEventConsistencyVerifier != null) {
1353            mInputEventConsistencyVerifier.onKeyEvent(event, 1);
1354        }
1355
1356        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
1357            if (super.dispatchKeyEvent(event)) {
1358                return true;
1359            }
1360        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
1361            if (mFocused.dispatchKeyEvent(event)) {
1362                return true;
1363            }
1364        }
1365
1366        if (mInputEventConsistencyVerifier != null) {
1367            mInputEventConsistencyVerifier.onUnhandledEvent(event, 1);
1368        }
1369        return false;
1370    }
1371
1372    /**
1373     * {@inheritDoc}
1374     */
1375    @Override
1376    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
1377        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
1378            return super.dispatchKeyShortcutEvent(event);
1379        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
1380            return mFocused.dispatchKeyShortcutEvent(event);
1381        }
1382        return false;
1383    }
1384
1385    /**
1386     * {@inheritDoc}
1387     */
1388    @Override
1389    public boolean dispatchTrackballEvent(MotionEvent event) {
1390        if (mInputEventConsistencyVerifier != null) {
1391            mInputEventConsistencyVerifier.onTrackballEvent(event, 1);
1392        }
1393
1394        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
1395            if (super.dispatchTrackballEvent(event)) {
1396                return true;
1397            }
1398        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
1399            if (mFocused.dispatchTrackballEvent(event)) {
1400                return true;
1401            }
1402        }
1403
1404        if (mInputEventConsistencyVerifier != null) {
1405            mInputEventConsistencyVerifier.onUnhandledEvent(event, 1);
1406        }
1407        return false;
1408    }
1409
1410    /**
1411     * {@inheritDoc}
1412     */
1413    @SuppressWarnings({"ConstantConditions"})
1414    @Override
1415    protected boolean dispatchHoverEvent(MotionEvent event) {
1416        final int action = event.getAction();
1417
1418        // First check whether the view group wants to intercept the hover event.
1419        final boolean interceptHover = onInterceptHoverEvent(event);
1420        event.setAction(action); // restore action in case it was changed
1421
1422        MotionEvent eventNoHistory = event;
1423        boolean handled = false;
1424
1425        // Send events to the hovered children and build a new list of hover targets until
1426        // one is found that handles the event.
1427        HoverTarget firstOldHoverTarget = mFirstHoverTarget;
1428        mFirstHoverTarget = null;
1429        if (!interceptHover && action != MotionEvent.ACTION_HOVER_EXIT) {
1430            final float x = event.getX();
1431            final float y = event.getY();
1432            final int childrenCount = mChildrenCount;
1433            if (childrenCount != 0) {
1434                final View[] children = mChildren;
1435                HoverTarget lastHoverTarget = null;
1436                for (int i = childrenCount - 1; i >= 0; i--) {
1437                    final View child = children[i];
1438                    if (!canViewReceivePointerEvents(child)
1439                            || !isTransformedTouchPointInView(x, y, child, null)) {
1440                        continue;
1441                    }
1442
1443                    // Obtain a hover target for this child.  Dequeue it from the
1444                    // old hover target list if the child was previously hovered.
1445                    HoverTarget hoverTarget = firstOldHoverTarget;
1446                    final boolean wasHovered;
1447                    for (HoverTarget predecessor = null; ;) {
1448                        if (hoverTarget == null) {
1449                            hoverTarget = HoverTarget.obtain(child);
1450                            wasHovered = false;
1451                            break;
1452                        }
1453
1454                        if (hoverTarget.child == child) {
1455                            if (predecessor != null) {
1456                                predecessor.next = hoverTarget.next;
1457                            } else {
1458                                firstOldHoverTarget = hoverTarget.next;
1459                            }
1460                            hoverTarget.next = null;
1461                            wasHovered = true;
1462                            break;
1463                        }
1464
1465                        predecessor = hoverTarget;
1466                        hoverTarget = hoverTarget.next;
1467                    }
1468
1469                    // Enqueue the hover target onto the new hover target list.
1470                    if (lastHoverTarget != null) {
1471                        lastHoverTarget.next = hoverTarget;
1472                    } else {
1473                        lastHoverTarget = hoverTarget;
1474                        mFirstHoverTarget = hoverTarget;
1475                    }
1476
1477                    // Dispatch the event to the child.
1478                    if (action == MotionEvent.ACTION_HOVER_ENTER) {
1479                        if (!wasHovered) {
1480                            // Send the enter as is.
1481                            handled |= dispatchTransformedGenericPointerEvent(
1482                                    event, child); // enter
1483                        }
1484                    } else if (action == MotionEvent.ACTION_HOVER_MOVE) {
1485                        if (!wasHovered) {
1486                            // Synthesize an enter from a move.
1487                            eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1488                            eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
1489                            handled |= dispatchTransformedGenericPointerEvent(
1490                                    eventNoHistory, child); // enter
1491                            eventNoHistory.setAction(action);
1492
1493                            handled |= dispatchTransformedGenericPointerEvent(
1494                                    eventNoHistory, child); // move
1495                        } else {
1496                            // Send the move as is.
1497                            handled |= dispatchTransformedGenericPointerEvent(event, child);
1498                        }
1499                    }
1500                    if (handled) {
1501                        break;
1502                    }
1503                }
1504            }
1505        }
1506
1507        // Send exit events to all previously hovered children that are no longer hovered.
1508        while (firstOldHoverTarget != null) {
1509            final View child = firstOldHoverTarget.child;
1510
1511            // Exit the old hovered child.
1512            if (action == MotionEvent.ACTION_HOVER_EXIT) {
1513                // Send the exit as is.
1514                handled |= dispatchTransformedGenericPointerEvent(
1515                        event, child); // exit
1516            } else {
1517                // Synthesize an exit from a move or enter.
1518                // Ignore the result because hover focus has moved to a different view.
1519                if (action == MotionEvent.ACTION_HOVER_MOVE) {
1520                    dispatchTransformedGenericPointerEvent(
1521                            event, child); // move
1522                }
1523                eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1524                eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
1525                dispatchTransformedGenericPointerEvent(
1526                        eventNoHistory, child); // exit
1527                eventNoHistory.setAction(action);
1528            }
1529
1530            final HoverTarget nextOldHoverTarget = firstOldHoverTarget.next;
1531            firstOldHoverTarget.recycle();
1532            firstOldHoverTarget = nextOldHoverTarget;
1533        }
1534
1535        // Send events to the view group itself if no children have handled it.
1536        boolean newHoveredSelf = !handled;
1537        if (newHoveredSelf == mHoveredSelf) {
1538            if (newHoveredSelf) {
1539                // Send event to the view group as before.
1540                handled |= super.dispatchHoverEvent(event);
1541            }
1542        } else {
1543            if (mHoveredSelf) {
1544                // Exit the view group.
1545                if (action == MotionEvent.ACTION_HOVER_EXIT) {
1546                    // Send the exit as is.
1547                    handled |= super.dispatchHoverEvent(event); // exit
1548                } else {
1549                    // Synthesize an exit from a move or enter.
1550                    // Ignore the result because hover focus is moving to a different view.
1551                    if (action == MotionEvent.ACTION_HOVER_MOVE) {
1552                        super.dispatchHoverEvent(event); // move
1553                    }
1554                    eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1555                    eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT);
1556                    super.dispatchHoverEvent(eventNoHistory); // exit
1557                    eventNoHistory.setAction(action);
1558                }
1559                mHoveredSelf = false;
1560            }
1561
1562            if (newHoveredSelf) {
1563                // Enter the view group.
1564                if (action == MotionEvent.ACTION_HOVER_ENTER) {
1565                    // Send the enter as is.
1566                    handled |= super.dispatchHoverEvent(event); // enter
1567                    mHoveredSelf = true;
1568                } else if (action == MotionEvent.ACTION_HOVER_MOVE) {
1569                    // Synthesize an enter from a move.
1570                    eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory);
1571                    eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER);
1572                    handled |= super.dispatchHoverEvent(eventNoHistory); // enter
1573                    eventNoHistory.setAction(action);
1574
1575                    handled |= super.dispatchHoverEvent(eventNoHistory); // move
1576                    mHoveredSelf = true;
1577                }
1578            }
1579        }
1580
1581        // Recycle the copy of the event that we made.
1582        if (eventNoHistory != event) {
1583            eventNoHistory.recycle();
1584        }
1585
1586        // Done.
1587        return handled;
1588    }
1589
1590    private void exitHoverTargets() {
1591        if (mHoveredSelf || mFirstHoverTarget != null) {
1592            final long now = SystemClock.uptimeMillis();
1593            MotionEvent event = MotionEvent.obtain(now, now,
1594                    MotionEvent.ACTION_HOVER_EXIT, 0.0f, 0.0f, 0);
1595            event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
1596            dispatchHoverEvent(event);
1597            event.recycle();
1598        }
1599    }
1600
1601    private void cancelHoverTarget(View view) {
1602        HoverTarget predecessor = null;
1603        HoverTarget target = mFirstHoverTarget;
1604        while (target != null) {
1605            final HoverTarget next = target.next;
1606            if (target.child == view) {
1607                if (predecessor == null) {
1608                    mFirstHoverTarget = next;
1609                } else {
1610                    predecessor.next = next;
1611                }
1612                target.recycle();
1613
1614                final long now = SystemClock.uptimeMillis();
1615                MotionEvent event = MotionEvent.obtain(now, now,
1616                        MotionEvent.ACTION_HOVER_EXIT, 0.0f, 0.0f, 0);
1617                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
1618                view.dispatchHoverEvent(event);
1619                event.recycle();
1620                return;
1621            }
1622            predecessor = target;
1623            target = next;
1624        }
1625    }
1626
1627    /** @hide */
1628    @Override
1629    protected boolean hasHoveredChild() {
1630        return mFirstHoverTarget != null;
1631    }
1632
1633    @Override
1634    public void addChildrenForAccessibility(ArrayList<View> childrenForAccessibility) {
1635        View[] children = mChildren;
1636        final int childrenCount = mChildrenCount;
1637        for (int i = 0; i < childrenCount; i++) {
1638            View child = children[i];
1639            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
1640                    && (child.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
1641                if (child.includeForAccessibility()) {
1642                    childrenForAccessibility.add(child);
1643                } else {
1644                    child.addChildrenForAccessibility(childrenForAccessibility);
1645                }
1646            }
1647        }
1648    }
1649
1650    /**
1651     * @hide
1652     */
1653    @Override
1654    public void childAccessibilityStateChanged(View child) {
1655        if (mParent != null) {
1656            mParent.childAccessibilityStateChanged(child);
1657        }
1658    }
1659
1660    /**
1661     * Implement this method to intercept hover events before they are handled
1662     * by child views.
1663     * <p>
1664     * This method is called before dispatching a hover event to a child of
1665     * the view group or to the view group's own {@link #onHoverEvent} to allow
1666     * the view group a chance to intercept the hover event.
1667     * This method can also be used to watch all pointer motions that occur within
1668     * the bounds of the view group even when the pointer is hovering over
1669     * a child of the view group rather than over the view group itself.
1670     * </p><p>
1671     * The view group can prevent its children from receiving hover events by
1672     * implementing this method and returning <code>true</code> to indicate
1673     * that it would like to intercept hover events.  The view group must
1674     * continuously return <code>true</code> from {@link #onInterceptHoverEvent}
1675     * for as long as it wishes to continue intercepting hover events from
1676     * its children.
1677     * </p><p>
1678     * Interception preserves the invariant that at most one view can be
1679     * hovered at a time by transferring hover focus from the currently hovered
1680     * child to the view group or vice-versa as needed.
1681     * </p><p>
1682     * If this method returns <code>true</code> and a child is already hovered, then the
1683     * child view will first receive a hover exit event and then the view group
1684     * itself will receive a hover enter event in {@link #onHoverEvent}.
1685     * Likewise, if this method had previously returned <code>true</code> to intercept hover
1686     * events and instead returns <code>false</code> while the pointer is hovering
1687     * within the bounds of one of a child, then the view group will first receive a
1688     * hover exit event in {@link #onHoverEvent} and then the hovered child will
1689     * receive a hover enter event.
1690     * </p><p>
1691     * The default implementation always returns false.
1692     * </p>
1693     *
1694     * @param event The motion event that describes the hover.
1695     * @return True if the view group would like to intercept the hover event
1696     * and prevent its children from receiving it.
1697     */
1698    public boolean onInterceptHoverEvent(MotionEvent event) {
1699        return false;
1700    }
1701
1702    private static MotionEvent obtainMotionEventNoHistoryOrSelf(MotionEvent event) {
1703        if (event.getHistorySize() == 0) {
1704            return event;
1705        }
1706        return MotionEvent.obtainNoHistory(event);
1707    }
1708
1709    /**
1710     * {@inheritDoc}
1711     */
1712    @Override
1713    protected boolean dispatchGenericPointerEvent(MotionEvent event) {
1714        // Send the event to the child under the pointer.
1715        final int childrenCount = mChildrenCount;
1716        if (childrenCount != 0) {
1717            final View[] children = mChildren;
1718            final float x = event.getX();
1719            final float y = event.getY();
1720
1721            for (int i = childrenCount - 1; i >= 0; i--) {
1722                final View child = children[i];
1723                if (!canViewReceivePointerEvents(child)
1724                        || !isTransformedTouchPointInView(x, y, child, null)) {
1725                    continue;
1726                }
1727
1728                if (dispatchTransformedGenericPointerEvent(event, child)) {
1729                    return true;
1730                }
1731            }
1732        }
1733
1734        // No child handled the event.  Send it to this view group.
1735        return super.dispatchGenericPointerEvent(event);
1736    }
1737
1738    /**
1739     * {@inheritDoc}
1740     */
1741    @Override
1742    protected boolean dispatchGenericFocusedEvent(MotionEvent event) {
1743        // Send the event to the focused child or to this view group if it has focus.
1744        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
1745            return super.dispatchGenericFocusedEvent(event);
1746        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
1747            return mFocused.dispatchGenericMotionEvent(event);
1748        }
1749        return false;
1750    }
1751
1752    /**
1753     * Dispatches a generic pointer event to a child, taking into account
1754     * transformations that apply to the child.
1755     *
1756     * @param event The event to send.
1757     * @param child The view to send the event to.
1758     * @return {@code true} if the child handled the event.
1759     */
1760    private boolean dispatchTransformedGenericPointerEvent(MotionEvent event, View child) {
1761        final float offsetX = mScrollX - child.mLeft;
1762        final float offsetY = mScrollY - child.mTop;
1763
1764        boolean handled;
1765        if (!child.hasIdentityMatrix()) {
1766            MotionEvent transformedEvent = MotionEvent.obtain(event);
1767            transformedEvent.offsetLocation(offsetX, offsetY);
1768            transformedEvent.transform(child.getInverseMatrix());
1769            handled = child.dispatchGenericMotionEvent(transformedEvent);
1770            transformedEvent.recycle();
1771        } else {
1772            event.offsetLocation(offsetX, offsetY);
1773            handled = child.dispatchGenericMotionEvent(event);
1774            event.offsetLocation(-offsetX, -offsetY);
1775        }
1776        return handled;
1777    }
1778
1779    /**
1780     * {@inheritDoc}
1781     */
1782    @Override
1783    public boolean dispatchTouchEvent(MotionEvent ev) {
1784        if (mInputEventConsistencyVerifier != null) {
1785            mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
1786        }
1787
1788        boolean handled = false;
1789        if (onFilterTouchEventForSecurity(ev)) {
1790            final int action = ev.getAction();
1791            final int actionMasked = action & MotionEvent.ACTION_MASK;
1792
1793            // Handle an initial down.
1794            if (actionMasked == MotionEvent.ACTION_DOWN) {
1795                // Throw away all previous state when starting a new touch gesture.
1796                // The framework may have dropped the up or cancel event for the previous gesture
1797                // due to an app switch, ANR, or some other state change.
1798                cancelAndClearTouchTargets(ev);
1799                resetTouchState();
1800            }
1801
1802            // Check for interception.
1803            final boolean intercepted;
1804            if (actionMasked == MotionEvent.ACTION_DOWN
1805                    || mFirstTouchTarget != null) {
1806                final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
1807                if (!disallowIntercept) {
1808                    intercepted = onInterceptTouchEvent(ev);
1809                    ev.setAction(action); // restore action in case it was changed
1810                } else {
1811                    intercepted = false;
1812                }
1813            } else {
1814                // There are no touch targets and this action is not an initial down
1815                // so this view group continues to intercept touches.
1816                intercepted = true;
1817            }
1818
1819            // Check for cancelation.
1820            final boolean canceled = resetCancelNextUpFlag(this)
1821                    || actionMasked == MotionEvent.ACTION_CANCEL;
1822
1823            // Update list of touch targets for pointer down, if needed.
1824            final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
1825            TouchTarget newTouchTarget = null;
1826            boolean alreadyDispatchedToNewTouchTarget = false;
1827            if (!canceled && !intercepted) {
1828                if (actionMasked == MotionEvent.ACTION_DOWN
1829                        || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
1830                        || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
1831                    final int actionIndex = ev.getActionIndex(); // always 0 for down
1832                    final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
1833                            : TouchTarget.ALL_POINTER_IDS;
1834
1835                    // Clean up earlier touch targets for this pointer id in case they
1836                    // have become out of sync.
1837                    removePointersFromTouchTargets(idBitsToAssign);
1838
1839                    final int childrenCount = mChildrenCount;
1840                    if (childrenCount != 0) {
1841                        // Find a child that can receive the event.
1842                        // Scan children from front to back.
1843                        final View[] children = mChildren;
1844                        final float x = ev.getX(actionIndex);
1845                        final float y = ev.getY(actionIndex);
1846
1847                        for (int i = childrenCount - 1; i >= 0; i--) {
1848                            final View child = children[i];
1849                            if (!canViewReceivePointerEvents(child)
1850                                    || !isTransformedTouchPointInView(x, y, child, null)) {
1851                                continue;
1852                            }
1853
1854                            newTouchTarget = getTouchTarget(child);
1855                            if (newTouchTarget != null) {
1856                                // Child is already receiving touch within its bounds.
1857                                // Give it the new pointer in addition to the ones it is handling.
1858                                newTouchTarget.pointerIdBits |= idBitsToAssign;
1859                                break;
1860                            }
1861
1862                            resetCancelNextUpFlag(child);
1863                            if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
1864                                // Child wants to receive touch within its bounds.
1865                                mLastTouchDownTime = ev.getDownTime();
1866                                mLastTouchDownIndex = i;
1867                                mLastTouchDownX = ev.getX();
1868                                mLastTouchDownY = ev.getY();
1869                                newTouchTarget = addTouchTarget(child, idBitsToAssign);
1870                                alreadyDispatchedToNewTouchTarget = true;
1871                                break;
1872                            }
1873                        }
1874                    }
1875
1876                    if (newTouchTarget == null && mFirstTouchTarget != null) {
1877                        // Did not find a child to receive the event.
1878                        // Assign the pointer to the least recently added target.
1879                        newTouchTarget = mFirstTouchTarget;
1880                        while (newTouchTarget.next != null) {
1881                            newTouchTarget = newTouchTarget.next;
1882                        }
1883                        newTouchTarget.pointerIdBits |= idBitsToAssign;
1884                    }
1885                }
1886            }
1887
1888            // Dispatch to touch targets.
1889            if (mFirstTouchTarget == null) {
1890                // No touch targets so treat this as an ordinary view.
1891                handled = dispatchTransformedTouchEvent(ev, canceled, null,
1892                        TouchTarget.ALL_POINTER_IDS);
1893            } else {
1894                // Dispatch to touch targets, excluding the new touch target if we already
1895                // dispatched to it.  Cancel touch targets if necessary.
1896                TouchTarget predecessor = null;
1897                TouchTarget target = mFirstTouchTarget;
1898                while (target != null) {
1899                    final TouchTarget next = target.next;
1900                    if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
1901                        handled = true;
1902                    } else {
1903                        final boolean cancelChild = resetCancelNextUpFlag(target.child)
1904                        || intercepted;
1905                        if (dispatchTransformedTouchEvent(ev, cancelChild,
1906                                target.child, target.pointerIdBits)) {
1907                            handled = true;
1908                        }
1909                        if (cancelChild) {
1910                            if (predecessor == null) {
1911                                mFirstTouchTarget = next;
1912                            } else {
1913                                predecessor.next = next;
1914                            }
1915                            target.recycle();
1916                            target = next;
1917                            continue;
1918                        }
1919                    }
1920                    predecessor = target;
1921                    target = next;
1922                }
1923            }
1924
1925            // Update list of touch targets for pointer up or cancel, if needed.
1926            if (canceled
1927                    || actionMasked == MotionEvent.ACTION_UP
1928                    || actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
1929                resetTouchState();
1930            } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
1931                final int actionIndex = ev.getActionIndex();
1932                final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
1933                removePointersFromTouchTargets(idBitsToRemove);
1934            }
1935        }
1936
1937        if (!handled && mInputEventConsistencyVerifier != null) {
1938            mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
1939        }
1940        return handled;
1941    }
1942
1943    /**
1944     * Resets all touch state in preparation for a new cycle.
1945     */
1946    private void resetTouchState() {
1947        clearTouchTargets();
1948        resetCancelNextUpFlag(this);
1949        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
1950    }
1951
1952    /**
1953     * Resets the cancel next up flag.
1954     * Returns true if the flag was previously set.
1955     */
1956    private static boolean resetCancelNextUpFlag(View view) {
1957        if ((view.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
1958            view.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1959            return true;
1960        }
1961        return false;
1962    }
1963
1964    /**
1965     * Clears all touch targets.
1966     */
1967    private void clearTouchTargets() {
1968        TouchTarget target = mFirstTouchTarget;
1969        if (target != null) {
1970            do {
1971                TouchTarget next = target.next;
1972                target.recycle();
1973                target = next;
1974            } while (target != null);
1975            mFirstTouchTarget = null;
1976        }
1977    }
1978
1979    /**
1980     * Cancels and clears all touch targets.
1981     */
1982    private void cancelAndClearTouchTargets(MotionEvent event) {
1983        if (mFirstTouchTarget != null) {
1984            boolean syntheticEvent = false;
1985            if (event == null) {
1986                final long now = SystemClock.uptimeMillis();
1987                event = MotionEvent.obtain(now, now,
1988                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
1989                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
1990                syntheticEvent = true;
1991            }
1992
1993            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
1994                resetCancelNextUpFlag(target.child);
1995                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
1996            }
1997            clearTouchTargets();
1998
1999            if (syntheticEvent) {
2000                event.recycle();
2001            }
2002        }
2003    }
2004
2005    /**
2006     * Gets the touch target for specified child view.
2007     * Returns null if not found.
2008     */
2009    private TouchTarget getTouchTarget(View child) {
2010        for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
2011            if (target.child == child) {
2012                return target;
2013            }
2014        }
2015        return null;
2016    }
2017
2018    /**
2019     * Adds a touch target for specified child to the beginning of the list.
2020     * Assumes the target child is not already present.
2021     */
2022    private TouchTarget addTouchTarget(View child, int pointerIdBits) {
2023        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
2024        target.next = mFirstTouchTarget;
2025        mFirstTouchTarget = target;
2026        return target;
2027    }
2028
2029    /**
2030     * Removes the pointer ids from consideration.
2031     */
2032    private void removePointersFromTouchTargets(int pointerIdBits) {
2033        TouchTarget predecessor = null;
2034        TouchTarget target = mFirstTouchTarget;
2035        while (target != null) {
2036            final TouchTarget next = target.next;
2037            if ((target.pointerIdBits & pointerIdBits) != 0) {
2038                target.pointerIdBits &= ~pointerIdBits;
2039                if (target.pointerIdBits == 0) {
2040                    if (predecessor == null) {
2041                        mFirstTouchTarget = next;
2042                    } else {
2043                        predecessor.next = next;
2044                    }
2045                    target.recycle();
2046                    target = next;
2047                    continue;
2048                }
2049            }
2050            predecessor = target;
2051            target = next;
2052        }
2053    }
2054
2055    private void cancelTouchTarget(View view) {
2056        TouchTarget predecessor = null;
2057        TouchTarget target = mFirstTouchTarget;
2058        while (target != null) {
2059            final TouchTarget next = target.next;
2060            if (target.child == view) {
2061                if (predecessor == null) {
2062                    mFirstTouchTarget = next;
2063                } else {
2064                    predecessor.next = next;
2065                }
2066                target.recycle();
2067
2068                final long now = SystemClock.uptimeMillis();
2069                MotionEvent event = MotionEvent.obtain(now, now,
2070                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
2071                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
2072                view.dispatchTouchEvent(event);
2073                event.recycle();
2074                return;
2075            }
2076            predecessor = target;
2077            target = next;
2078        }
2079    }
2080
2081    /**
2082     * Returns true if a child view can receive pointer events.
2083     * @hide
2084     */
2085    private static boolean canViewReceivePointerEvents(View child) {
2086        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
2087                || child.getAnimation() != null;
2088    }
2089
2090    /**
2091     * Returns true if a child view contains the specified point when transformed
2092     * into its coordinate space.
2093     * Child must not be null.
2094     * @hide
2095     */
2096    protected boolean isTransformedTouchPointInView(float x, float y, View child,
2097            PointF outLocalPoint) {
2098        float localX = x + mScrollX - child.mLeft;
2099        float localY = y + mScrollY - child.mTop;
2100        if (! child.hasIdentityMatrix() && mAttachInfo != null) {
2101            final float[] localXY = mAttachInfo.mTmpTransformLocation;
2102            localXY[0] = localX;
2103            localXY[1] = localY;
2104            child.getInverseMatrix().mapPoints(localXY);
2105            localX = localXY[0];
2106            localY = localXY[1];
2107        }
2108        final boolean isInView = child.pointInView(localX, localY);
2109        if (isInView && outLocalPoint != null) {
2110            outLocalPoint.set(localX, localY);
2111        }
2112        return isInView;
2113    }
2114
2115    /**
2116     * Transforms a motion event into the coordinate space of a particular child view,
2117     * filters out irrelevant pointer ids, and overrides its action if necessary.
2118     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
2119     */
2120    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
2121            View child, int desiredPointerIdBits) {
2122        final boolean handled;
2123
2124        // Canceling motions is a special case.  We don't need to perform any transformations
2125        // or filtering.  The important part is the action, not the contents.
2126        final int oldAction = event.getAction();
2127        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
2128            event.setAction(MotionEvent.ACTION_CANCEL);
2129            if (child == null) {
2130                handled = super.dispatchTouchEvent(event);
2131            } else {
2132                handled = child.dispatchTouchEvent(event);
2133            }
2134            event.setAction(oldAction);
2135            return handled;
2136        }
2137
2138        // Calculate the number of pointers to deliver.
2139        final int oldPointerIdBits = event.getPointerIdBits();
2140        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
2141
2142        // If for some reason we ended up in an inconsistent state where it looks like we
2143        // might produce a motion event with no pointers in it, then drop the event.
2144        if (newPointerIdBits == 0) {
2145            return false;
2146        }
2147
2148        // If the number of pointers is the same and we don't need to perform any fancy
2149        // irreversible transformations, then we can reuse the motion event for this
2150        // dispatch as long as we are careful to revert any changes we make.
2151        // Otherwise we need to make a copy.
2152        final MotionEvent transformedEvent;
2153        if (newPointerIdBits == oldPointerIdBits) {
2154            if (child == null || child.hasIdentityMatrix()) {
2155                if (child == null) {
2156                    handled = super.dispatchTouchEvent(event);
2157                } else {
2158                    final float offsetX = mScrollX - child.mLeft;
2159                    final float offsetY = mScrollY - child.mTop;
2160                    event.offsetLocation(offsetX, offsetY);
2161
2162                    handled = child.dispatchTouchEvent(event);
2163
2164                    event.offsetLocation(-offsetX, -offsetY);
2165                }
2166                return handled;
2167            }
2168            transformedEvent = MotionEvent.obtain(event);
2169        } else {
2170            transformedEvent = event.split(newPointerIdBits);
2171        }
2172
2173        // Perform any necessary transformations and dispatch.
2174        if (child == null) {
2175            handled = super.dispatchTouchEvent(transformedEvent);
2176        } else {
2177            final float offsetX = mScrollX - child.mLeft;
2178            final float offsetY = mScrollY - child.mTop;
2179            transformedEvent.offsetLocation(offsetX, offsetY);
2180            if (! child.hasIdentityMatrix()) {
2181                transformedEvent.transform(child.getInverseMatrix());
2182            }
2183
2184            handled = child.dispatchTouchEvent(transformedEvent);
2185        }
2186
2187        // Done.
2188        transformedEvent.recycle();
2189        return handled;
2190    }
2191
2192    /**
2193     * Enable or disable the splitting of MotionEvents to multiple children during touch event
2194     * dispatch. This behavior is enabled by default for applications that target an
2195     * SDK version of {@link Build.VERSION_CODES#HONEYCOMB} or newer.
2196     *
2197     * <p>When this option is enabled MotionEvents may be split and dispatched to different child
2198     * views depending on where each pointer initially went down. This allows for user interactions
2199     * such as scrolling two panes of content independently, chording of buttons, and performing
2200     * independent gestures on different pieces of content.
2201     *
2202     * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple
2203     *              child views. <code>false</code> to only allow one child view to be the target of
2204     *              any MotionEvent received by this ViewGroup.
2205     */
2206    public void setMotionEventSplittingEnabled(boolean split) {
2207        // TODO Applications really shouldn't change this setting mid-touch event,
2208        // but perhaps this should handle that case and send ACTION_CANCELs to any child views
2209        // with gestures in progress when this is changed.
2210        if (split) {
2211            mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
2212        } else {
2213            mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
2214        }
2215    }
2216
2217    /**
2218     * Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
2219     * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
2220     */
2221    public boolean isMotionEventSplittingEnabled() {
2222        return (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS;
2223    }
2224
2225    /**
2226     * {@inheritDoc}
2227     */
2228    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2229
2230        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
2231            // We're already in this state, assume our ancestors are too
2232            return;
2233        }
2234
2235        if (disallowIntercept) {
2236            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
2237        } else {
2238            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
2239        }
2240
2241        // Pass it up to our parent
2242        if (mParent != null) {
2243            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
2244        }
2245    }
2246
2247    /**
2248     * Implement this method to intercept all touch screen motion events.  This
2249     * allows you to watch events as they are dispatched to your children, and
2250     * take ownership of the current gesture at any point.
2251     *
2252     * <p>Using this function takes some care, as it has a fairly complicated
2253     * interaction with {@link View#onTouchEvent(MotionEvent)
2254     * View.onTouchEvent(MotionEvent)}, and using it requires implementing
2255     * that method as well as this one in the correct way.  Events will be
2256     * received in the following order:
2257     *
2258     * <ol>
2259     * <li> You will receive the down event here.
2260     * <li> The down event will be handled either by a child of this view
2261     * group, or given to your own onTouchEvent() method to handle; this means
2262     * you should implement onTouchEvent() to return true, so you will
2263     * continue to see the rest of the gesture (instead of looking for
2264     * a parent view to handle it).  Also, by returning true from
2265     * onTouchEvent(), you will not receive any following
2266     * events in onInterceptTouchEvent() and all touch processing must
2267     * happen in onTouchEvent() like normal.
2268     * <li> For as long as you return false from this function, each following
2269     * event (up to and including the final up) will be delivered first here
2270     * and then to the target's onTouchEvent().
2271     * <li> If you return true from here, you will not receive any
2272     * following events: the target view will receive the same event but
2273     * with the action {@link MotionEvent#ACTION_CANCEL}, and all further
2274     * events will be delivered to your onTouchEvent() method and no longer
2275     * appear here.
2276     * </ol>
2277     *
2278     * @param ev The motion event being dispatched down the hierarchy.
2279     * @return Return true to steal motion events from the children and have
2280     * them dispatched to this ViewGroup through onTouchEvent().
2281     * The current target will receive an ACTION_CANCEL event, and no further
2282     * messages will be delivered here.
2283     */
2284    public boolean onInterceptTouchEvent(MotionEvent ev) {
2285        return false;
2286    }
2287
2288    /**
2289     * {@inheritDoc}
2290     *
2291     * Looks for a view to give focus to respecting the setting specified by
2292     * {@link #getDescendantFocusability()}.
2293     *
2294     * Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to
2295     * find focus within the children of this group when appropriate.
2296     *
2297     * @see #FOCUS_BEFORE_DESCENDANTS
2298     * @see #FOCUS_AFTER_DESCENDANTS
2299     * @see #FOCUS_BLOCK_DESCENDANTS
2300     * @see #onRequestFocusInDescendants(int, android.graphics.Rect)
2301     */
2302    @Override
2303    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
2304        if (DBG) {
2305            System.out.println(this + " ViewGroup.requestFocus direction="
2306                    + direction);
2307        }
2308        int descendantFocusability = getDescendantFocusability();
2309
2310        switch (descendantFocusability) {
2311            case FOCUS_BLOCK_DESCENDANTS:
2312                return super.requestFocus(direction, previouslyFocusedRect);
2313            case FOCUS_BEFORE_DESCENDANTS: {
2314                final boolean took = super.requestFocus(direction, previouslyFocusedRect);
2315                return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect);
2316            }
2317            case FOCUS_AFTER_DESCENDANTS: {
2318                final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);
2319                return took ? took : super.requestFocus(direction, previouslyFocusedRect);
2320            }
2321            default:
2322                throw new IllegalStateException("descendant focusability must be "
2323                        + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS "
2324                        + "but is " + descendantFocusability);
2325        }
2326    }
2327
2328    /**
2329     * Look for a descendant to call {@link View#requestFocus} on.
2330     * Called by {@link ViewGroup#requestFocus(int, android.graphics.Rect)}
2331     * when it wants to request focus within its children.  Override this to
2332     * customize how your {@link ViewGroup} requests focus within its children.
2333     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
2334     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
2335     *        to give a finer grained hint about where focus is coming from.  May be null
2336     *        if there is no hint.
2337     * @return Whether focus was taken.
2338     */
2339    @SuppressWarnings({"ConstantConditions"})
2340    protected boolean onRequestFocusInDescendants(int direction,
2341            Rect previouslyFocusedRect) {
2342        int index;
2343        int increment;
2344        int end;
2345        int count = mChildrenCount;
2346        if ((direction & FOCUS_FORWARD) != 0) {
2347            index = 0;
2348            increment = 1;
2349            end = count;
2350        } else {
2351            index = count - 1;
2352            increment = -1;
2353            end = -1;
2354        }
2355        final View[] children = mChildren;
2356        for (int i = index; i != end; i += increment) {
2357            View child = children[i];
2358            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2359                if (child.requestFocus(direction, previouslyFocusedRect)) {
2360                    return true;
2361                }
2362            }
2363        }
2364        return false;
2365    }
2366
2367    /**
2368     * {@inheritDoc}
2369     *
2370     * @hide
2371     */
2372    @Override
2373    public void dispatchStartTemporaryDetach() {
2374        super.dispatchStartTemporaryDetach();
2375        final int count = mChildrenCount;
2376        final View[] children = mChildren;
2377        for (int i = 0; i < count; i++) {
2378            children[i].dispatchStartTemporaryDetach();
2379        }
2380    }
2381
2382    /**
2383     * {@inheritDoc}
2384     *
2385     * @hide
2386     */
2387    @Override
2388    public void dispatchFinishTemporaryDetach() {
2389        super.dispatchFinishTemporaryDetach();
2390        final int count = mChildrenCount;
2391        final View[] children = mChildren;
2392        for (int i = 0; i < count; i++) {
2393            children[i].dispatchFinishTemporaryDetach();
2394        }
2395    }
2396
2397    /**
2398     * {@inheritDoc}
2399     */
2400    @Override
2401    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
2402        mGroupFlags |= FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;
2403        super.dispatchAttachedToWindow(info, visibility);
2404        mGroupFlags &= ~FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;
2405
2406        final int count = mChildrenCount;
2407        final View[] children = mChildren;
2408        for (int i = 0; i < count; i++) {
2409            final View child = children[i];
2410            child.dispatchAttachedToWindow(info,
2411                    visibility | (child.mViewFlags&VISIBILITY_MASK));
2412        }
2413    }
2414
2415    @Override
2416    void dispatchScreenStateChanged(int screenState) {
2417        super.dispatchScreenStateChanged(screenState);
2418
2419        final int count = mChildrenCount;
2420        final View[] children = mChildren;
2421        for (int i = 0; i < count; i++) {
2422            children[i].dispatchScreenStateChanged(screenState);
2423        }
2424    }
2425
2426    @Override
2427    boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) {
2428        boolean handled = false;
2429        if (includeForAccessibility()) {
2430            handled = super.dispatchPopulateAccessibilityEventInternal(event);
2431            if (handled) {
2432                return handled;
2433            }
2434        }
2435        // Let our children have a shot in populating the event.
2436        ChildListForAccessibility children = ChildListForAccessibility.obtain(this, true);
2437        final int childCount = children.getChildCount();
2438        for (int i = 0; i < childCount; i++) {
2439            View child = children.getChildAt(i);
2440            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2441                handled = child.dispatchPopulateAccessibilityEvent(event);
2442                if (handled) {
2443                    children.recycle();
2444                    return handled;
2445                }
2446            }
2447        }
2448        children.recycle();
2449        return false;
2450    }
2451
2452    @Override
2453    void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) {
2454        super.onInitializeAccessibilityNodeInfoInternal(info);
2455        if (mAttachInfo != null) {
2456            ArrayList<View> childrenForAccessibility = mAttachInfo.mTempArrayList;
2457            childrenForAccessibility.clear();
2458            addChildrenForAccessibility(childrenForAccessibility);
2459            final int childrenForAccessibilityCount = childrenForAccessibility.size();
2460            for (int i = 0; i < childrenForAccessibilityCount; i++) {
2461                View child = childrenForAccessibility.get(i);
2462                info.addChild(child);
2463            }
2464            childrenForAccessibility.clear();
2465        }
2466    }
2467
2468    @Override
2469    void onInitializeAccessibilityEventInternal(AccessibilityEvent event) {
2470        super.onInitializeAccessibilityEventInternal(event);
2471        event.setClassName(ViewGroup.class.getName());
2472    }
2473
2474    /**
2475     * @hide
2476     */
2477    @Override
2478    public void resetAccessibilityStateChanged() {
2479        super.resetAccessibilityStateChanged();
2480        View[] children = mChildren;
2481        final int childCount = mChildrenCount;
2482        for (int i = 0; i < childCount; i++) {
2483            View child = children[i];
2484            child.resetAccessibilityStateChanged();
2485        }
2486    }
2487
2488    /**
2489     * {@inheritDoc}
2490     */
2491    @Override
2492    void dispatchDetachedFromWindow() {
2493        // If we still have a touch target, we are still in the process of
2494        // dispatching motion events to a child; we need to get rid of that
2495        // child to avoid dispatching events to it after the window is torn
2496        // down. To make sure we keep the child in a consistent state, we
2497        // first send it an ACTION_CANCEL motion event.
2498        cancelAndClearTouchTargets(null);
2499
2500        // Similarly, set ACTION_EXIT to all hover targets and clear them.
2501        exitHoverTargets();
2502
2503        // In case view is detached while transition is running
2504        mLayoutSuppressed = false;
2505
2506        // Tear down our drag tracking
2507        mDragNotifiedChildren = null;
2508        if (mCurrentDrag != null) {
2509            mCurrentDrag.recycle();
2510            mCurrentDrag = null;
2511        }
2512
2513        final int count = mChildrenCount;
2514        final View[] children = mChildren;
2515        for (int i = 0; i < count; i++) {
2516            children[i].dispatchDetachedFromWindow();
2517        }
2518        super.dispatchDetachedFromWindow();
2519    }
2520
2521    /**
2522     * {@inheritDoc}
2523     */
2524    @Override
2525    public void setPadding(int left, int top, int right, int bottom) {
2526        super.setPadding(left, top, right, bottom);
2527
2528        if ((mPaddingLeft | mPaddingTop | mPaddingRight | mPaddingBottom) != 0) {
2529            mGroupFlags |= FLAG_PADDING_NOT_NULL;
2530        } else {
2531            mGroupFlags &= ~FLAG_PADDING_NOT_NULL;
2532        }
2533    }
2534
2535    /**
2536     * {@inheritDoc}
2537     */
2538    @Override
2539    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
2540        super.dispatchSaveInstanceState(container);
2541        final int count = mChildrenCount;
2542        final View[] children = mChildren;
2543        for (int i = 0; i < count; i++) {
2544            View c = children[i];
2545            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
2546                c.dispatchSaveInstanceState(container);
2547            }
2548        }
2549    }
2550
2551    /**
2552     * Perform dispatching of a {@link #saveHierarchyState(android.util.SparseArray)}  freeze()}
2553     * to only this view, not to its children.  For use when overriding
2554     * {@link #dispatchSaveInstanceState(android.util.SparseArray)}  dispatchFreeze()} to allow
2555     * subclasses to freeze their own state but not the state of their children.
2556     *
2557     * @param container the container
2558     */
2559    protected void dispatchFreezeSelfOnly(SparseArray<Parcelable> container) {
2560        super.dispatchSaveInstanceState(container);
2561    }
2562
2563    /**
2564     * {@inheritDoc}
2565     */
2566    @Override
2567    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
2568        super.dispatchRestoreInstanceState(container);
2569        final int count = mChildrenCount;
2570        final View[] children = mChildren;
2571        for (int i = 0; i < count; i++) {
2572            View c = children[i];
2573            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
2574                c.dispatchRestoreInstanceState(container);
2575            }
2576        }
2577    }
2578
2579    /**
2580     * Perform dispatching of a {@link #restoreHierarchyState(android.util.SparseArray)}
2581     * to only this view, not to its children.  For use when overriding
2582     * {@link #dispatchRestoreInstanceState(android.util.SparseArray)} to allow
2583     * subclasses to thaw their own state but not the state of their children.
2584     *
2585     * @param container the container
2586     */
2587    protected void dispatchThawSelfOnly(SparseArray<Parcelable> container) {
2588        super.dispatchRestoreInstanceState(container);
2589    }
2590
2591    /**
2592     * Enables or disables the drawing cache for each child of this view group.
2593     *
2594     * @param enabled true to enable the cache, false to dispose of it
2595     */
2596    protected void setChildrenDrawingCacheEnabled(boolean enabled) {
2597        if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) {
2598            final View[] children = mChildren;
2599            final int count = mChildrenCount;
2600            for (int i = 0; i < count; i++) {
2601                children[i].setDrawingCacheEnabled(enabled);
2602            }
2603        }
2604    }
2605
2606    @Override
2607    protected void onAnimationStart() {
2608        super.onAnimationStart();
2609
2610        // When this ViewGroup's animation starts, build the cache for the children
2611        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2612            final int count = mChildrenCount;
2613            final View[] children = mChildren;
2614            final boolean buildCache = !isHardwareAccelerated();
2615
2616            for (int i = 0; i < count; i++) {
2617                final View child = children[i];
2618                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2619                    child.setDrawingCacheEnabled(true);
2620                    if (buildCache) {
2621                        child.buildDrawingCache(true);
2622                    }
2623                }
2624            }
2625
2626            mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
2627        }
2628    }
2629
2630    @Override
2631    protected void onAnimationEnd() {
2632        super.onAnimationEnd();
2633
2634        // When this ViewGroup's animation ends, destroy the cache of the children
2635        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2636            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
2637
2638            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
2639                setChildrenDrawingCacheEnabled(false);
2640            }
2641        }
2642    }
2643
2644    @Override
2645    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
2646        int count = mChildrenCount;
2647        int[] visibilities = null;
2648
2649        if (skipChildren) {
2650            visibilities = new int[count];
2651            for (int i = 0; i < count; i++) {
2652                View child = getChildAt(i);
2653                visibilities[i] = child.getVisibility();
2654                if (visibilities[i] == View.VISIBLE) {
2655                    child.setVisibility(INVISIBLE);
2656                }
2657            }
2658        }
2659
2660        Bitmap b = super.createSnapshot(quality, backgroundColor, skipChildren);
2661
2662        if (skipChildren) {
2663            for (int i = 0; i < count; i++) {
2664                getChildAt(i).setVisibility(visibilities[i]);
2665            }
2666        }
2667
2668        return b;
2669    }
2670
2671    private static void drawRect(Canvas canvas, int x1, int y1, int x2, int y2, int color) {
2672        Paint paint = getDebugPaint();
2673        paint.setColor(color);
2674        canvas.drawRect(x1, y1, x2 - 1, y2 - 1, paint);
2675    }
2676
2677    /**
2678     * @hide
2679     */
2680    protected void onDebugDrawMargins(Canvas canvas) {
2681        for (int i = 0; i < getChildCount(); i++) {
2682            View c = getChildAt(i);
2683            c.getLayoutParams().onDebugDraw(c, canvas);
2684        }
2685    }
2686
2687    /**
2688     * @hide
2689     */
2690    protected void onDebugDraw(Canvas canvas) {
2691        // Draw optical bounds
2692        if (getLayoutMode() == LAYOUT_BOUNDS) {
2693            for (int i = 0; i < getChildCount(); i++) {
2694                View c = getChildAt(i);
2695                Insets insets = c.getLayoutInsets();
2696                drawRect(canvas,
2697                        c.getLeft() + insets.left,
2698                        c.getTop() + insets.top,
2699                        c.getRight() - insets.right,
2700                        c.getBottom() - insets.bottom, Color.RED);
2701            }
2702        }
2703
2704        // Draw margins
2705        onDebugDrawMargins(canvas);
2706
2707        // Draw bounds
2708        for (int i = 0; i < getChildCount(); i++) {
2709            View c = getChildAt(i);
2710            drawRect(canvas, c.getLeft(), c.getTop(), c.getRight(), c.getBottom(), Color.BLUE);
2711        }
2712    }
2713
2714    /**
2715     * {@inheritDoc}
2716     */
2717    @Override
2718    protected void dispatchDraw(Canvas canvas) {
2719        final int count = mChildrenCount;
2720        final View[] children = mChildren;
2721        int flags = mGroupFlags;
2722
2723        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
2724            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
2725
2726            final boolean buildCache = !isHardwareAccelerated();
2727            for (int i = 0; i < count; i++) {
2728                final View child = children[i];
2729                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2730                    final LayoutParams params = child.getLayoutParams();
2731                    attachLayoutAnimationParameters(child, params, i, count);
2732                    bindLayoutAnimation(child);
2733                    if (cache) {
2734                        child.setDrawingCacheEnabled(true);
2735                        if (buildCache) {
2736                            child.buildDrawingCache(true);
2737                        }
2738                    }
2739                }
2740            }
2741
2742            final LayoutAnimationController controller = mLayoutAnimationController;
2743            if (controller.willOverlap()) {
2744                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
2745            }
2746
2747            controller.start();
2748
2749            mGroupFlags &= ~FLAG_RUN_ANIMATION;
2750            mGroupFlags &= ~FLAG_ANIMATION_DONE;
2751
2752            if (cache) {
2753                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
2754            }
2755
2756            if (mAnimationListener != null) {
2757                mAnimationListener.onAnimationStart(controller.getAnimation());
2758            }
2759        }
2760
2761        int saveCount = 0;
2762        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
2763        if (clipToPadding) {
2764            saveCount = canvas.save();
2765            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
2766                    mScrollX + mRight - mLeft - mPaddingRight,
2767                    mScrollY + mBottom - mTop - mPaddingBottom);
2768
2769        }
2770
2771        // We will draw our child's animation, let's reset the flag
2772        mPrivateFlags &= ~DRAW_ANIMATION;
2773        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
2774
2775        boolean more = false;
2776        final long drawingTime = getDrawingTime();
2777
2778        if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {
2779            for (int i = 0; i < count; i++) {
2780                final View child = children[i];
2781                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
2782                    more |= drawChild(canvas, child, drawingTime);
2783                }
2784            }
2785        } else {
2786            for (int i = 0; i < count; i++) {
2787                final View child = children[getChildDrawingOrder(count, i)];
2788                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
2789                    more |= drawChild(canvas, child, drawingTime);
2790                }
2791            }
2792        }
2793
2794        // Draw any disappearing views that have animations
2795        if (mDisappearingChildren != null) {
2796            final ArrayList<View> disappearingChildren = mDisappearingChildren;
2797            final int disappearingCount = disappearingChildren.size() - 1;
2798            // Go backwards -- we may delete as animations finish
2799            for (int i = disappearingCount; i >= 0; i--) {
2800                final View child = disappearingChildren.get(i);
2801                more |= drawChild(canvas, child, drawingTime);
2802            }
2803        }
2804
2805        if (debugDraw()) {
2806            onDebugDraw(canvas);
2807        }
2808
2809        if (clipToPadding) {
2810            canvas.restoreToCount(saveCount);
2811        }
2812
2813        // mGroupFlags might have been updated by drawChild()
2814        flags = mGroupFlags;
2815
2816        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
2817            invalidate(true);
2818        }
2819
2820        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
2821                mLayoutAnimationController.isDone() && !more) {
2822            // We want to erase the drawing cache and notify the listener after the
2823            // next frame is drawn because one extra invalidate() is caused by
2824            // drawChild() after the animation is over
2825            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
2826            final Runnable end = new Runnable() {
2827               public void run() {
2828                   notifyAnimationListener();
2829               }
2830            };
2831            post(end);
2832        }
2833    }
2834
2835    /**
2836     * Returns the index of the child to draw for this iteration. Override this
2837     * if you want to change the drawing order of children. By default, it
2838     * returns i.
2839     * <p>
2840     * NOTE: In order for this method to be called, you must enable child ordering
2841     * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}.
2842     *
2843     * @param i The current iteration.
2844     * @return The index of the child to draw this iteration.
2845     *
2846     * @see #setChildrenDrawingOrderEnabled(boolean)
2847     * @see #isChildrenDrawingOrderEnabled()
2848     */
2849    protected int getChildDrawingOrder(int childCount, int i) {
2850        return i;
2851    }
2852
2853    private void notifyAnimationListener() {
2854        mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER;
2855        mGroupFlags |= FLAG_ANIMATION_DONE;
2856
2857        if (mAnimationListener != null) {
2858           final Runnable end = new Runnable() {
2859               public void run() {
2860                   mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation());
2861               }
2862           };
2863           post(end);
2864        }
2865
2866        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2867            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
2868            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
2869                setChildrenDrawingCacheEnabled(false);
2870            }
2871        }
2872
2873        invalidate(true);
2874    }
2875
2876    /**
2877     * This method is used to cause children of this ViewGroup to restore or recreate their
2878     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
2879     * to recreate its own display list, which would happen if it went through the normal
2880     * draw/dispatchDraw mechanisms.
2881     *
2882     * @hide
2883     */
2884    @Override
2885    protected void dispatchGetDisplayList() {
2886        final int count = mChildrenCount;
2887        final View[] children = mChildren;
2888        for (int i = 0; i < count; i++) {
2889            final View child = children[i];
2890            if (((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) &&
2891                    child.hasStaticLayer()) {
2892                child.mRecreateDisplayList = (child.mPrivateFlags & INVALIDATED) == INVALIDATED;
2893                child.mPrivateFlags &= ~INVALIDATED;
2894                child.getDisplayList();
2895                child.mRecreateDisplayList = false;
2896            }
2897        }
2898    }
2899
2900    /**
2901     * Draw one child of this View Group. This method is responsible for getting
2902     * the canvas in the right state. This includes clipping, translating so
2903     * that the child's scrolled origin is at 0, 0, and applying any animation
2904     * transformations.
2905     *
2906     * @param canvas The canvas on which to draw the child
2907     * @param child Who to draw
2908     * @param drawingTime The time at which draw is occurring
2909     * @return True if an invalidate() was issued
2910     */
2911    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
2912        return child.draw(canvas, this, drawingTime);
2913    }
2914
2915    /**
2916     *
2917     * @param enabled True if children should be drawn with layers, false otherwise.
2918     *
2919     * @hide
2920     */
2921    public void setChildrenLayersEnabled(boolean enabled) {
2922        if (enabled != mDrawLayers) {
2923            mDrawLayers = enabled;
2924            invalidate(true);
2925
2926            boolean flushLayers = !enabled;
2927            AttachInfo info = mAttachInfo;
2928            if (info != null && info.mHardwareRenderer != null &&
2929                    info.mHardwareRenderer.isEnabled()) {
2930                if (!info.mHardwareRenderer.validate()) {
2931                    flushLayers = false;
2932                }
2933            } else {
2934                flushLayers = false;
2935            }
2936
2937            // We need to invalidate any child with a layer. For instance,
2938            // if a child is backed by a hardware layer and we disable layers
2939            // the child is marked as not dirty (flags cleared the last time
2940            // the child was drawn inside its layer.) However, that child might
2941            // never have created its own display list or have an obsolete
2942            // display list. By invalidating the child we ensure the display
2943            // list is in sync with the content of the hardware layer.
2944            for (int i = 0; i < mChildrenCount; i++) {
2945                View child = mChildren[i];
2946                if (child.mLayerType != LAYER_TYPE_NONE) {
2947                    if (flushLayers) child.flushLayer();
2948                    child.invalidate(true);
2949                }
2950            }
2951        }
2952    }
2953
2954    /**
2955     * By default, children are clipped to their bounds before drawing. This
2956     * allows view groups to override this behavior for animations, etc.
2957     *
2958     * @param clipChildren true to clip children to their bounds,
2959     *        false otherwise
2960     * @attr ref android.R.styleable#ViewGroup_clipChildren
2961     */
2962    public void setClipChildren(boolean clipChildren) {
2963        boolean previousValue = (mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN;
2964        if (clipChildren != previousValue) {
2965            setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren);
2966            for (int i = 0; i < mChildrenCount; ++i) {
2967                View child = getChildAt(i);
2968                if (child.mDisplayList != null) {
2969                    child.mDisplayList.setClipChildren(clipChildren);
2970                }
2971            }
2972        }
2973    }
2974
2975    /**
2976     * By default, children are clipped to the padding of the ViewGroup. This
2977     * allows view groups to override this behavior
2978     *
2979     * @param clipToPadding true to clip children to the padding of the
2980     *        group, false otherwise
2981     * @attr ref android.R.styleable#ViewGroup_clipToPadding
2982     */
2983    public void setClipToPadding(boolean clipToPadding) {
2984        setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
2985    }
2986
2987    /**
2988     * {@inheritDoc}
2989     */
2990    @Override
2991    public void dispatchSetSelected(boolean selected) {
2992        final View[] children = mChildren;
2993        final int count = mChildrenCount;
2994        for (int i = 0; i < count; i++) {
2995            children[i].setSelected(selected);
2996        }
2997    }
2998
2999    /**
3000     * {@inheritDoc}
3001     */
3002    @Override
3003    public void dispatchSetActivated(boolean activated) {
3004        final View[] children = mChildren;
3005        final int count = mChildrenCount;
3006        for (int i = 0; i < count; i++) {
3007            children[i].setActivated(activated);
3008        }
3009    }
3010
3011    @Override
3012    protected void dispatchSetPressed(boolean pressed) {
3013        final View[] children = mChildren;
3014        final int count = mChildrenCount;
3015        for (int i = 0; i < count; i++) {
3016            final View child = children[i];
3017            // Children that are clickable on their own should not
3018            // show a pressed state when their parent view does.
3019            // Clearing a pressed state always propagates.
3020            if (!pressed || (!child.isClickable() && !child.isLongClickable())) {
3021                child.setPressed(pressed);
3022            }
3023        }
3024    }
3025
3026    /**
3027     * When this property is set to true, this ViewGroup supports static transformations on
3028     * children; this causes
3029     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
3030     * invoked when a child is drawn.
3031     *
3032     * Any subclass overriding
3033     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
3034     * set this property to true.
3035     *
3036     * @param enabled True to enable static transformations on children, false otherwise.
3037     *
3038     * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS
3039     */
3040    protected void setStaticTransformationsEnabled(boolean enabled) {
3041        setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled);
3042    }
3043
3044    /**
3045     * Sets  <code>t</code> to be the static transformation of the child, if set, returning a
3046     * boolean to indicate whether a static transform was set. The default implementation
3047     * simply returns <code>false</code>; subclasses may override this method for different
3048     * behavior.
3049     *
3050     * @param child The child view whose static transform is being requested
3051     * @param t The Transformation which will hold the result
3052     * @return true if the transformation was set, false otherwise
3053     * @see #setStaticTransformationsEnabled(boolean)
3054     */
3055    protected boolean getChildStaticTransformation(View child, Transformation t) {
3056        return false;
3057    }
3058
3059    /**
3060     * {@hide}
3061     */
3062    @Override
3063    protected View findViewTraversal(int id) {
3064        if (id == mID) {
3065            return this;
3066        }
3067
3068        final View[] where = mChildren;
3069        final int len = mChildrenCount;
3070
3071        for (int i = 0; i < len; i++) {
3072            View v = where[i];
3073
3074            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3075                v = v.findViewById(id);
3076
3077                if (v != null) {
3078                    return v;
3079                }
3080            }
3081        }
3082
3083        return null;
3084    }
3085
3086    /**
3087     * {@hide}
3088     */
3089    @Override
3090    protected View findViewWithTagTraversal(Object tag) {
3091        if (tag != null && tag.equals(mTag)) {
3092            return this;
3093        }
3094
3095        final View[] where = mChildren;
3096        final int len = mChildrenCount;
3097
3098        for (int i = 0; i < len; i++) {
3099            View v = where[i];
3100
3101            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3102                v = v.findViewWithTag(tag);
3103
3104                if (v != null) {
3105                    return v;
3106                }
3107            }
3108        }
3109
3110        return null;
3111    }
3112
3113    /**
3114     * {@hide}
3115     */
3116    @Override
3117    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
3118        if (predicate.apply(this)) {
3119            return this;
3120        }
3121
3122        final View[] where = mChildren;
3123        final int len = mChildrenCount;
3124
3125        for (int i = 0; i < len; i++) {
3126            View v = where[i];
3127
3128            if (v != childToSkip && (v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3129                v = v.findViewByPredicate(predicate);
3130
3131                if (v != null) {
3132                    return v;
3133                }
3134            }
3135        }
3136
3137        return null;
3138    }
3139
3140    /**
3141     * Adds a child view. If no layout parameters are already set on the child, the
3142     * default parameters for this ViewGroup are set on the child.
3143     *
3144     * @param child the child view to add
3145     *
3146     * @see #generateDefaultLayoutParams()
3147     */
3148    public void addView(View child) {
3149        addView(child, -1);
3150    }
3151
3152    /**
3153     * Adds a child view. If no layout parameters are already set on the child, the
3154     * default parameters for this ViewGroup are set on the child.
3155     *
3156     * @param child the child view to add
3157     * @param index the position at which to add the child
3158     *
3159     * @see #generateDefaultLayoutParams()
3160     */
3161    public void addView(View child, int index) {
3162        LayoutParams params = child.getLayoutParams();
3163        if (params == null) {
3164            params = generateDefaultLayoutParams();
3165            if (params == null) {
3166                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
3167            }
3168        }
3169        addView(child, index, params);
3170    }
3171
3172    /**
3173     * Adds a child view with this ViewGroup's default layout parameters and the
3174     * specified width and height.
3175     *
3176     * @param child the child view to add
3177     */
3178    public void addView(View child, int width, int height) {
3179        final LayoutParams params = generateDefaultLayoutParams();
3180        params.width = width;
3181        params.height = height;
3182        addView(child, -1, params);
3183    }
3184
3185    /**
3186     * Adds a child view with the specified layout parameters.
3187     *
3188     * @param child the child view to add
3189     * @param params the layout parameters to set on the child
3190     */
3191    public void addView(View child, LayoutParams params) {
3192        addView(child, -1, params);
3193    }
3194
3195    /**
3196     * Adds a child view with the specified layout parameters.
3197     *
3198     * @param child the child view to add
3199     * @param index the position at which to add the child
3200     * @param params the layout parameters to set on the child
3201     */
3202    public void addView(View child, int index, LayoutParams params) {
3203        if (DBG) {
3204            System.out.println(this + " addView");
3205        }
3206
3207        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
3208        // therefore, we call requestLayout() on ourselves before, so that the child's request
3209        // will be blocked at our level
3210        requestLayout();
3211        invalidate(true);
3212        addViewInner(child, index, params, false);
3213    }
3214
3215    /**
3216     * {@inheritDoc}
3217     */
3218    public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
3219        if (!checkLayoutParams(params)) {
3220            throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this);
3221        }
3222        if (view.mParent != this) {
3223            throw new IllegalArgumentException("Given view not a child of " + this);
3224        }
3225        view.setLayoutParams(params);
3226    }
3227
3228    /**
3229     * {@inheritDoc}
3230     */
3231    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
3232        return  p != null;
3233    }
3234
3235    /**
3236     * Interface definition for a callback to be invoked when the hierarchy
3237     * within this view changed. The hierarchy changes whenever a child is added
3238     * to or removed from this view.
3239     */
3240    public interface OnHierarchyChangeListener {
3241        /**
3242         * Called when a new child is added to a parent view.
3243         *
3244         * @param parent the view in which a child was added
3245         * @param child the new child view added in the hierarchy
3246         */
3247        void onChildViewAdded(View parent, View child);
3248
3249        /**
3250         * Called when a child is removed from a parent view.
3251         *
3252         * @param parent the view from which the child was removed
3253         * @param child the child removed from the hierarchy
3254         */
3255        void onChildViewRemoved(View parent, View child);
3256    }
3257
3258    /**
3259     * Register a callback to be invoked when a child is added to or removed
3260     * from this view.
3261     *
3262     * @param listener the callback to invoke on hierarchy change
3263     */
3264    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
3265        mOnHierarchyChangeListener = listener;
3266    }
3267
3268    /**
3269     * @hide
3270     */
3271    protected void onViewAdded(View child) {
3272        if (mOnHierarchyChangeListener != null) {
3273            mOnHierarchyChangeListener.onChildViewAdded(this, child);
3274        }
3275    }
3276
3277    /**
3278     * @hide
3279     */
3280    protected void onViewRemoved(View child) {
3281        if (mOnHierarchyChangeListener != null) {
3282            mOnHierarchyChangeListener.onChildViewRemoved(this, child);
3283        }
3284    }
3285
3286    /**
3287     * Adds a view during layout. This is useful if in your onLayout() method,
3288     * you need to add more views (as does the list view for example).
3289     *
3290     * If index is negative, it means put it at the end of the list.
3291     *
3292     * @param child the view to add to the group
3293     * @param index the index at which the child must be added
3294     * @param params the layout parameters to associate with the child
3295     * @return true if the child was added, false otherwise
3296     */
3297    protected boolean addViewInLayout(View child, int index, LayoutParams params) {
3298        return addViewInLayout(child, index, params, false);
3299    }
3300
3301    /**
3302     * Adds a view during layout. This is useful if in your onLayout() method,
3303     * you need to add more views (as does the list view for example).
3304     *
3305     * If index is negative, it means put it at the end of the list.
3306     *
3307     * @param child the view to add to the group
3308     * @param index the index at which the child must be added
3309     * @param params the layout parameters to associate with the child
3310     * @param preventRequestLayout if true, calling this method will not trigger a
3311     *        layout request on child
3312     * @return true if the child was added, false otherwise
3313     */
3314    protected boolean addViewInLayout(View child, int index, LayoutParams params,
3315            boolean preventRequestLayout) {
3316        child.mParent = null;
3317        addViewInner(child, index, params, preventRequestLayout);
3318        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN;
3319        return true;
3320    }
3321
3322    /**
3323     * Prevents the specified child to be laid out during the next layout pass.
3324     *
3325     * @param child the child on which to perform the cleanup
3326     */
3327    protected void cleanupLayoutState(View child) {
3328        child.mPrivateFlags &= ~View.FORCE_LAYOUT;
3329    }
3330
3331    private void addViewInner(View child, int index, LayoutParams params,
3332            boolean preventRequestLayout) {
3333
3334        if (mTransition != null) {
3335            // Don't prevent other add transitions from completing, but cancel remove
3336            // transitions to let them complete the process before we add to the container
3337            mTransition.cancel(LayoutTransition.DISAPPEARING);
3338        }
3339
3340        if (child.getParent() != null) {
3341            throw new IllegalStateException("The specified child already has a parent. " +
3342                    "You must call removeView() on the child's parent first.");
3343        }
3344
3345        if (mTransition != null) {
3346            mTransition.addChild(this, child);
3347        }
3348
3349        if (!checkLayoutParams(params)) {
3350            params = generateLayoutParams(params);
3351        }
3352
3353        if (preventRequestLayout) {
3354            child.mLayoutParams = params;
3355        } else {
3356            child.setLayoutParams(params);
3357        }
3358
3359        if (index < 0) {
3360            index = mChildrenCount;
3361        }
3362
3363        addInArray(child, index);
3364
3365        // tell our children
3366        if (preventRequestLayout) {
3367            child.assignParent(this);
3368        } else {
3369            child.mParent = this;
3370        }
3371
3372        if (child.hasFocus()) {
3373            requestChildFocus(child, child.findFocus());
3374        }
3375
3376        AttachInfo ai = mAttachInfo;
3377        if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
3378            boolean lastKeepOn = ai.mKeepScreenOn;
3379            ai.mKeepScreenOn = false;
3380            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
3381            if (ai.mKeepScreenOn) {
3382                needGlobalAttributesUpdate(true);
3383            }
3384            ai.mKeepScreenOn = lastKeepOn;
3385        }
3386
3387        onViewAdded(child);
3388
3389        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
3390            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
3391        }
3392
3393        if (child.hasTransientState()) {
3394            childHasTransientStateChanged(child, true);
3395        }
3396    }
3397
3398    private void addInArray(View child, int index) {
3399        View[] children = mChildren;
3400        final int count = mChildrenCount;
3401        final int size = children.length;
3402        if (index == count) {
3403            if (size == count) {
3404                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3405                System.arraycopy(children, 0, mChildren, 0, size);
3406                children = mChildren;
3407            }
3408            children[mChildrenCount++] = child;
3409        } else if (index < count) {
3410            if (size == count) {
3411                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3412                System.arraycopy(children, 0, mChildren, 0, index);
3413                System.arraycopy(children, index, mChildren, index + 1, count - index);
3414                children = mChildren;
3415            } else {
3416                System.arraycopy(children, index, children, index + 1, count - index);
3417            }
3418            children[index] = child;
3419            mChildrenCount++;
3420            if (mLastTouchDownIndex >= index) {
3421                mLastTouchDownIndex++;
3422            }
3423        } else {
3424            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
3425        }
3426    }
3427
3428    // This method also sets the child's mParent to null
3429    private void removeFromArray(int index) {
3430        final View[] children = mChildren;
3431        if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
3432            children[index].mParent = null;
3433        }
3434        final int count = mChildrenCount;
3435        if (index == count - 1) {
3436            children[--mChildrenCount] = null;
3437        } else if (index >= 0 && index < count) {
3438            System.arraycopy(children, index + 1, children, index, count - index - 1);
3439            children[--mChildrenCount] = null;
3440        } else {
3441            throw new IndexOutOfBoundsException();
3442        }
3443        if (mLastTouchDownIndex == index) {
3444            mLastTouchDownTime = 0;
3445            mLastTouchDownIndex = -1;
3446        } else if (mLastTouchDownIndex > index) {
3447            mLastTouchDownIndex--;
3448        }
3449    }
3450
3451    // This method also sets the children's mParent to null
3452    private void removeFromArray(int start, int count) {
3453        final View[] children = mChildren;
3454        final int childrenCount = mChildrenCount;
3455
3456        start = Math.max(0, start);
3457        final int end = Math.min(childrenCount, start + count);
3458
3459        if (start == end) {
3460            return;
3461        }
3462
3463        if (end == childrenCount) {
3464            for (int i = start; i < end; i++) {
3465                children[i].mParent = null;
3466                children[i] = null;
3467            }
3468        } else {
3469            for (int i = start; i < end; i++) {
3470                children[i].mParent = null;
3471            }
3472
3473            // Since we're looping above, we might as well do the copy, but is arraycopy()
3474            // faster than the extra 2 bounds checks we would do in the loop?
3475            System.arraycopy(children, end, children, start, childrenCount - end);
3476
3477            for (int i = childrenCount - (end - start); i < childrenCount; i++) {
3478                children[i] = null;
3479            }
3480        }
3481
3482        mChildrenCount -= (end - start);
3483    }
3484
3485    private void bindLayoutAnimation(View child) {
3486        Animation a = mLayoutAnimationController.getAnimationForView(child);
3487        child.setAnimation(a);
3488    }
3489
3490    /**
3491     * Subclasses should override this method to set layout animation
3492     * parameters on the supplied child.
3493     *
3494     * @param child the child to associate with animation parameters
3495     * @param params the child's layout parameters which hold the animation
3496     *        parameters
3497     * @param index the index of the child in the view group
3498     * @param count the number of children in the view group
3499     */
3500    protected void attachLayoutAnimationParameters(View child,
3501            LayoutParams params, int index, int count) {
3502        LayoutAnimationController.AnimationParameters animationParams =
3503                    params.layoutAnimationParameters;
3504        if (animationParams == null) {
3505            animationParams = new LayoutAnimationController.AnimationParameters();
3506            params.layoutAnimationParameters = animationParams;
3507        }
3508
3509        animationParams.count = count;
3510        animationParams.index = index;
3511    }
3512
3513    /**
3514     * {@inheritDoc}
3515     */
3516    public void removeView(View view) {
3517        removeViewInternal(view);
3518        requestLayout();
3519        invalidate(true);
3520    }
3521
3522    /**
3523     * Removes a view during layout. This is useful if in your onLayout() method,
3524     * you need to remove more views.
3525     *
3526     * @param view the view to remove from the group
3527     */
3528    public void removeViewInLayout(View view) {
3529        removeViewInternal(view);
3530    }
3531
3532    /**
3533     * Removes a range of views during layout. This is useful if in your onLayout() method,
3534     * you need to remove more views.
3535     *
3536     * @param start the index of the first view to remove from the group
3537     * @param count the number of views to remove from the group
3538     */
3539    public void removeViewsInLayout(int start, int count) {
3540        removeViewsInternal(start, count);
3541    }
3542
3543    /**
3544     * Removes the view at the specified position in the group.
3545     *
3546     * @param index the position in the group of the view to remove
3547     */
3548    public void removeViewAt(int index) {
3549        removeViewInternal(index, getChildAt(index));
3550        requestLayout();
3551        invalidate(true);
3552    }
3553
3554    /**
3555     * Removes the specified range of views from the group.
3556     *
3557     * @param start the first position in the group of the range of views to remove
3558     * @param count the number of views to remove
3559     */
3560    public void removeViews(int start, int count) {
3561        removeViewsInternal(start, count);
3562        requestLayout();
3563        invalidate(true);
3564    }
3565
3566    private void removeViewInternal(View view) {
3567        final int index = indexOfChild(view);
3568        if (index >= 0) {
3569            removeViewInternal(index, view);
3570        }
3571    }
3572
3573    private void removeViewInternal(int index, View view) {
3574
3575        if (mTransition != null) {
3576            mTransition.removeChild(this, view);
3577        }
3578
3579        boolean clearChildFocus = false;
3580        if (view == mFocused) {
3581            view.unFocus();
3582            clearChildFocus = true;
3583        }
3584
3585        cancelTouchTarget(view);
3586        cancelHoverTarget(view);
3587
3588        if (view.getAnimation() != null ||
3589                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3590            addDisappearingView(view);
3591        } else if (view.mAttachInfo != null) {
3592           view.dispatchDetachedFromWindow();
3593        }
3594
3595        if (view.hasTransientState()) {
3596            childHasTransientStateChanged(view, false);
3597        }
3598
3599        onViewRemoved(view);
3600
3601        needGlobalAttributesUpdate(false);
3602
3603        removeFromArray(index);
3604
3605        if (clearChildFocus) {
3606            clearChildFocus(view);
3607            ensureInputFocusOnFirstFocusable();
3608        }
3609
3610        if (view.isAccessibilityFocused()) {
3611            view.clearAccessibilityFocus();
3612        }
3613    }
3614
3615    /**
3616     * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3617     * not null, changes in layout which occur because of children being added to or removed from
3618     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3619     * object. By default, the transition object is null (so layout changes are not animated).
3620     *
3621     * @param transition The LayoutTransition object that will animated changes in layout. A value
3622     * of <code>null</code> means no transition will run on layout changes.
3623     * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
3624     */
3625    public void setLayoutTransition(LayoutTransition transition) {
3626        if (mTransition != null) {
3627            mTransition.removeTransitionListener(mLayoutTransitionListener);
3628        }
3629        mTransition = transition;
3630        if (mTransition != null) {
3631            mTransition.addTransitionListener(mLayoutTransitionListener);
3632        }
3633    }
3634
3635    /**
3636     * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3637     * not null, changes in layout which occur because of children being added to or removed from
3638     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3639     * object. By default, the transition object is null (so layout changes are not animated).
3640     *
3641     * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
3642     * A value of <code>null</code> means no transition will run on layout changes.
3643     */
3644    public LayoutTransition getLayoutTransition() {
3645        return mTransition;
3646    }
3647
3648    private void removeViewsInternal(int start, int count) {
3649        final View focused = mFocused;
3650        final boolean detach = mAttachInfo != null;
3651        View clearChildFocus = null;
3652
3653        final View[] children = mChildren;
3654        final int end = start + count;
3655
3656        for (int i = start; i < end; i++) {
3657            final View view = children[i];
3658
3659            if (mTransition != null) {
3660                mTransition.removeChild(this, view);
3661            }
3662
3663            if (view == focused) {
3664                view.unFocus();
3665                clearChildFocus = view;
3666            }
3667
3668            cancelTouchTarget(view);
3669            cancelHoverTarget(view);
3670
3671            if (view.getAnimation() != null ||
3672                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3673                addDisappearingView(view);
3674            } else if (detach) {
3675               view.dispatchDetachedFromWindow();
3676            }
3677
3678            if (view.hasTransientState()) {
3679                childHasTransientStateChanged(view, false);
3680            }
3681
3682            needGlobalAttributesUpdate(false);
3683
3684            onViewRemoved(view);
3685        }
3686
3687        removeFromArray(start, count);
3688
3689        if (clearChildFocus != null) {
3690            clearChildFocus(clearChildFocus);
3691            ensureInputFocusOnFirstFocusable();
3692        }
3693    }
3694
3695    /**
3696     * Call this method to remove all child views from the
3697     * ViewGroup.
3698     */
3699    public void removeAllViews() {
3700        removeAllViewsInLayout();
3701        requestLayout();
3702        invalidate(true);
3703    }
3704
3705    /**
3706     * Called by a ViewGroup subclass to remove child views from itself,
3707     * when it must first know its size on screen before it can calculate how many
3708     * child views it will render. An example is a Gallery or a ListView, which
3709     * may "have" 50 children, but actually only render the number of children
3710     * that can currently fit inside the object on screen. Do not call
3711     * this method unless you are extending ViewGroup and understand the
3712     * view measuring and layout pipeline.
3713     */
3714    public void removeAllViewsInLayout() {
3715        final int count = mChildrenCount;
3716        if (count <= 0) {
3717            return;
3718        }
3719
3720        final View[] children = mChildren;
3721        mChildrenCount = 0;
3722
3723        final View focused = mFocused;
3724        final boolean detach = mAttachInfo != null;
3725        View clearChildFocus = null;
3726
3727        needGlobalAttributesUpdate(false);
3728
3729        for (int i = count - 1; i >= 0; i--) {
3730            final View view = children[i];
3731
3732            if (mTransition != null) {
3733                mTransition.removeChild(this, view);
3734            }
3735
3736            if (view == focused) {
3737                view.unFocus();
3738                clearChildFocus = view;
3739            }
3740
3741            cancelTouchTarget(view);
3742            cancelHoverTarget(view);
3743
3744            if (view.getAnimation() != null ||
3745                    (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3746                addDisappearingView(view);
3747            } else if (detach) {
3748               view.dispatchDetachedFromWindow();
3749            }
3750
3751            if (view.hasTransientState()) {
3752                childHasTransientStateChanged(view, false);
3753            }
3754
3755            onViewRemoved(view);
3756
3757            view.mParent = null;
3758            children[i] = null;
3759        }
3760
3761        if (clearChildFocus != null) {
3762            clearChildFocus(clearChildFocus);
3763            ensureInputFocusOnFirstFocusable();
3764        }
3765    }
3766
3767    /**
3768     * Finishes the removal of a detached view. This method will dispatch the detached from
3769     * window event and notify the hierarchy change listener.
3770     *
3771     * @param child the child to be definitely removed from the view hierarchy
3772     * @param animate if true and the view has an animation, the view is placed in the
3773     *                disappearing views list, otherwise, it is detached from the window
3774     *
3775     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3776     * @see #detachAllViewsFromParent()
3777     * @see #detachViewFromParent(View)
3778     * @see #detachViewFromParent(int)
3779     */
3780    protected void removeDetachedView(View child, boolean animate) {
3781        if (mTransition != null) {
3782            mTransition.removeChild(this, child);
3783        }
3784
3785        if (child == mFocused) {
3786            child.clearFocus();
3787        }
3788
3789        cancelTouchTarget(child);
3790        cancelHoverTarget(child);
3791
3792        if ((animate && child.getAnimation() != null) ||
3793                (mTransitioningViews != null && mTransitioningViews.contains(child))) {
3794            addDisappearingView(child);
3795        } else if (child.mAttachInfo != null) {
3796            child.dispatchDetachedFromWindow();
3797        }
3798
3799        if (child.hasTransientState()) {
3800            childHasTransientStateChanged(child, false);
3801        }
3802
3803        onViewRemoved(child);
3804    }
3805
3806    /**
3807     * Attaches a view to this view group. Attaching a view assigns this group as the parent,
3808     * sets the layout parameters and puts the view in the list of children so it can be retrieved
3809     * by calling {@link #getChildAt(int)}.
3810     *
3811     * This method should be called only for view which were detached from their parent.
3812     *
3813     * @param child the child to attach
3814     * @param index the index at which the child should be attached
3815     * @param params the layout parameters of the child
3816     *
3817     * @see #removeDetachedView(View, boolean)
3818     * @see #detachAllViewsFromParent()
3819     * @see #detachViewFromParent(View)
3820     * @see #detachViewFromParent(int)
3821     */
3822    protected void attachViewToParent(View child, int index, LayoutParams params) {
3823        child.mLayoutParams = params;
3824
3825        if (index < 0) {
3826            index = mChildrenCount;
3827        }
3828
3829        addInArray(child, index);
3830
3831        child.mParent = this;
3832        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) |
3833                DRAWN | INVALIDATED;
3834        this.mPrivateFlags |= INVALIDATED;
3835
3836        if (child.hasFocus()) {
3837            requestChildFocus(child, child.findFocus());
3838        }
3839    }
3840
3841    /**
3842     * Detaches a view from its parent. Detaching a view should be temporary and followed
3843     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3844     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3845     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3846     *
3847     * @param child the child to detach
3848     *
3849     * @see #detachViewFromParent(int)
3850     * @see #detachViewsFromParent(int, int)
3851     * @see #detachAllViewsFromParent()
3852     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3853     * @see #removeDetachedView(View, boolean)
3854     */
3855    protected void detachViewFromParent(View child) {
3856        removeFromArray(indexOfChild(child));
3857    }
3858
3859    /**
3860     * Detaches a view from its parent. Detaching a view should be temporary and followed
3861     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3862     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3863     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3864     *
3865     * @param index the index of the child to detach
3866     *
3867     * @see #detachViewFromParent(View)
3868     * @see #detachAllViewsFromParent()
3869     * @see #detachViewsFromParent(int, int)
3870     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3871     * @see #removeDetachedView(View, boolean)
3872     */
3873    protected void detachViewFromParent(int index) {
3874        removeFromArray(index);
3875    }
3876
3877    /**
3878     * Detaches a range of view from their parent. Detaching a view should be temporary and followed
3879     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3880     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its
3881     * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3882     *
3883     * @param start the first index of the childrend range to detach
3884     * @param count the number of children to detach
3885     *
3886     * @see #detachViewFromParent(View)
3887     * @see #detachViewFromParent(int)
3888     * @see #detachAllViewsFromParent()
3889     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3890     * @see #removeDetachedView(View, boolean)
3891     */
3892    protected void detachViewsFromParent(int start, int count) {
3893        removeFromArray(start, count);
3894    }
3895
3896    /**
3897     * Detaches all views from the parent. Detaching a view should be temporary and followed
3898     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3899     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3900     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3901     *
3902     * @see #detachViewFromParent(View)
3903     * @see #detachViewFromParent(int)
3904     * @see #detachViewsFromParent(int, int)
3905     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3906     * @see #removeDetachedView(View, boolean)
3907     */
3908    protected void detachAllViewsFromParent() {
3909        final int count = mChildrenCount;
3910        if (count <= 0) {
3911            return;
3912        }
3913
3914        final View[] children = mChildren;
3915        mChildrenCount = 0;
3916
3917        for (int i = count - 1; i >= 0; i--) {
3918            children[i].mParent = null;
3919            children[i] = null;
3920        }
3921    }
3922
3923    /**
3924     * Don't call or override this method. It is used for the implementation of
3925     * the view hierarchy.
3926     */
3927    public final void invalidateChild(View child, final Rect dirty) {
3928        if (ViewDebug.TRACE_HIERARCHY) {
3929            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD);
3930        }
3931
3932        ViewParent parent = this;
3933
3934        final AttachInfo attachInfo = mAttachInfo;
3935        if (attachInfo != null) {
3936            // If the child is drawing an animation, we want to copy this flag onto
3937            // ourselves and the parent to make sure the invalidate request goes
3938            // through
3939            final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;
3940
3941            //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            drawRect(canvas,
5804                    view.getLeft() - leftMargin,
5805                    view.getTop() - topMargin,
5806                    view.getRight() + rightMargin,
5807                    view.getBottom() + bottomMargin, Color.MAGENTA);
5808        }
5809    }
5810
5811    /* Describes a touched view and the ids of the pointers that it has captured.
5812     *
5813     * This code assumes that pointer ids are always in the range 0..31 such that
5814     * it can use a bitfield to track which pointer ids are present.
5815     * As it happens, the lower layers of the input dispatch pipeline also use the
5816     * same trick so the assumption should be safe here...
5817     */
5818    private static final class TouchTarget {
5819        private static final int MAX_RECYCLED = 32;
5820        private static final Object sRecycleLock = new Object();
5821        private static TouchTarget sRecycleBin;
5822        private static int sRecycledCount;
5823
5824        public static final int ALL_POINTER_IDS = -1; // all ones
5825
5826        // The touched child view.
5827        public View child;
5828
5829        // The combined bit mask of pointer ids for all pointers captured by the target.
5830        public int pointerIdBits;
5831
5832        // The next target in the target list.
5833        public TouchTarget next;
5834
5835        private TouchTarget() {
5836        }
5837
5838        public static TouchTarget obtain(View child, int pointerIdBits) {
5839            final TouchTarget target;
5840            synchronized (sRecycleLock) {
5841                if (sRecycleBin == null) {
5842                    target = new TouchTarget();
5843                } else {
5844                    target = sRecycleBin;
5845                    sRecycleBin = target.next;
5846                     sRecycledCount--;
5847                    target.next = null;
5848                }
5849            }
5850            target.child = child;
5851            target.pointerIdBits = pointerIdBits;
5852            return target;
5853        }
5854
5855        public void recycle() {
5856            synchronized (sRecycleLock) {
5857                if (sRecycledCount < MAX_RECYCLED) {
5858                    next = sRecycleBin;
5859                    sRecycleBin = this;
5860                    sRecycledCount += 1;
5861                } else {
5862                    next = null;
5863                }
5864                child = null;
5865            }
5866        }
5867    }
5868
5869    /* Describes a hovered view. */
5870    private static final class HoverTarget {
5871        private static final int MAX_RECYCLED = 32;
5872        private static final Object sRecycleLock = new Object();
5873        private static HoverTarget sRecycleBin;
5874        private static int sRecycledCount;
5875
5876        // The hovered child view.
5877        public View child;
5878
5879        // The next target in the target list.
5880        public HoverTarget next;
5881
5882        private HoverTarget() {
5883        }
5884
5885        public static HoverTarget obtain(View child) {
5886            final HoverTarget target;
5887            synchronized (sRecycleLock) {
5888                if (sRecycleBin == null) {
5889                    target = new HoverTarget();
5890                } else {
5891                    target = sRecycleBin;
5892                    sRecycleBin = target.next;
5893                     sRecycledCount--;
5894                    target.next = null;
5895                }
5896            }
5897            target.child = child;
5898            return target;
5899        }
5900
5901        public void recycle() {
5902            synchronized (sRecycleLock) {
5903                if (sRecycledCount < MAX_RECYCLED) {
5904                    next = sRecycleBin;
5905                    sRecycleBin = this;
5906                    sRecycledCount += 1;
5907                } else {
5908                    next = null;
5909                }
5910                child = null;
5911            }
5912        }
5913    }
5914
5915    /**
5916     * Pooled class that orderes the children of a ViewGroup from start
5917     * to end based on how they are laid out and the layout direction.
5918     */
5919    static class ChildListForAccessibility {
5920
5921        private static final int MAX_POOL_SIZE = 32;
5922
5923        private static final Object sPoolLock = new Object();
5924
5925        private static ChildListForAccessibility sPool;
5926
5927        private static int sPoolSize;
5928
5929        private boolean mIsPooled;
5930
5931        private ChildListForAccessibility mNext;
5932
5933        private final ArrayList<View> mChildren = new ArrayList<View>();
5934
5935        private final ArrayList<ViewLocationHolder> mHolders = new ArrayList<ViewLocationHolder>();
5936
5937        public static ChildListForAccessibility obtain(ViewGroup parent, boolean sort) {
5938            ChildListForAccessibility list = null;
5939            synchronized (sPoolLock) {
5940                if (sPool != null) {
5941                    list = sPool;
5942                    sPool = list.mNext;
5943                    list.mNext = null;
5944                    list.mIsPooled = false;
5945                    sPoolSize--;
5946                } else {
5947                    list = new ChildListForAccessibility();
5948                }
5949                list.init(parent, sort);
5950                return list;
5951            }
5952        }
5953
5954        public void recycle() {
5955            if (mIsPooled) {
5956                throw new IllegalStateException("Instance already recycled.");
5957            }
5958            clear();
5959            synchronized (sPoolLock) {
5960                if (sPoolSize < MAX_POOL_SIZE) {
5961                    mNext = sPool;
5962                    mIsPooled = true;
5963                    sPool = this;
5964                    sPoolSize++;
5965                }
5966            }
5967        }
5968
5969        public int getChildCount() {
5970            return mChildren.size();
5971        }
5972
5973        public View getChildAt(int index) {
5974            return mChildren.get(index);
5975        }
5976
5977        public int getChildIndex(View child) {
5978            return mChildren.indexOf(child);
5979        }
5980
5981        private void init(ViewGroup parent, boolean sort) {
5982            ArrayList<View> children = mChildren;
5983            final int childCount = parent.getChildCount();
5984            for (int i = 0; i < childCount; i++) {
5985                View child = parent.getChildAt(i);
5986                children.add(child);
5987            }
5988            if (sort) {
5989                ArrayList<ViewLocationHolder> holders = mHolders;
5990                for (int i = 0; i < childCount; i++) {
5991                    View child = children.get(i);
5992                    ViewLocationHolder holder = ViewLocationHolder.obtain(parent, child);
5993                    holders.add(holder);
5994                }
5995                Collections.sort(holders);
5996                for (int i = 0; i < childCount; i++) {
5997                    ViewLocationHolder holder = holders.get(i);
5998                    children.set(i, holder.mView);
5999                    holder.recycle();
6000                }
6001                holders.clear();
6002            }
6003        }
6004
6005        private void clear() {
6006            mChildren.clear();
6007        }
6008    }
6009
6010    /**
6011     * Pooled class that holds a View and its location with respect to
6012     * a specified root. This enables sorting of views based on their
6013     * coordinates without recomputing the position relative to the root
6014     * on every comparison.
6015     */
6016    static class ViewLocationHolder implements Comparable<ViewLocationHolder> {
6017
6018        private static final int MAX_POOL_SIZE = 32;
6019
6020        private static final Object sPoolLock = new Object();
6021
6022        private static ViewLocationHolder sPool;
6023
6024        private static int sPoolSize;
6025
6026        private boolean mIsPooled;
6027
6028        private ViewLocationHolder mNext;
6029
6030        private final Rect mLocation = new Rect();
6031
6032        public View mView;
6033
6034        private int mLayoutDirection;
6035
6036        public static ViewLocationHolder obtain(ViewGroup root, View view) {
6037            ViewLocationHolder holder = null;
6038            synchronized (sPoolLock) {
6039                if (sPool != null) {
6040                    holder = sPool;
6041                    sPool = holder.mNext;
6042                    holder.mNext = null;
6043                    holder.mIsPooled = false;
6044                    sPoolSize--;
6045                } else {
6046                    holder = new ViewLocationHolder();
6047                }
6048                holder.init(root, view);
6049                return holder;
6050            }
6051        }
6052
6053        public void recycle() {
6054            if (mIsPooled) {
6055                throw new IllegalStateException("Instance already recycled.");
6056            }
6057            clear();
6058            synchronized (sPoolLock) {
6059                if (sPoolSize < MAX_POOL_SIZE) {
6060                    mNext = sPool;
6061                    mIsPooled = true;
6062                    sPool = this;
6063                    sPoolSize++;
6064                }
6065            }
6066        }
6067
6068        @Override
6069        public int compareTo(ViewLocationHolder another) {
6070            // This instance is greater than an invalid argument.
6071            if (another == null) {
6072                return 1;
6073            }
6074            if (getClass() != another.getClass()) {
6075                return 1;
6076            }
6077            // First is above second.
6078            if (mLocation.bottom - another.mLocation.top <= 0) {
6079                return -1;
6080            }
6081            // First is below second.
6082            if (mLocation.top - another.mLocation.bottom >= 0) {
6083                return 1;
6084            }
6085            // LTR
6086            if (mLayoutDirection == LAYOUT_DIRECTION_LTR) {
6087                final int leftDifference = mLocation.left - another.mLocation.left;
6088                // First more to the left than second.
6089                if (leftDifference != 0) {
6090                    return leftDifference;
6091                }
6092            } else { // RTL
6093                final int rightDifference = mLocation.right - another.mLocation.right;
6094                // First more to the right than second.
6095                if (rightDifference != 0) {
6096                    return -rightDifference;
6097                }
6098            }
6099            // Break tie by top.
6100            final int topDiference = mLocation.top - another.mLocation.top;
6101            if (topDiference != 0) {
6102                return topDiference;
6103            }
6104            // Break tie by height.
6105            final int heightDiference = mLocation.height() - another.mLocation.height();
6106            if (heightDiference != 0) {
6107                return -heightDiference;
6108            }
6109            // Break tie by width.
6110            final int widthDiference = mLocation.width() - another.mLocation.width();
6111            if (widthDiference != 0) {
6112                return -widthDiference;
6113            }
6114            // Just break the tie somehow. The accessibliity ids are unique
6115            // and stable, hence this is deterministic tie breaking.
6116            return mView.getAccessibilityViewId() - another.mView.getAccessibilityViewId();
6117        }
6118
6119        private void init(ViewGroup root, View view) {
6120            Rect viewLocation = mLocation;
6121            view.getDrawingRect(viewLocation);
6122            root.offsetDescendantRectToMyCoords(view, viewLocation);
6123            mView = view;
6124            mLayoutDirection = root.getResolvedLayoutDirection();
6125        }
6126
6127        private void clear() {
6128            mView = null;
6129            mLocation.set(0, 0, 0, 0);
6130        }
6131    }
6132}
6133