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