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