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