ViewGroup.java revision b84b94e1a04cd1f396dd6fef98d65ca1a2729c92
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        }
2828
2829        if (hasNoCache) {
2830            boolean layerRendered = false;
2831            if (layerType == LAYER_TYPE_HARDWARE) {
2832                final HardwareLayer layer = child.getHardwareLayer();
2833                if (layer != null && layer.isValid()) {
2834                    child.mLayerPaint.setAlpha((int) (alpha * 255));
2835                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, child.mLayerPaint);
2836                    layerRendered = true;
2837                } else {
2838                    final int scrollX = hasDisplayList ? 0 : sx;
2839                    final int scrollY = hasDisplayList ? 0 : sy;
2840                    canvas.saveLayer(scrollX, scrollY,
2841                            scrollX + cr - cl, scrollY + cb - ct, child.mLayerPaint,
2842                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
2843                }
2844            }
2845
2846            if (!layerRendered) {
2847                if (!hasDisplayList) {
2848                    // Fast path for layouts with no backgrounds
2849                    if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
2850                        if (ViewDebug.TRACE_HIERARCHY) {
2851                            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
2852                        }
2853                        child.mPrivateFlags &= ~DIRTY_MASK;
2854                        child.dispatchDraw(canvas);
2855                    } else {
2856                        child.draw(canvas);
2857                    }
2858                } else {
2859                    child.mPrivateFlags &= ~DIRTY_MASK;
2860                    ((HardwareCanvas) canvas).drawDisplayList(displayList, cr - cl, cb - ct, null);
2861                }
2862            }
2863        } else if (cache != null) {
2864            child.mPrivateFlags &= ~DIRTY_MASK;
2865            Paint cachePaint;
2866
2867            if (layerType == LAYER_TYPE_NONE) {
2868                cachePaint = mCachePaint;
2869                if (alpha < 1.0f) {
2870                    cachePaint.setAlpha((int) (alpha * 255));
2871                    mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE;
2872                } else if  ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) {
2873                    cachePaint.setAlpha(255);
2874                    mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE;
2875                }
2876            } else {
2877                cachePaint = child.mLayerPaint;
2878                cachePaint.setAlpha((int) (alpha * 255));
2879            }
2880            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
2881        }
2882
2883        canvas.restoreToCount(restoreTo);
2884
2885        if (a != null && !more) {
2886            if (!hardwareAccelerated && !a.getFillAfter()) {
2887                child.onSetAlpha(255);
2888            }
2889            finishAnimatingView(child, a);
2890        }
2891
2892        if (more && hardwareAccelerated) {
2893            // invalidation is the trigger to recreate display lists, so if we're using
2894            // display lists to render, force an invalidate to allow the animation to
2895            // continue drawing another frame
2896            invalidate(true);
2897            if (a.hasAlpha() && (child.mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
2898                // alpha animations should cause the child to recreate its display list
2899                child.invalidate(true);
2900            }
2901        }
2902
2903        child.mRecreateDisplayList = false;
2904
2905        return more;
2906    }
2907
2908    /**
2909     *
2910     * @param enabled True if children should be drawn with layers, false otherwise.
2911     *
2912     * @hide
2913     */
2914    public void setChildrenLayersEnabled(boolean enabled) {
2915        if (enabled != mDrawLayers) {
2916            mDrawLayers = enabled;
2917            invalidate(true);
2918
2919            // We need to invalidate any child with a layer. For instance,
2920            // if a child is backed by a hardware layer and we disable layers
2921            // the child is marked as not dirty (flags cleared the last time
2922            // the child was drawn inside its layer.) However, that child might
2923            // never have created its own display list or have an obsolete
2924            // display list. By invalidating the child we ensure the display
2925            // list is in sync with the content of the hardware layer.
2926            for (int i = 0; i < mChildrenCount; i++) {
2927                View child = mChildren[i];
2928                if (child.mLayerType != LAYER_TYPE_NONE) {
2929                    child.invalidate(true);
2930                }
2931            }
2932        }
2933    }
2934
2935    /**
2936     * By default, children are clipped to their bounds before drawing. This
2937     * allows view groups to override this behavior for animations, etc.
2938     *
2939     * @param clipChildren true to clip children to their bounds,
2940     *        false otherwise
2941     * @attr ref android.R.styleable#ViewGroup_clipChildren
2942     */
2943    public void setClipChildren(boolean clipChildren) {
2944        setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren);
2945    }
2946
2947    /**
2948     * By default, children are clipped to the padding of the ViewGroup. This
2949     * allows view groups to override this behavior
2950     *
2951     * @param clipToPadding true to clip children to the padding of the
2952     *        group, false otherwise
2953     * @attr ref android.R.styleable#ViewGroup_clipToPadding
2954     */
2955    public void setClipToPadding(boolean clipToPadding) {
2956        setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
2957    }
2958
2959    /**
2960     * {@inheritDoc}
2961     */
2962    @Override
2963    public void dispatchSetSelected(boolean selected) {
2964        final View[] children = mChildren;
2965        final int count = mChildrenCount;
2966        for (int i = 0; i < count; i++) {
2967            children[i].setSelected(selected);
2968        }
2969    }
2970
2971    /**
2972     * {@inheritDoc}
2973     */
2974    @Override
2975    public void dispatchSetActivated(boolean activated) {
2976        final View[] children = mChildren;
2977        final int count = mChildrenCount;
2978        for (int i = 0; i < count; i++) {
2979            children[i].setActivated(activated);
2980        }
2981    }
2982
2983    @Override
2984    protected void dispatchSetPressed(boolean pressed) {
2985        final View[] children = mChildren;
2986        final int count = mChildrenCount;
2987        for (int i = 0; i < count; i++) {
2988            children[i].setPressed(pressed);
2989        }
2990    }
2991
2992    /**
2993     * When this property is set to true, this ViewGroup supports static transformations on
2994     * children; this causes
2995     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
2996     * invoked when a child is drawn.
2997     *
2998     * Any subclass overriding
2999     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
3000     * set this property to true.
3001     *
3002     * @param enabled True to enable static transformations on children, false otherwise.
3003     *
3004     * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS
3005     */
3006    protected void setStaticTransformationsEnabled(boolean enabled) {
3007        setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled);
3008    }
3009
3010    /**
3011     * {@inheritDoc}
3012     *
3013     * @see #setStaticTransformationsEnabled(boolean)
3014     */
3015    protected boolean getChildStaticTransformation(View child, Transformation t) {
3016        return false;
3017    }
3018
3019    /**
3020     * {@hide}
3021     */
3022    @Override
3023    protected View findViewTraversal(int id) {
3024        if (id == mID) {
3025            return this;
3026        }
3027
3028        final View[] where = mChildren;
3029        final int len = mChildrenCount;
3030
3031        for (int i = 0; i < len; i++) {
3032            View v = where[i];
3033
3034            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3035                v = v.findViewById(id);
3036
3037                if (v != null) {
3038                    return v;
3039                }
3040            }
3041        }
3042
3043        return null;
3044    }
3045
3046    /**
3047     * {@hide}
3048     */
3049    @Override
3050    protected View findViewWithTagTraversal(Object tag) {
3051        if (tag != null && tag.equals(mTag)) {
3052            return this;
3053        }
3054
3055        final View[] where = mChildren;
3056        final int len = mChildrenCount;
3057
3058        for (int i = 0; i < len; i++) {
3059            View v = where[i];
3060
3061            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3062                v = v.findViewWithTag(tag);
3063
3064                if (v != null) {
3065                    return v;
3066                }
3067            }
3068        }
3069
3070        return null;
3071    }
3072
3073    /**
3074     * {@hide}
3075     */
3076    @Override
3077    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
3078        if (predicate.apply(this)) {
3079            return this;
3080        }
3081
3082        final View[] where = mChildren;
3083        final int len = mChildrenCount;
3084
3085        for (int i = 0; i < len; i++) {
3086            View v = where[i];
3087
3088            if (v != childToSkip && (v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3089                v = v.findViewByPredicate(predicate);
3090
3091                if (v != null) {
3092                    return v;
3093                }
3094            }
3095        }
3096
3097        return null;
3098    }
3099
3100    /**
3101     * Adds a child view. If no layout parameters are already set on the child, the
3102     * default parameters for this ViewGroup are set on the child.
3103     *
3104     * @param child the child view to add
3105     *
3106     * @see #generateDefaultLayoutParams()
3107     */
3108    public void addView(View child) {
3109        addView(child, -1);
3110    }
3111
3112    /**
3113     * Adds a child view. If no layout parameters are already set on the child, the
3114     * default parameters for this ViewGroup are set on the child.
3115     *
3116     * @param child the child view to add
3117     * @param index the position at which to add the child
3118     *
3119     * @see #generateDefaultLayoutParams()
3120     */
3121    public void addView(View child, int index) {
3122        LayoutParams params = child.getLayoutParams();
3123        if (params == null) {
3124            params = generateDefaultLayoutParams();
3125            if (params == null) {
3126                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
3127            }
3128        }
3129        addView(child, index, params);
3130    }
3131
3132    /**
3133     * Adds a child view with this ViewGroup's default layout parameters and the
3134     * specified width and height.
3135     *
3136     * @param child the child view to add
3137     */
3138    public void addView(View child, int width, int height) {
3139        final LayoutParams params = generateDefaultLayoutParams();
3140        params.width = width;
3141        params.height = height;
3142        addView(child, -1, params);
3143    }
3144
3145    /**
3146     * Adds a child view with the specified layout parameters.
3147     *
3148     * @param child the child view to add
3149     * @param params the layout parameters to set on the child
3150     */
3151    public void addView(View child, LayoutParams params) {
3152        addView(child, -1, params);
3153    }
3154
3155    /**
3156     * Adds a child view with the specified layout parameters.
3157     *
3158     * @param child the child view to add
3159     * @param index the position at which to add the child
3160     * @param params the layout parameters to set on the child
3161     */
3162    public void addView(View child, int index, LayoutParams params) {
3163        if (DBG) {
3164            System.out.println(this + " addView");
3165        }
3166
3167        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
3168        // therefore, we call requestLayout() on ourselves before, so that the child's request
3169        // will be blocked at our level
3170        requestLayout();
3171        invalidate(true);
3172        addViewInner(child, index, params, false);
3173    }
3174
3175    /**
3176     * {@inheritDoc}
3177     */
3178    public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
3179        if (!checkLayoutParams(params)) {
3180            throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this);
3181        }
3182        if (view.mParent != this) {
3183            throw new IllegalArgumentException("Given view not a child of " + this);
3184        }
3185        view.setLayoutParams(params);
3186    }
3187
3188    /**
3189     * {@inheritDoc}
3190     */
3191    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
3192        return  p != null;
3193    }
3194
3195    /**
3196     * Interface definition for a callback to be invoked when the hierarchy
3197     * within this view changed. The hierarchy changes whenever a child is added
3198     * to or removed from this view.
3199     */
3200    public interface OnHierarchyChangeListener {
3201        /**
3202         * Called when a new child is added to a parent view.
3203         *
3204         * @param parent the view in which a child was added
3205         * @param child the new child view added in the hierarchy
3206         */
3207        void onChildViewAdded(View parent, View child);
3208
3209        /**
3210         * Called when a child is removed from a parent view.
3211         *
3212         * @param parent the view from which the child was removed
3213         * @param child the child removed from the hierarchy
3214         */
3215        void onChildViewRemoved(View parent, View child);
3216    }
3217
3218    /**
3219     * Register a callback to be invoked when a child is added to or removed
3220     * from this view.
3221     *
3222     * @param listener the callback to invoke on hierarchy change
3223     */
3224    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
3225        mOnHierarchyChangeListener = listener;
3226    }
3227
3228    /**
3229     * @hide
3230     */
3231    protected void onViewAdded(View child) {
3232        if (mOnHierarchyChangeListener != null) {
3233            mOnHierarchyChangeListener.onChildViewAdded(this, child);
3234        }
3235    }
3236
3237    /**
3238     * @hide
3239     */
3240    protected void onViewRemoved(View child) {
3241        if (mOnHierarchyChangeListener != null) {
3242            mOnHierarchyChangeListener.onChildViewRemoved(this, child);
3243        }
3244    }
3245
3246    /**
3247     * Adds a view during layout. This is useful if in your onLayout() method,
3248     * you need to add more views (as does the list view for example).
3249     *
3250     * If index is negative, it means put it at the end of the list.
3251     *
3252     * @param child the view to add to the group
3253     * @param index the index at which the child must be added
3254     * @param params the layout parameters to associate with the child
3255     * @return true if the child was added, false otherwise
3256     */
3257    protected boolean addViewInLayout(View child, int index, LayoutParams params) {
3258        return addViewInLayout(child, index, params, false);
3259    }
3260
3261    /**
3262     * Adds a view during layout. This is useful if in your onLayout() method,
3263     * you need to add more views (as does the list view for example).
3264     *
3265     * If index is negative, it means put it at the end of the list.
3266     *
3267     * @param child the view to add to the group
3268     * @param index the index at which the child must be added
3269     * @param params the layout parameters to associate with the child
3270     * @param preventRequestLayout if true, calling this method will not trigger a
3271     *        layout request on child
3272     * @return true if the child was added, false otherwise
3273     */
3274    protected boolean addViewInLayout(View child, int index, LayoutParams params,
3275            boolean preventRequestLayout) {
3276        child.mParent = null;
3277        addViewInner(child, index, params, preventRequestLayout);
3278        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN;
3279        return true;
3280    }
3281
3282    /**
3283     * Prevents the specified child to be laid out during the next layout pass.
3284     *
3285     * @param child the child on which to perform the cleanup
3286     */
3287    protected void cleanupLayoutState(View child) {
3288        child.mPrivateFlags &= ~View.FORCE_LAYOUT;
3289    }
3290
3291    private void addViewInner(View child, int index, LayoutParams params,
3292            boolean preventRequestLayout) {
3293
3294        if (mTransition != null) {
3295            // Don't prevent other add transitions from completing, but cancel remove
3296            // transitions to let them complete the process before we add to the container
3297            mTransition.cancel(LayoutTransition.DISAPPEARING);
3298        }
3299
3300        if (child.getParent() != null) {
3301            throw new IllegalStateException("The specified child already has a parent. " +
3302                    "You must call removeView() on the child's parent first.");
3303        }
3304
3305        if (mTransition != null) {
3306            mTransition.addChild(this, child);
3307        }
3308
3309        if (!checkLayoutParams(params)) {
3310            params = generateLayoutParams(params);
3311        }
3312
3313        if (preventRequestLayout) {
3314            child.mLayoutParams = params;
3315        } else {
3316            child.setLayoutParams(params);
3317        }
3318
3319        if (index < 0) {
3320            index = mChildrenCount;
3321        }
3322
3323        addInArray(child, index);
3324
3325        // tell our children
3326        if (preventRequestLayout) {
3327            child.assignParent(this);
3328        } else {
3329            child.mParent = this;
3330        }
3331
3332        if (child.hasFocus()) {
3333            requestChildFocus(child, child.findFocus());
3334        }
3335
3336        AttachInfo ai = mAttachInfo;
3337        if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
3338            boolean lastKeepOn = ai.mKeepScreenOn;
3339            ai.mKeepScreenOn = false;
3340            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
3341            if (ai.mKeepScreenOn) {
3342                needGlobalAttributesUpdate(true);
3343            }
3344            ai.mKeepScreenOn = lastKeepOn;
3345        }
3346
3347        onViewAdded(child);
3348
3349        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
3350            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
3351        }
3352    }
3353
3354    private void addInArray(View child, int index) {
3355        View[] children = mChildren;
3356        final int count = mChildrenCount;
3357        final int size = children.length;
3358        if (index == count) {
3359            if (size == count) {
3360                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3361                System.arraycopy(children, 0, mChildren, 0, size);
3362                children = mChildren;
3363            }
3364            children[mChildrenCount++] = child;
3365        } else if (index < count) {
3366            if (size == count) {
3367                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3368                System.arraycopy(children, 0, mChildren, 0, index);
3369                System.arraycopy(children, index, mChildren, index + 1, count - index);
3370                children = mChildren;
3371            } else {
3372                System.arraycopy(children, index, children, index + 1, count - index);
3373            }
3374            children[index] = child;
3375            mChildrenCount++;
3376            if (mLastTouchDownIndex >= index) {
3377                mLastTouchDownIndex++;
3378            }
3379        } else {
3380            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
3381        }
3382    }
3383
3384    // This method also sets the child's mParent to null
3385    private void removeFromArray(int index) {
3386        final View[] children = mChildren;
3387        if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
3388            children[index].mParent = null;
3389        }
3390        final int count = mChildrenCount;
3391        if (index == count - 1) {
3392            children[--mChildrenCount] = null;
3393        } else if (index >= 0 && index < count) {
3394            System.arraycopy(children, index + 1, children, index, count - index - 1);
3395            children[--mChildrenCount] = null;
3396        } else {
3397            throw new IndexOutOfBoundsException();
3398        }
3399        if (mLastTouchDownIndex == index) {
3400            mLastTouchDownTime = 0;
3401            mLastTouchDownIndex = -1;
3402        } else if (mLastTouchDownIndex > index) {
3403            mLastTouchDownIndex--;
3404        }
3405    }
3406
3407    // This method also sets the children's mParent to null
3408    private void removeFromArray(int start, int count) {
3409        final View[] children = mChildren;
3410        final int childrenCount = mChildrenCount;
3411
3412        start = Math.max(0, start);
3413        final int end = Math.min(childrenCount, start + count);
3414
3415        if (start == end) {
3416            return;
3417        }
3418
3419        if (end == childrenCount) {
3420            for (int i = start; i < end; i++) {
3421                children[i].mParent = null;
3422                children[i] = null;
3423            }
3424        } else {
3425            for (int i = start; i < end; i++) {
3426                children[i].mParent = null;
3427            }
3428
3429            // Since we're looping above, we might as well do the copy, but is arraycopy()
3430            // faster than the extra 2 bounds checks we would do in the loop?
3431            System.arraycopy(children, end, children, start, childrenCount - end);
3432
3433            for (int i = childrenCount - (end - start); i < childrenCount; i++) {
3434                children[i] = null;
3435            }
3436        }
3437
3438        mChildrenCount -= (end - start);
3439    }
3440
3441    private void bindLayoutAnimation(View child) {
3442        Animation a = mLayoutAnimationController.getAnimationForView(child);
3443        child.setAnimation(a);
3444    }
3445
3446    /**
3447     * Subclasses should override this method to set layout animation
3448     * parameters on the supplied child.
3449     *
3450     * @param child the child to associate with animation parameters
3451     * @param params the child's layout parameters which hold the animation
3452     *        parameters
3453     * @param index the index of the child in the view group
3454     * @param count the number of children in the view group
3455     */
3456    protected void attachLayoutAnimationParameters(View child,
3457            LayoutParams params, int index, int count) {
3458        LayoutAnimationController.AnimationParameters animationParams =
3459                    params.layoutAnimationParameters;
3460        if (animationParams == null) {
3461            animationParams = new LayoutAnimationController.AnimationParameters();
3462            params.layoutAnimationParameters = animationParams;
3463        }
3464
3465        animationParams.count = count;
3466        animationParams.index = index;
3467    }
3468
3469    /**
3470     * {@inheritDoc}
3471     */
3472    public void removeView(View view) {
3473        removeViewInternal(view);
3474        requestLayout();
3475        invalidate(true);
3476    }
3477
3478    /**
3479     * Removes a view during layout. This is useful if in your onLayout() method,
3480     * you need to remove more views.
3481     *
3482     * @param view the view to remove from the group
3483     */
3484    public void removeViewInLayout(View view) {
3485        removeViewInternal(view);
3486    }
3487
3488    /**
3489     * Removes a range of views during layout. This is useful if in your onLayout() method,
3490     * you need to remove more views.
3491     *
3492     * @param start the index of the first view to remove from the group
3493     * @param count the number of views to remove from the group
3494     */
3495    public void removeViewsInLayout(int start, int count) {
3496        removeViewsInternal(start, count);
3497    }
3498
3499    /**
3500     * Removes the view at the specified position in the group.
3501     *
3502     * @param index the position in the group of the view to remove
3503     */
3504    public void removeViewAt(int index) {
3505        removeViewInternal(index, getChildAt(index));
3506        requestLayout();
3507        invalidate(true);
3508    }
3509
3510    /**
3511     * Removes the specified range of views from the group.
3512     *
3513     * @param start the first position in the group of the range of views to remove
3514     * @param count the number of views to remove
3515     */
3516    public void removeViews(int start, int count) {
3517        removeViewsInternal(start, count);
3518        requestLayout();
3519        invalidate(true);
3520    }
3521
3522    private void removeViewInternal(View view) {
3523        final int index = indexOfChild(view);
3524        if (index >= 0) {
3525            removeViewInternal(index, view);
3526        }
3527    }
3528
3529    private void removeViewInternal(int index, View view) {
3530
3531        if (mTransition != null) {
3532            mTransition.removeChild(this, view);
3533        }
3534
3535        boolean clearChildFocus = false;
3536        if (view == mFocused) {
3537            view.clearFocusForRemoval();
3538            clearChildFocus = true;
3539        }
3540
3541        if (view.getAnimation() != null ||
3542                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3543            addDisappearingView(view);
3544        } else if (view.mAttachInfo != null) {
3545           view.dispatchDetachedFromWindow();
3546        }
3547
3548        onViewRemoved(view);
3549
3550        needGlobalAttributesUpdate(false);
3551
3552        removeFromArray(index);
3553
3554        if (clearChildFocus) {
3555            clearChildFocus(view);
3556        }
3557    }
3558
3559    /**
3560     * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3561     * not null, changes in layout which occur because of children being added to or removed from
3562     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3563     * object. By default, the transition object is null (so layout changes are not animated).
3564     *
3565     * @param transition The LayoutTransition object that will animated changes in layout. A value
3566     * of <code>null</code> means no transition will run on layout changes.
3567     * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
3568     */
3569    public void setLayoutTransition(LayoutTransition transition) {
3570        if (mTransition != null) {
3571            mTransition.removeTransitionListener(mLayoutTransitionListener);
3572        }
3573        mTransition = transition;
3574        if (mTransition != null) {
3575            mTransition.addTransitionListener(mLayoutTransitionListener);
3576        }
3577    }
3578
3579    /**
3580     * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3581     * not null, changes in layout which occur because of children being added to or removed from
3582     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3583     * object. By default, the transition object is null (so layout changes are not animated).
3584     *
3585     * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
3586     * A value of <code>null</code> means no transition will run on layout changes.
3587     */
3588    public LayoutTransition getLayoutTransition() {
3589        return mTransition;
3590    }
3591
3592    private void removeViewsInternal(int start, int count) {
3593        final View focused = mFocused;
3594        final boolean detach = mAttachInfo != null;
3595        View clearChildFocus = null;
3596
3597        final View[] children = mChildren;
3598        final int end = start + count;
3599
3600        for (int i = start; i < end; i++) {
3601            final View view = children[i];
3602
3603            if (mTransition != null) {
3604                mTransition.removeChild(this, view);
3605            }
3606
3607            if (view == focused) {
3608                view.clearFocusForRemoval();
3609                clearChildFocus = view;
3610            }
3611
3612            if (view.getAnimation() != null ||
3613                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3614                addDisappearingView(view);
3615            } else if (detach) {
3616               view.dispatchDetachedFromWindow();
3617            }
3618
3619            needGlobalAttributesUpdate(false);
3620
3621            onViewRemoved(view);
3622        }
3623
3624        removeFromArray(start, count);
3625
3626        if (clearChildFocus != null) {
3627            clearChildFocus(clearChildFocus);
3628        }
3629    }
3630
3631    /**
3632     * Call this method to remove all child views from the
3633     * ViewGroup.
3634     */
3635    public void removeAllViews() {
3636        removeAllViewsInLayout();
3637        requestLayout();
3638        invalidate(true);
3639    }
3640
3641    /**
3642     * Called by a ViewGroup subclass to remove child views from itself,
3643     * when it must first know its size on screen before it can calculate how many
3644     * child views it will render. An example is a Gallery or a ListView, which
3645     * may "have" 50 children, but actually only render the number of children
3646     * that can currently fit inside the object on screen. Do not call
3647     * this method unless you are extending ViewGroup and understand the
3648     * view measuring and layout pipeline.
3649     */
3650    public void removeAllViewsInLayout() {
3651        final int count = mChildrenCount;
3652        if (count <= 0) {
3653            return;
3654        }
3655
3656        final View[] children = mChildren;
3657        mChildrenCount = 0;
3658
3659        final View focused = mFocused;
3660        final boolean detach = mAttachInfo != null;
3661        View clearChildFocus = null;
3662
3663        needGlobalAttributesUpdate(false);
3664
3665        for (int i = count - 1; i >= 0; i--) {
3666            final View view = children[i];
3667
3668            if (mTransition != null) {
3669                mTransition.removeChild(this, view);
3670            }
3671
3672            if (view == focused) {
3673                view.clearFocusForRemoval();
3674                clearChildFocus = view;
3675            }
3676
3677            if (view.getAnimation() != null ||
3678                    (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3679                addDisappearingView(view);
3680            } else if (detach) {
3681               view.dispatchDetachedFromWindow();
3682            }
3683
3684            onViewRemoved(view);
3685
3686            view.mParent = null;
3687            children[i] = null;
3688        }
3689
3690        if (clearChildFocus != null) {
3691            clearChildFocus(clearChildFocus);
3692        }
3693    }
3694
3695    /**
3696     * Finishes the removal of a detached view. This method will dispatch the detached from
3697     * window event and notify the hierarchy change listener.
3698     *
3699     * @param child the child to be definitely removed from the view hierarchy
3700     * @param animate if true and the view has an animation, the view is placed in the
3701     *                disappearing views list, otherwise, it is detached from the window
3702     *
3703     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3704     * @see #detachAllViewsFromParent()
3705     * @see #detachViewFromParent(View)
3706     * @see #detachViewFromParent(int)
3707     */
3708    protected void removeDetachedView(View child, boolean animate) {
3709        if (mTransition != null) {
3710            mTransition.removeChild(this, child);
3711        }
3712
3713        if (child == mFocused) {
3714            child.clearFocus();
3715        }
3716
3717        if ((animate && child.getAnimation() != null) ||
3718                (mTransitioningViews != null && mTransitioningViews.contains(child))) {
3719            addDisappearingView(child);
3720        } else if (child.mAttachInfo != null) {
3721            child.dispatchDetachedFromWindow();
3722        }
3723
3724        onViewRemoved(child);
3725    }
3726
3727    /**
3728     * Attaches a view to this view group. Attaching a view assigns this group as the parent,
3729     * sets the layout parameters and puts the view in the list of children so it can be retrieved
3730     * by calling {@link #getChildAt(int)}.
3731     *
3732     * This method should be called only for view which were detached from their parent.
3733     *
3734     * @param child the child to attach
3735     * @param index the index at which the child should be attached
3736     * @param params the layout parameters of the child
3737     *
3738     * @see #removeDetachedView(View, boolean)
3739     * @see #detachAllViewsFromParent()
3740     * @see #detachViewFromParent(View)
3741     * @see #detachViewFromParent(int)
3742     */
3743    protected void attachViewToParent(View child, int index, LayoutParams params) {
3744        child.mLayoutParams = params;
3745
3746        if (index < 0) {
3747            index = mChildrenCount;
3748        }
3749
3750        addInArray(child, index);
3751
3752        child.mParent = this;
3753        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) |
3754                DRAWN | INVALIDATED;
3755        this.mPrivateFlags |= INVALIDATED;
3756
3757        if (child.hasFocus()) {
3758            requestChildFocus(child, child.findFocus());
3759        }
3760    }
3761
3762    /**
3763     * Detaches a view from its parent. Detaching a view should be temporary and followed
3764     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3765     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3766     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3767     *
3768     * @param child the child to detach
3769     *
3770     * @see #detachViewFromParent(int)
3771     * @see #detachViewsFromParent(int, int)
3772     * @see #detachAllViewsFromParent()
3773     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3774     * @see #removeDetachedView(View, boolean)
3775     */
3776    protected void detachViewFromParent(View child) {
3777        removeFromArray(indexOfChild(child));
3778    }
3779
3780    /**
3781     * Detaches a view from its parent. Detaching a view should be temporary and followed
3782     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3783     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3784     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3785     *
3786     * @param index the index of the child to detach
3787     *
3788     * @see #detachViewFromParent(View)
3789     * @see #detachAllViewsFromParent()
3790     * @see #detachViewsFromParent(int, int)
3791     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3792     * @see #removeDetachedView(View, boolean)
3793     */
3794    protected void detachViewFromParent(int index) {
3795        removeFromArray(index);
3796    }
3797
3798    /**
3799     * Detaches a range of view from their parent. Detaching a view should be temporary and followed
3800     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3801     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its
3802     * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3803     *
3804     * @param start the first index of the childrend range to detach
3805     * @param count the number of children to detach
3806     *
3807     * @see #detachViewFromParent(View)
3808     * @see #detachViewFromParent(int)
3809     * @see #detachAllViewsFromParent()
3810     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3811     * @see #removeDetachedView(View, boolean)
3812     */
3813    protected void detachViewsFromParent(int start, int count) {
3814        removeFromArray(start, count);
3815    }
3816
3817    /**
3818     * Detaches all views from the parent. Detaching a view should be temporary and followed
3819     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3820     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3821     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3822     *
3823     * @see #detachViewFromParent(View)
3824     * @see #detachViewFromParent(int)
3825     * @see #detachViewsFromParent(int, int)
3826     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3827     * @see #removeDetachedView(View, boolean)
3828     */
3829    protected void detachAllViewsFromParent() {
3830        final int count = mChildrenCount;
3831        if (count <= 0) {
3832            return;
3833        }
3834
3835        final View[] children = mChildren;
3836        mChildrenCount = 0;
3837
3838        for (int i = count - 1; i >= 0; i--) {
3839            children[i].mParent = null;
3840            children[i] = null;
3841        }
3842    }
3843
3844    /**
3845     * Don't call or override this method. It is used for the implementation of
3846     * the view hierarchy.
3847     */
3848    public final void invalidateChild(View child, final Rect dirty) {
3849        if (ViewDebug.TRACE_HIERARCHY) {
3850            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD);
3851        }
3852
3853        ViewParent parent = this;
3854
3855        final AttachInfo attachInfo = mAttachInfo;
3856        if (attachInfo != null) {
3857            // If the child is drawing an animation, we want to copy this flag onto
3858            // ourselves and the parent to make sure the invalidate request goes
3859            // through
3860            final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;
3861
3862            if (dirty == null) {
3863                if (child.mLayerType != LAYER_TYPE_NONE) {
3864                    mPrivateFlags |= INVALIDATED;
3865                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
3866                    child.mLocalDirtyRect.setEmpty();
3867                }
3868                do {
3869                    View view = null;
3870                    if (parent instanceof View) {
3871                        view = (View) parent;
3872                        if (view.mLayerType != LAYER_TYPE_NONE) {
3873                            view.mLocalDirtyRect.setEmpty();
3874                            if (view.getParent() instanceof View) {
3875                                final View grandParent = (View) view.getParent();
3876                                grandParent.mPrivateFlags |= INVALIDATED;
3877                                grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID;
3878                            }
3879                        }
3880                        if ((view.mPrivateFlags & DIRTY_MASK) != 0) {
3881                            // already marked dirty - we're done
3882                            break;
3883                        }
3884                    }
3885
3886                    if (drawAnimation) {
3887                        if (view != null) {
3888                            view.mPrivateFlags |= DRAW_ANIMATION;
3889                        } else if (parent instanceof ViewRootImpl) {
3890                            ((ViewRootImpl) parent).mIsAnimating = true;
3891                        }
3892                    }
3893
3894                    if (parent instanceof ViewRootImpl) {
3895                        ((ViewRootImpl) parent).invalidate();
3896                        parent = null;
3897                    } else if (view != null) {
3898                        if ((view.mPrivateFlags & DRAWN) == DRAWN ||
3899                                (view.mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
3900                            view.mPrivateFlags &= ~DRAWING_CACHE_VALID;
3901                            view.mPrivateFlags |= DIRTY;
3902                            parent = view.mParent;
3903                        } else {
3904                            parent = null;
3905                        }
3906                    }
3907                } while (parent != null);
3908            } else {
3909                // Check whether the child that requests the invalidate is fully opaque
3910                final boolean isOpaque = child.isOpaque() && !drawAnimation &&
3911                        child.getAnimation() == null;
3912                // Mark the child as dirty, using the appropriate flag
3913                // Make sure we do not set both flags at the same time
3914                int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
3915
3916                if (child.mLayerType != LAYER_TYPE_NONE) {
3917                    mPrivateFlags |= INVALIDATED;
3918                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
3919                    child.mLocalDirtyRect.union(dirty);
3920                }
3921
3922                final int[] location = attachInfo.mInvalidateChildLocation;
3923                location[CHILD_LEFT_INDEX] = child.mLeft;
3924                location[CHILD_TOP_INDEX] = child.mTop;
3925                Matrix childMatrix = child.getMatrix();
3926                if (!childMatrix.isIdentity()) {
3927                    RectF boundingRect = attachInfo.mTmpTransformRect;
3928                    boundingRect.set(dirty);
3929                    //boundingRect.inset(-0.5f, -0.5f);
3930                    childMatrix.mapRect(boundingRect);
3931                    dirty.set((int) (boundingRect.left - 0.5f),
3932                            (int) (boundingRect.top - 0.5f),
3933                            (int) (boundingRect.right + 0.5f),
3934                            (int) (boundingRect.bottom + 0.5f));
3935                }
3936
3937                do {
3938                    View view = null;
3939                    if (parent instanceof View) {
3940                        view = (View) parent;
3941                        if (view.mLayerType != LAYER_TYPE_NONE &&
3942                                view.getParent() instanceof View) {
3943                            final View grandParent = (View) view.getParent();
3944                            grandParent.mPrivateFlags |= INVALIDATED;
3945                            grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID;
3946                        }
3947                    }
3948
3949                    if (drawAnimation) {
3950                        if (view != null) {
3951                            view.mPrivateFlags |= DRAW_ANIMATION;
3952                        } else if (parent instanceof ViewRootImpl) {
3953                            ((ViewRootImpl) parent).mIsAnimating = true;
3954                        }
3955                    }
3956
3957                    // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
3958                    // flag coming from the child that initiated the invalidate
3959                    if (view != null) {
3960                        if ((view.mViewFlags & FADING_EDGE_MASK) != 0 &&
3961                                view.getSolidColor() == 0) {
3962                            opaqueFlag = DIRTY;
3963                        }
3964                        if ((view.mPrivateFlags & DIRTY_MASK) != DIRTY) {
3965                            view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;
3966                        }
3967                    }
3968
3969                    parent = parent.invalidateChildInParent(location, dirty);
3970                    if (view != null) {
3971                        // Account for transform on current parent
3972                        Matrix m = view.getMatrix();
3973                        if (!m.isIdentity()) {
3974                            RectF boundingRect = attachInfo.mTmpTransformRect;
3975                            boundingRect.set(dirty);
3976                            m.mapRect(boundingRect);
3977                            dirty.set((int) boundingRect.left, (int) boundingRect.top,
3978                                    (int) (boundingRect.right + 0.5f),
3979                                    (int) (boundingRect.bottom + 0.5f));
3980                        }
3981                    }
3982                } while (parent != null);
3983            }
3984        }
3985    }
3986
3987    /**
3988     * Don't call or override this method. It is used for the implementation of
3989     * the view hierarchy.
3990     *
3991     * This implementation returns null if this ViewGroup does not have a parent,
3992     * if this ViewGroup is already fully invalidated or if the dirty rectangle
3993     * does not intersect with this ViewGroup's bounds.
3994     */
3995    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
3996        if (ViewDebug.TRACE_HIERARCHY) {
3997            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD_IN_PARENT);
3998        }
3999
4000        if ((mPrivateFlags & DRAWN) == DRAWN ||
4001                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
4002            if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
4003                        FLAG_OPTIMIZE_INVALIDATE) {
4004                dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
4005                        location[CHILD_TOP_INDEX] - mScrollY);
4006
4007                final int left = mLeft;
4008                final int top = mTop;
4009
4010                if ((mGroupFlags & FLAG_CLIP_CHILDREN) != FLAG_CLIP_CHILDREN ||
4011                        dirty.intersect(0, 0, mRight - left, mBottom - top) ||
4012                        (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
4013                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
4014
4015                    location[CHILD_LEFT_INDEX] = left;
4016                    location[CHILD_TOP_INDEX] = top;
4017
4018                    if (mLayerType != LAYER_TYPE_NONE) {
4019                        mLocalDirtyRect.union(dirty);
4020                    }
4021
4022                    return mParent;
4023                }
4024            } else {
4025                mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
4026
4027                location[CHILD_LEFT_INDEX] = mLeft;
4028                location[CHILD_TOP_INDEX] = mTop;
4029                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
4030                    dirty.set(0, 0, mRight - mLeft, mBottom - mTop);
4031                } else {
4032                    // in case the dirty rect extends outside the bounds of this container
4033                    dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
4034                }
4035
4036                if (mLayerType != LAYER_TYPE_NONE) {
4037                    mLocalDirtyRect.union(dirty);
4038                }
4039
4040                return mParent;
4041            }
4042        }
4043
4044        return null;
4045    }
4046
4047    /**
4048     * Offset a rectangle that is in a descendant's coordinate
4049     * space into our coordinate space.
4050     * @param descendant A descendant of this view
4051     * @param rect A rectangle defined in descendant's coordinate space.
4052     */
4053    public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) {
4054        offsetRectBetweenParentAndChild(descendant, rect, true, false);
4055    }
4056
4057    /**
4058     * Offset a rectangle that is in our coordinate space into an ancestor's
4059     * coordinate space.
4060     * @param descendant A descendant of this view
4061     * @param rect A rectangle defined in descendant's coordinate space.
4062     */
4063    public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) {
4064        offsetRectBetweenParentAndChild(descendant, rect, false, false);
4065    }
4066
4067    /**
4068     * Helper method that offsets a rect either from parent to descendant or
4069     * descendant to parent.
4070     */
4071    void offsetRectBetweenParentAndChild(View descendant, Rect rect,
4072            boolean offsetFromChildToParent, boolean clipToBounds) {
4073
4074        // already in the same coord system :)
4075        if (descendant == this) {
4076            return;
4077        }
4078
4079        ViewParent theParent = descendant.mParent;
4080
4081        // search and offset up to the parent
4082        while ((theParent != null)
4083                && (theParent instanceof View)
4084                && (theParent != this)) {
4085
4086            if (offsetFromChildToParent) {
4087                rect.offset(descendant.mLeft - descendant.mScrollX,
4088                        descendant.mTop - descendant.mScrollY);
4089                if (clipToBounds) {
4090                    View p = (View) theParent;
4091                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4092                }
4093            } else {
4094                if (clipToBounds) {
4095                    View p = (View) theParent;
4096                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4097                }
4098                rect.offset(descendant.mScrollX - descendant.mLeft,
4099                        descendant.mScrollY - descendant.mTop);
4100            }
4101
4102            descendant = (View) theParent;
4103            theParent = descendant.mParent;
4104        }
4105
4106        // now that we are up to this view, need to offset one more time
4107        // to get into our coordinate space
4108        if (theParent == this) {
4109            if (offsetFromChildToParent) {
4110                rect.offset(descendant.mLeft - descendant.mScrollX,
4111                        descendant.mTop - descendant.mScrollY);
4112            } else {
4113                rect.offset(descendant.mScrollX - descendant.mLeft,
4114                        descendant.mScrollY - descendant.mTop);
4115            }
4116        } else {
4117            throw new IllegalArgumentException("parameter must be a descendant of this view");
4118        }
4119    }
4120
4121    /**
4122     * Offset the vertical location of all children of this view by the specified number of pixels.
4123     *
4124     * @param offset the number of pixels to offset
4125     *
4126     * @hide
4127     */
4128    public void offsetChildrenTopAndBottom(int offset) {
4129        final int count = mChildrenCount;
4130        final View[] children = mChildren;
4131
4132        for (int i = 0; i < count; i++) {
4133            final View v = children[i];
4134            v.mTop += offset;
4135            v.mBottom += offset;
4136        }
4137    }
4138
4139    /**
4140     * {@inheritDoc}
4141     */
4142    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
4143        int dx = child.mLeft - mScrollX;
4144        int dy = child.mTop - mScrollY;
4145        if (offset != null) {
4146            offset.x += dx;
4147            offset.y += dy;
4148        }
4149        r.offset(dx, dy);
4150        return r.intersect(0, 0, mRight - mLeft, mBottom - mTop) &&
4151               (mParent == null || mParent.getChildVisibleRect(this, r, offset));
4152    }
4153
4154    /**
4155     * {@inheritDoc}
4156     */
4157    @Override
4158    public final void layout(int l, int t, int r, int b) {
4159        if (mTransition == null || !mTransition.isChangingLayout()) {
4160            super.layout(l, t, r, b);
4161        } else {
4162            // record the fact that we noop'd it; request layout when transition finishes
4163            mLayoutSuppressed = true;
4164        }
4165    }
4166
4167    /**
4168     * {@inheritDoc}
4169     */
4170    @Override
4171    protected abstract void onLayout(boolean changed,
4172            int l, int t, int r, int b);
4173
4174    /**
4175     * Indicates whether the view group has the ability to animate its children
4176     * after the first layout.
4177     *
4178     * @return true if the children can be animated, false otherwise
4179     */
4180    protected boolean canAnimate() {
4181        return mLayoutAnimationController != null;
4182    }
4183
4184    /**
4185     * Runs the layout animation. Calling this method triggers a relayout of
4186     * this view group.
4187     */
4188    public void startLayoutAnimation() {
4189        if (mLayoutAnimationController != null) {
4190            mGroupFlags |= FLAG_RUN_ANIMATION;
4191            requestLayout();
4192        }
4193    }
4194
4195    /**
4196     * Schedules the layout animation to be played after the next layout pass
4197     * of this view group. This can be used to restart the layout animation
4198     * when the content of the view group changes or when the activity is
4199     * paused and resumed.
4200     */
4201    public void scheduleLayoutAnimation() {
4202        mGroupFlags |= FLAG_RUN_ANIMATION;
4203    }
4204
4205    /**
4206     * Sets the layout animation controller used to animate the group's
4207     * children after the first layout.
4208     *
4209     * @param controller the animation controller
4210     */
4211    public void setLayoutAnimation(LayoutAnimationController controller) {
4212        mLayoutAnimationController = controller;
4213        if (mLayoutAnimationController != null) {
4214            mGroupFlags |= FLAG_RUN_ANIMATION;
4215        }
4216    }
4217
4218    /**
4219     * Returns the layout animation controller used to animate the group's
4220     * children.
4221     *
4222     * @return the current animation controller
4223     */
4224    public LayoutAnimationController getLayoutAnimation() {
4225        return mLayoutAnimationController;
4226    }
4227
4228    /**
4229     * Indicates whether the children's drawing cache is used during a layout
4230     * animation. By default, the drawing cache is enabled but this will prevent
4231     * nested layout animations from working. To nest animations, you must disable
4232     * the cache.
4233     *
4234     * @return true if the animation cache is enabled, false otherwise
4235     *
4236     * @see #setAnimationCacheEnabled(boolean)
4237     * @see View#setDrawingCacheEnabled(boolean)
4238     */
4239    @ViewDebug.ExportedProperty
4240    public boolean isAnimationCacheEnabled() {
4241        return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
4242    }
4243
4244    /**
4245     * Enables or disables the children's drawing cache during a layout animation.
4246     * By default, the drawing cache is enabled but this will prevent nested
4247     * layout animations from working. To nest animations, you must disable the
4248     * cache.
4249     *
4250     * @param enabled true to enable the animation cache, false otherwise
4251     *
4252     * @see #isAnimationCacheEnabled()
4253     * @see View#setDrawingCacheEnabled(boolean)
4254     */
4255    public void setAnimationCacheEnabled(boolean enabled) {
4256        setBooleanFlag(FLAG_ANIMATION_CACHE, enabled);
4257    }
4258
4259    /**
4260     * Indicates whether this ViewGroup will always try to draw its children using their
4261     * drawing cache. By default this property is enabled.
4262     *
4263     * @return true if the animation cache is enabled, false otherwise
4264     *
4265     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4266     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4267     * @see View#setDrawingCacheEnabled(boolean)
4268     */
4269    @ViewDebug.ExportedProperty(category = "drawing")
4270    public boolean isAlwaysDrawnWithCacheEnabled() {
4271        return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE;
4272    }
4273
4274    /**
4275     * Indicates whether this ViewGroup will always try to draw its children using their
4276     * drawing cache. This property can be set to true when the cache rendering is
4277     * slightly different from the children's normal rendering. Renderings can be different,
4278     * for instance, when the cache's quality is set to low.
4279     *
4280     * When this property is disabled, the ViewGroup will use the drawing cache of its
4281     * children only when asked to. It's usually the task of subclasses to tell ViewGroup
4282     * when to start using the drawing cache and when to stop using it.
4283     *
4284     * @param always true to always draw with the drawing cache, false otherwise
4285     *
4286     * @see #isAlwaysDrawnWithCacheEnabled()
4287     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4288     * @see View#setDrawingCacheEnabled(boolean)
4289     * @see View#setDrawingCacheQuality(int)
4290     */
4291    public void setAlwaysDrawnWithCacheEnabled(boolean always) {
4292        setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always);
4293    }
4294
4295    /**
4296     * Indicates whether the ViewGroup is currently drawing its children using
4297     * their drawing cache.
4298     *
4299     * @return true if children should be drawn with their cache, false otherwise
4300     *
4301     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4302     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4303     */
4304    @ViewDebug.ExportedProperty(category = "drawing")
4305    protected boolean isChildrenDrawnWithCacheEnabled() {
4306        return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE;
4307    }
4308
4309    /**
4310     * Tells the ViewGroup to draw its children using their drawing cache. This property
4311     * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache
4312     * will be used only if it has been enabled.
4313     *
4314     * Subclasses should call this method to start and stop using the drawing cache when
4315     * they perform performance sensitive operations, like scrolling or animating.
4316     *
4317     * @param enabled true if children should be drawn with their cache, false otherwise
4318     *
4319     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4320     * @see #isChildrenDrawnWithCacheEnabled()
4321     */
4322    protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
4323        setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled);
4324    }
4325
4326    /**
4327     * Indicates whether the ViewGroup is drawing its children in the order defined by
4328     * {@link #getChildDrawingOrder(int, int)}.
4329     *
4330     * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)},
4331     *         false otherwise
4332     *
4333     * @see #setChildrenDrawingOrderEnabled(boolean)
4334     * @see #getChildDrawingOrder(int, int)
4335     */
4336    @ViewDebug.ExportedProperty(category = "drawing")
4337    protected boolean isChildrenDrawingOrderEnabled() {
4338        return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER;
4339    }
4340
4341    /**
4342     * Tells the ViewGroup whether to draw its children in the order defined by the method
4343     * {@link #getChildDrawingOrder(int, int)}.
4344     *
4345     * @param enabled true if the order of the children when drawing is determined by
4346     *        {@link #getChildDrawingOrder(int, int)}, false otherwise
4347     *
4348     * @see #isChildrenDrawingOrderEnabled()
4349     * @see #getChildDrawingOrder(int, int)
4350     */
4351    protected void setChildrenDrawingOrderEnabled(boolean enabled) {
4352        setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled);
4353    }
4354
4355    private void setBooleanFlag(int flag, boolean value) {
4356        if (value) {
4357            mGroupFlags |= flag;
4358        } else {
4359            mGroupFlags &= ~flag;
4360        }
4361    }
4362
4363    /**
4364     * Returns an integer indicating what types of drawing caches are kept in memory.
4365     *
4366     * @see #setPersistentDrawingCache(int)
4367     * @see #setAnimationCacheEnabled(boolean)
4368     *
4369     * @return one or a combination of {@link #PERSISTENT_NO_CACHE},
4370     *         {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4371     *         and {@link #PERSISTENT_ALL_CACHES}
4372     */
4373    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4374        @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE,        to = "NONE"),
4375        @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"),
4376        @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"),
4377        @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES,      to = "ALL")
4378    })
4379    public int getPersistentDrawingCache() {
4380        return mPersistentDrawingCache;
4381    }
4382
4383    /**
4384     * Indicates what types of drawing caches should be kept in memory after
4385     * they have been created.
4386     *
4387     * @see #getPersistentDrawingCache()
4388     * @see #setAnimationCacheEnabled(boolean)
4389     *
4390     * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE},
4391     *        {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4392     *        and {@link #PERSISTENT_ALL_CACHES}
4393     */
4394    public void setPersistentDrawingCache(int drawingCacheToKeep) {
4395        mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES;
4396    }
4397
4398    /**
4399     * Returns a new set of layout parameters based on the supplied attributes set.
4400     *
4401     * @param attrs the attributes to build the layout parameters from
4402     *
4403     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4404     *         of its descendants
4405     */
4406    public LayoutParams generateLayoutParams(AttributeSet attrs) {
4407        return new LayoutParams(getContext(), attrs);
4408    }
4409
4410    /**
4411     * Returns a safe set of layout parameters based on the supplied layout params.
4412     * When a ViewGroup is passed a View whose layout params do not pass the test of
4413     * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
4414     * is invoked. This method should return a new set of layout params suitable for
4415     * this ViewGroup, possibly by copying the appropriate attributes from the
4416     * specified set of layout params.
4417     *
4418     * @param p The layout parameters to convert into a suitable set of layout parameters
4419     *          for this ViewGroup.
4420     *
4421     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4422     *         of its descendants
4423     */
4424    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
4425        return p;
4426    }
4427
4428    /**
4429     * Returns a set of default layout parameters. These parameters are requested
4430     * when the View passed to {@link #addView(View)} has no layout parameters
4431     * already set. If null is returned, an exception is thrown from addView.
4432     *
4433     * @return a set of default layout parameters or null
4434     */
4435    protected LayoutParams generateDefaultLayoutParams() {
4436        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
4437    }
4438
4439    /**
4440     * @hide
4441     */
4442    @Override
4443    protected boolean dispatchConsistencyCheck(int consistency) {
4444        boolean result = super.dispatchConsistencyCheck(consistency);
4445
4446        final int count = mChildrenCount;
4447        final View[] children = mChildren;
4448        for (int i = 0; i < count; i++) {
4449            if (!children[i].dispatchConsistencyCheck(consistency)) result = false;
4450        }
4451
4452        return result;
4453    }
4454
4455    /**
4456     * @hide
4457     */
4458    @Override
4459    protected boolean onConsistencyCheck(int consistency) {
4460        boolean result = super.onConsistencyCheck(consistency);
4461
4462        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
4463        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
4464
4465        if (checkLayout) {
4466            final int count = mChildrenCount;
4467            final View[] children = mChildren;
4468            for (int i = 0; i < count; i++) {
4469                if (children[i].getParent() != this) {
4470                    result = false;
4471                    android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
4472                            "View " + children[i] + " has no parent/a parent that is not " + this);
4473                }
4474            }
4475        }
4476
4477        if (checkDrawing) {
4478            // If this group is dirty, check that the parent is dirty as well
4479            if ((mPrivateFlags & DIRTY_MASK) != 0) {
4480                final ViewParent parent = getParent();
4481                if (parent != null && !(parent instanceof ViewRootImpl)) {
4482                    if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) {
4483                        result = false;
4484                        android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
4485                                "ViewGroup " + this + " is dirty but its parent is not: " + this);
4486                    }
4487                }
4488            }
4489        }
4490
4491        return result;
4492    }
4493
4494    /**
4495     * {@inheritDoc}
4496     */
4497    @Override
4498    protected void debug(int depth) {
4499        super.debug(depth);
4500        String output;
4501
4502        if (mFocused != null) {
4503            output = debugIndent(depth);
4504            output += "mFocused";
4505            Log.d(VIEW_LOG_TAG, output);
4506        }
4507        if (mChildrenCount != 0) {
4508            output = debugIndent(depth);
4509            output += "{";
4510            Log.d(VIEW_LOG_TAG, output);
4511        }
4512        int count = mChildrenCount;
4513        for (int i = 0; i < count; i++) {
4514            View child = mChildren[i];
4515            child.debug(depth + 1);
4516        }
4517
4518        if (mChildrenCount != 0) {
4519            output = debugIndent(depth);
4520            output += "}";
4521            Log.d(VIEW_LOG_TAG, output);
4522        }
4523    }
4524
4525    /**
4526     * Returns the position in the group of the specified child view.
4527     *
4528     * @param child the view for which to get the position
4529     * @return a positive integer representing the position of the view in the
4530     *         group, or -1 if the view does not exist in the group
4531     */
4532    public int indexOfChild(View child) {
4533        final int count = mChildrenCount;
4534        final View[] children = mChildren;
4535        for (int i = 0; i < count; i++) {
4536            if (children[i] == child) {
4537                return i;
4538            }
4539        }
4540        return -1;
4541    }
4542
4543    /**
4544     * Returns the number of children in the group.
4545     *
4546     * @return a positive integer representing the number of children in
4547     *         the group
4548     */
4549    public int getChildCount() {
4550        return mChildrenCount;
4551    }
4552
4553    /**
4554     * Returns the view at the specified position in the group.
4555     *
4556     * @param index the position at which to get the view from
4557     * @return the view at the specified position or null if the position
4558     *         does not exist within the group
4559     */
4560    public View getChildAt(int index) {
4561        if (index < 0 || index >= mChildrenCount) {
4562            return null;
4563        }
4564        return mChildren[index];
4565    }
4566
4567    /**
4568     * Ask all of the children of this view to measure themselves, taking into
4569     * account both the MeasureSpec requirements for this view and its padding.
4570     * We skip children that are in the GONE state The heavy lifting is done in
4571     * getChildMeasureSpec.
4572     *
4573     * @param widthMeasureSpec The width requirements for this view
4574     * @param heightMeasureSpec The height requirements for this view
4575     */
4576    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
4577        final int size = mChildrenCount;
4578        final View[] children = mChildren;
4579        for (int i = 0; i < size; ++i) {
4580            final View child = children[i];
4581            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
4582                measureChild(child, widthMeasureSpec, heightMeasureSpec);
4583            }
4584        }
4585    }
4586
4587    /**
4588     * Ask one of the children of this view to measure itself, taking into
4589     * account both the MeasureSpec requirements for this view and its padding.
4590     * The heavy lifting is done in getChildMeasureSpec.
4591     *
4592     * @param child The child to measure
4593     * @param parentWidthMeasureSpec The width requirements for this view
4594     * @param parentHeightMeasureSpec The height requirements for this view
4595     */
4596    protected void measureChild(View child, int parentWidthMeasureSpec,
4597            int parentHeightMeasureSpec) {
4598        final LayoutParams lp = child.getLayoutParams();
4599
4600        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4601                mPaddingLeft + mPaddingRight, lp.width);
4602        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4603                mPaddingTop + mPaddingBottom, lp.height);
4604
4605        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4606    }
4607
4608    /**
4609     * Ask one of the children of this view to measure itself, taking into
4610     * account both the MeasureSpec requirements for this view and its padding
4611     * and margins. The child must have MarginLayoutParams The heavy lifting is
4612     * done in getChildMeasureSpec.
4613     *
4614     * @param child The child to measure
4615     * @param parentWidthMeasureSpec The width requirements for this view
4616     * @param widthUsed Extra space that has been used up by the parent
4617     *        horizontally (possibly by other children of the parent)
4618     * @param parentHeightMeasureSpec The height requirements for this view
4619     * @param heightUsed Extra space that has been used up by the parent
4620     *        vertically (possibly by other children of the parent)
4621     */
4622    protected void measureChildWithMargins(View child,
4623            int parentWidthMeasureSpec, int widthUsed,
4624            int parentHeightMeasureSpec, int heightUsed) {
4625        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
4626
4627        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4628                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
4629                        + widthUsed, lp.width);
4630        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4631                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
4632                        + heightUsed, lp.height);
4633
4634        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4635    }
4636
4637    /**
4638     * Does the hard part of measureChildren: figuring out the MeasureSpec to
4639     * pass to a particular child. This method figures out the right MeasureSpec
4640     * for one dimension (height or width) of one child view.
4641     *
4642     * The goal is to combine information from our MeasureSpec with the
4643     * LayoutParams of the child to get the best possible results. For example,
4644     * if the this view knows its size (because its MeasureSpec has a mode of
4645     * EXACTLY), and the child has indicated in its LayoutParams that it wants
4646     * to be the same size as the parent, the parent should ask the child to
4647     * layout given an exact size.
4648     *
4649     * @param spec The requirements for this view
4650     * @param padding The padding of this view for the current dimension and
4651     *        margins, if applicable
4652     * @param childDimension How big the child wants to be in the current
4653     *        dimension
4654     * @return a MeasureSpec integer for the child
4655     */
4656    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
4657        int specMode = MeasureSpec.getMode(spec);
4658        int specSize = MeasureSpec.getSize(spec);
4659
4660        int size = Math.max(0, specSize - padding);
4661
4662        int resultSize = 0;
4663        int resultMode = 0;
4664
4665        switch (specMode) {
4666        // Parent has imposed an exact size on us
4667        case MeasureSpec.EXACTLY:
4668            if (childDimension >= 0) {
4669                resultSize = childDimension;
4670                resultMode = MeasureSpec.EXACTLY;
4671            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4672                // Child wants to be our size. So be it.
4673                resultSize = size;
4674                resultMode = MeasureSpec.EXACTLY;
4675            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4676                // Child wants to determine its own size. It can't be
4677                // bigger than us.
4678                resultSize = size;
4679                resultMode = MeasureSpec.AT_MOST;
4680            }
4681            break;
4682
4683        // Parent has imposed a maximum size on us
4684        case MeasureSpec.AT_MOST:
4685            if (childDimension >= 0) {
4686                // Child wants a specific size... so be it
4687                resultSize = childDimension;
4688                resultMode = MeasureSpec.EXACTLY;
4689            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4690                // Child wants to be our size, but our size is not fixed.
4691                // Constrain child to not be bigger than us.
4692                resultSize = size;
4693                resultMode = MeasureSpec.AT_MOST;
4694            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4695                // Child wants to determine its own size. It can't be
4696                // bigger than us.
4697                resultSize = size;
4698                resultMode = MeasureSpec.AT_MOST;
4699            }
4700            break;
4701
4702        // Parent asked to see how big we want to be
4703        case MeasureSpec.UNSPECIFIED:
4704            if (childDimension >= 0) {
4705                // Child wants a specific size... let him have it
4706                resultSize = childDimension;
4707                resultMode = MeasureSpec.EXACTLY;
4708            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4709                // Child wants to be our size... find out how big it should
4710                // be
4711                resultSize = 0;
4712                resultMode = MeasureSpec.UNSPECIFIED;
4713            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4714                // Child wants to determine its own size.... find out how
4715                // big it should be
4716                resultSize = 0;
4717                resultMode = MeasureSpec.UNSPECIFIED;
4718            }
4719            break;
4720        }
4721        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
4722    }
4723
4724
4725    /**
4726     * Removes any pending animations for views that have been removed. Call
4727     * this if you don't want animations for exiting views to stack up.
4728     */
4729    public void clearDisappearingChildren() {
4730        if (mDisappearingChildren != null) {
4731            mDisappearingChildren.clear();
4732        }
4733    }
4734
4735    /**
4736     * Add a view which is removed from mChildren but still needs animation
4737     *
4738     * @param v View to add
4739     */
4740    private void addDisappearingView(View v) {
4741        ArrayList<View> disappearingChildren = mDisappearingChildren;
4742
4743        if (disappearingChildren == null) {
4744            disappearingChildren = mDisappearingChildren = new ArrayList<View>();
4745        }
4746
4747        disappearingChildren.add(v);
4748    }
4749
4750    /**
4751     * Cleanup a view when its animation is done. This may mean removing it from
4752     * the list of disappearing views.
4753     *
4754     * @param view The view whose animation has finished
4755     * @param animation The animation, cannot be null
4756     */
4757    private void finishAnimatingView(final View view, Animation animation) {
4758        final ArrayList<View> disappearingChildren = mDisappearingChildren;
4759        if (disappearingChildren != null) {
4760            if (disappearingChildren.contains(view)) {
4761                disappearingChildren.remove(view);
4762
4763                if (view.mAttachInfo != null) {
4764                    view.dispatchDetachedFromWindow();
4765                }
4766
4767                view.clearAnimation();
4768                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
4769            }
4770        }
4771
4772        if (animation != null && !animation.getFillAfter()) {
4773            view.clearAnimation();
4774        }
4775
4776        if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) {
4777            view.onAnimationEnd();
4778            // Should be performed by onAnimationEnd() but this avoid an infinite loop,
4779            // so we'd rather be safe than sorry
4780            view.mPrivateFlags &= ~ANIMATION_STARTED;
4781            // Draw one more frame after the animation is done
4782            mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
4783        }
4784    }
4785
4786    /**
4787     * Utility function called by View during invalidation to determine whether a view that
4788     * is invisible or gone should still be invalidated because it is being transitioned (and
4789     * therefore still needs to be drawn).
4790     */
4791    boolean isViewTransitioning(View view) {
4792        return (mTransitioningViews != null && mTransitioningViews.contains(view));
4793    }
4794
4795    /**
4796     * This method tells the ViewGroup that the given View object, which should have this
4797     * ViewGroup as its parent,
4798     * should be kept around  (re-displayed when the ViewGroup draws its children) even if it
4799     * is removed from its parent. This allows animations, such as those used by
4800     * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate
4801     * the removal of views. A call to this method should always be accompanied by a later call
4802     * to {@link #endViewTransition(View)}, such as after an animation on the View has finished,
4803     * so that the View finally gets removed.
4804     *
4805     * @param view The View object to be kept visible even if it gets removed from its parent.
4806     */
4807    public void startViewTransition(View view) {
4808        if (view.mParent == this) {
4809            if (mTransitioningViews == null) {
4810                mTransitioningViews = new ArrayList<View>();
4811            }
4812            mTransitioningViews.add(view);
4813        }
4814    }
4815
4816    /**
4817     * This method should always be called following an earlier call to
4818     * {@link #startViewTransition(View)}. The given View is finally removed from its parent
4819     * and will no longer be displayed. Note that this method does not perform the functionality
4820     * of removing a view from its parent; it just discontinues the display of a View that
4821     * has previously been removed.
4822     *
4823     * @return view The View object that has been removed but is being kept around in the visible
4824     * hierarchy by an earlier call to {@link #startViewTransition(View)}.
4825     */
4826    public void endViewTransition(View view) {
4827        if (mTransitioningViews != null) {
4828            mTransitioningViews.remove(view);
4829            final ArrayList<View> disappearingChildren = mDisappearingChildren;
4830            if (disappearingChildren != null && disappearingChildren.contains(view)) {
4831                disappearingChildren.remove(view);
4832                if (mVisibilityChangingChildren != null &&
4833                        mVisibilityChangingChildren.contains(view)) {
4834                    mVisibilityChangingChildren.remove(view);
4835                } else {
4836                    if (view.mAttachInfo != null) {
4837                        view.dispatchDetachedFromWindow();
4838                    }
4839                    if (view.mParent != null) {
4840                        view.mParent = null;
4841                    }
4842                }
4843                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
4844            }
4845        }
4846    }
4847
4848    private LayoutTransition.TransitionListener mLayoutTransitionListener =
4849            new LayoutTransition.TransitionListener() {
4850        @Override
4851        public void startTransition(LayoutTransition transition, ViewGroup container,
4852                View view, int transitionType) {
4853            // We only care about disappearing items, since we need special logic to keep
4854            // those items visible after they've been 'removed'
4855            if (transitionType == LayoutTransition.DISAPPEARING) {
4856                startViewTransition(view);
4857            }
4858        }
4859
4860        @Override
4861        public void endTransition(LayoutTransition transition, ViewGroup container,
4862                View view, int transitionType) {
4863            if (mLayoutSuppressed && !transition.isChangingLayout()) {
4864                requestLayout();
4865                mLayoutSuppressed = false;
4866            }
4867            if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
4868                endViewTransition(view);
4869            }
4870        }
4871    };
4872
4873    /**
4874     * {@inheritDoc}
4875     */
4876    @Override
4877    public boolean gatherTransparentRegion(Region region) {
4878        // If no transparent regions requested, we are always opaque.
4879        final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0;
4880        if (meOpaque && region == null) {
4881            // The caller doesn't care about the region, so stop now.
4882            return true;
4883        }
4884        super.gatherTransparentRegion(region);
4885        final View[] children = mChildren;
4886        final int count = mChildrenCount;
4887        boolean noneOfTheChildrenAreTransparent = true;
4888        for (int i = 0; i < count; i++) {
4889            final View child = children[i];
4890            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
4891                if (!child.gatherTransparentRegion(region)) {
4892                    noneOfTheChildrenAreTransparent = false;
4893                }
4894            }
4895        }
4896        return meOpaque || noneOfTheChildrenAreTransparent;
4897    }
4898
4899    /**
4900     * {@inheritDoc}
4901     */
4902    public void requestTransparentRegion(View child) {
4903        if (child != null) {
4904            child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
4905            if (mParent != null) {
4906                mParent.requestTransparentRegion(this);
4907            }
4908        }
4909    }
4910
4911
4912    @Override
4913    protected boolean fitSystemWindows(Rect insets) {
4914        boolean done = super.fitSystemWindows(insets);
4915        if (!done) {
4916            final int count = mChildrenCount;
4917            final View[] children = mChildren;
4918            for (int i = 0; i < count; i++) {
4919                done = children[i].fitSystemWindows(insets);
4920                if (done) {
4921                    break;
4922                }
4923            }
4924        }
4925        return done;
4926    }
4927
4928    /**
4929     * Returns the animation listener to which layout animation events are
4930     * sent.
4931     *
4932     * @return an {@link android.view.animation.Animation.AnimationListener}
4933     */
4934    public Animation.AnimationListener getLayoutAnimationListener() {
4935        return mAnimationListener;
4936    }
4937
4938    @Override
4939    protected void drawableStateChanged() {
4940        super.drawableStateChanged();
4941
4942        if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
4943            if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
4944                throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
4945                        + " child has duplicateParentState set to true");
4946            }
4947
4948            final View[] children = mChildren;
4949            final int count = mChildrenCount;
4950
4951            for (int i = 0; i < count; i++) {
4952                final View child = children[i];
4953                if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
4954                    child.refreshDrawableState();
4955                }
4956            }
4957        }
4958    }
4959
4960    @Override
4961    public void jumpDrawablesToCurrentState() {
4962        super.jumpDrawablesToCurrentState();
4963        final View[] children = mChildren;
4964        final int count = mChildrenCount;
4965        for (int i = 0; i < count; i++) {
4966            children[i].jumpDrawablesToCurrentState();
4967        }
4968    }
4969
4970    @Override
4971    protected int[] onCreateDrawableState(int extraSpace) {
4972        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) {
4973            return super.onCreateDrawableState(extraSpace);
4974        }
4975
4976        int need = 0;
4977        int n = getChildCount();
4978        for (int i = 0; i < n; i++) {
4979            int[] childState = getChildAt(i).getDrawableState();
4980
4981            if (childState != null) {
4982                need += childState.length;
4983            }
4984        }
4985
4986        int[] state = super.onCreateDrawableState(extraSpace + need);
4987
4988        for (int i = 0; i < n; i++) {
4989            int[] childState = getChildAt(i).getDrawableState();
4990
4991            if (childState != null) {
4992                state = mergeDrawableStates(state, childState);
4993            }
4994        }
4995
4996        return state;
4997    }
4998
4999    /**
5000     * Sets whether this ViewGroup's drawable states also include
5001     * its children's drawable states.  This is used, for example, to
5002     * make a group appear to be focused when its child EditText or button
5003     * is focused.
5004     */
5005    public void setAddStatesFromChildren(boolean addsStates) {
5006        if (addsStates) {
5007            mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN;
5008        } else {
5009            mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN;
5010        }
5011
5012        refreshDrawableState();
5013    }
5014
5015    /**
5016     * Returns whether this ViewGroup's drawable states also include
5017     * its children's drawable states.  This is used, for example, to
5018     * make a group appear to be focused when its child EditText or button
5019     * is focused.
5020     */
5021    public boolean addStatesFromChildren() {
5022        return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0;
5023    }
5024
5025    /**
5026     * If {link #addStatesFromChildren} is true, refreshes this group's
5027     * drawable state (to include the states from its children).
5028     */
5029    public void childDrawableStateChanged(View child) {
5030        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5031            refreshDrawableState();
5032        }
5033    }
5034
5035    /**
5036     * Specifies the animation listener to which layout animation events must
5037     * be sent. Only
5038     * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)}
5039     * and
5040     * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)}
5041     * are invoked.
5042     *
5043     * @param animationListener the layout animation listener
5044     */
5045    public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
5046        mAnimationListener = animationListener;
5047    }
5048
5049    /**
5050     * This method is called by LayoutTransition when there are 'changing' animations that need
5051     * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who
5052     * starts all pending transitions prior to the drawing phase in the current traversal.
5053     *
5054     * @param transition The LayoutTransition to be started on the next traversal.
5055     *
5056     * @hide
5057     */
5058    public void requestTransitionStart(LayoutTransition transition) {
5059        ViewRootImpl viewAncestor = getViewRootImpl();
5060        if (viewAncestor != null) {
5061            viewAncestor.requestTransitionStart(transition);
5062        }
5063    }
5064
5065    @Override
5066    protected void resetResolvedLayoutDirection() {
5067        super.resetResolvedLayoutDirection();
5068
5069        // Take care of resetting the children resolution too
5070        final int count = getChildCount();
5071        for (int i = 0; i < count; i++) {
5072            final View child = getChildAt(i);
5073            if (child.getLayoutDirection() == LAYOUT_DIRECTION_INHERIT) {
5074                child.resetResolvedLayoutDirection();
5075            }
5076        }
5077    }
5078
5079    @Override
5080    protected void resetResolvedTextDirection() {
5081        super.resetResolvedTextDirection();
5082
5083        // Take care of resetting the children resolution too
5084        final int count = getChildCount();
5085        for (int i = 0; i < count; i++) {
5086            final View child = getChildAt(i);
5087            if (child.getTextDirection() == TEXT_DIRECTION_INHERIT) {
5088                child.resetResolvedTextDirection();
5089            }
5090        }
5091    }
5092
5093    /**
5094     * Return true if the pressed state should be delayed for children or descendants of this
5095     * ViewGroup. Generally, this should be done for containers that can scroll, such as a List.
5096     * This prevents the pressed state from appearing when the user is actually trying to scroll
5097     * the content.
5098     *
5099     * The default implementation returns true for compatibility reasons. Subclasses that do
5100     * not scroll should generally override this method and return false.
5101     */
5102    public boolean shouldDelayChildPressedState() {
5103        return true;
5104    }
5105
5106    /**
5107     * LayoutParams are used by views to tell their parents how they want to be
5108     * laid out. See
5109     * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes}
5110     * for a list of all child view attributes that this class supports.
5111     *
5112     * <p>
5113     * The base LayoutParams class just describes how big the view wants to be
5114     * for both width and height. For each dimension, it can specify one of:
5115     * <ul>
5116     * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
5117     * means that the view wants to be as big as its parent (minus padding)
5118     * <li> WRAP_CONTENT, which means that the view wants to be just big enough
5119     * to enclose its content (plus padding)
5120     * <li> an exact number
5121     * </ul>
5122     * There are subclasses of LayoutParams for different subclasses of
5123     * ViewGroup. For example, AbsoluteLayout has its own subclass of
5124     * LayoutParams which adds an X and Y value.
5125     *
5126     * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
5127     * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
5128     */
5129    public static class LayoutParams {
5130        /**
5131         * Special value for the height or width requested by a View.
5132         * FILL_PARENT means that the view wants to be as big as its parent,
5133         * minus the parent's padding, if any. This value is deprecated
5134         * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
5135         */
5136        @SuppressWarnings({"UnusedDeclaration"})
5137        @Deprecated
5138        public static final int FILL_PARENT = -1;
5139
5140        /**
5141         * Special value for the height or width requested by a View.
5142         * MATCH_PARENT means that the view wants to be as big as its parent,
5143         * minus the parent's padding, if any. Introduced in API Level 8.
5144         */
5145        public static final int MATCH_PARENT = -1;
5146
5147        /**
5148         * Special value for the height or width requested by a View.
5149         * WRAP_CONTENT means that the view wants to be just large enough to fit
5150         * its own internal content, taking its own padding into account.
5151         */
5152        public static final int WRAP_CONTENT = -2;
5153
5154        /**
5155         * Information about how wide the view wants to be. Can be one of the
5156         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5157         * in API Level 8) or WRAP_CONTENT. or an exact size.
5158         */
5159        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5160            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5161            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5162        })
5163        public int width;
5164
5165        /**
5166         * Information about how tall the view wants to be. Can be one of the
5167         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5168         * in API Level 8) or WRAP_CONTENT. or an exact size.
5169         */
5170        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5171            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5172            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5173        })
5174        public int height;
5175
5176        /**
5177         * Used to animate layouts.
5178         */
5179        public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
5180
5181        /**
5182         * Creates a new set of layout parameters. The values are extracted from
5183         * the supplied attributes set and context. The XML attributes mapped
5184         * to this set of layout parameters are:
5185         *
5186         * <ul>
5187         *   <li><code>layout_width</code>: the width, either an exact value,
5188         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5189         *   {@link #MATCH_PARENT} in API Level 8)</li>
5190         *   <li><code>layout_height</code>: the height, either an exact value,
5191         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5192         *   {@link #MATCH_PARENT} in API Level 8)</li>
5193         * </ul>
5194         *
5195         * @param c the application environment
5196         * @param attrs the set of attributes from which to extract the layout
5197         *              parameters' values
5198         */
5199        public LayoutParams(Context c, AttributeSet attrs) {
5200            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
5201            setBaseAttributes(a,
5202                    R.styleable.ViewGroup_Layout_layout_width,
5203                    R.styleable.ViewGroup_Layout_layout_height);
5204            a.recycle();
5205        }
5206
5207        /**
5208         * Creates a new set of layout parameters with the specified width
5209         * and height.
5210         *
5211         * @param width the width, either {@link #WRAP_CONTENT},
5212         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5213         *        API Level 8), or a fixed size in pixels
5214         * @param height the height, either {@link #WRAP_CONTENT},
5215         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5216         *        API Level 8), or a fixed size in pixels
5217         */
5218        public LayoutParams(int width, int height) {
5219            this.width = width;
5220            this.height = height;
5221        }
5222
5223        /**
5224         * Copy constructor. Clones the width and height values of the source.
5225         *
5226         * @param source The layout params to copy from.
5227         */
5228        public LayoutParams(LayoutParams source) {
5229            this.width = source.width;
5230            this.height = source.height;
5231        }
5232
5233        /**
5234         * Used internally by MarginLayoutParams.
5235         * @hide
5236         */
5237        LayoutParams() {
5238        }
5239
5240        /**
5241         * Extracts the layout parameters from the supplied attributes.
5242         *
5243         * @param a the style attributes to extract the parameters from
5244         * @param widthAttr the identifier of the width attribute
5245         * @param heightAttr the identifier of the height attribute
5246         */
5247        protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
5248            width = a.getLayoutDimension(widthAttr, "layout_width");
5249            height = a.getLayoutDimension(heightAttr, "layout_height");
5250        }
5251
5252        /**
5253         * Resolve layout parameters depending on the layout direction. Subclasses that care about
5254         * layoutDirection changes should override this method. The default implementation does
5255         * nothing.
5256         *
5257         * @param layoutDirection the direction of the layout
5258         *
5259         * {@link View#LAYOUT_DIRECTION_LTR}
5260         * {@link View#LAYOUT_DIRECTION_RTL}
5261         *
5262         * @hide
5263         */
5264        protected void resolveWithDirection(int layoutDirection) {
5265        }
5266
5267        /**
5268         * Returns a String representation of this set of layout parameters.
5269         *
5270         * @param output the String to prepend to the internal representation
5271         * @return a String with the following format: output +
5272         *         "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }"
5273         *
5274         * @hide
5275         */
5276        public String debug(String output) {
5277            return output + "ViewGroup.LayoutParams={ width="
5278                    + sizeToString(width) + ", height=" + sizeToString(height) + " }";
5279        }
5280
5281        /**
5282         * Converts the specified size to a readable String.
5283         *
5284         * @param size the size to convert
5285         * @return a String instance representing the supplied size
5286         *
5287         * @hide
5288         */
5289        protected static String sizeToString(int size) {
5290            if (size == WRAP_CONTENT) {
5291                return "wrap-content";
5292            }
5293            if (size == MATCH_PARENT) {
5294                return "match-parent";
5295            }
5296            return String.valueOf(size);
5297        }
5298    }
5299
5300    /**
5301     * Per-child layout information for layouts that support margins.
5302     * See
5303     * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes}
5304     * for a list of all child view attributes that this class supports.
5305     */
5306    public static class MarginLayoutParams extends ViewGroup.LayoutParams {
5307        /**
5308         * The left margin in pixels of the child. Whenever this value is changed, a call to
5309         * {@link android.view.View#requestLayout()} needs to be done.
5310         */
5311        @ViewDebug.ExportedProperty(category = "layout")
5312        public int leftMargin;
5313
5314        /**
5315         * The top 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 topMargin;
5320
5321        /**
5322         * The right 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 rightMargin;
5327
5328        /**
5329         * The bottom 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 bottomMargin;
5334
5335        /**
5336         * The start margin in pixels of the child.
5337         *
5338         * @hide
5339         *
5340         */
5341        @ViewDebug.ExportedProperty(category = "layout")
5342        protected int startMargin = DEFAULT_RELATIVE;
5343
5344        /**
5345         * The end margin in pixels of the child.
5346         *
5347         * @hide
5348         */
5349        @ViewDebug.ExportedProperty(category = "layout")
5350        protected int endMargin = DEFAULT_RELATIVE;
5351
5352        /**
5353         * The default start and end margin.
5354         */
5355        static private final int DEFAULT_RELATIVE = Integer.MIN_VALUE;
5356
5357        /**
5358         * Creates a new set of layout parameters. The values are extracted from
5359         * the supplied attributes set and context.
5360         *
5361         * @param c the application environment
5362         * @param attrs the set of attributes from which to extract the layout
5363         *              parameters' values
5364         */
5365        public MarginLayoutParams(Context c, AttributeSet attrs) {
5366            super();
5367
5368            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
5369            setBaseAttributes(a,
5370                    R.styleable.ViewGroup_MarginLayout_layout_width,
5371                    R.styleable.ViewGroup_MarginLayout_layout_height);
5372
5373            int margin = a.getDimensionPixelSize(
5374                    com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
5375            if (margin >= 0) {
5376                leftMargin = margin;
5377                topMargin = margin;
5378                rightMargin= margin;
5379                bottomMargin = margin;
5380            } else {
5381                leftMargin = a.getDimensionPixelSize(
5382                        R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0);
5383                topMargin = a.getDimensionPixelSize(
5384                        R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0);
5385                rightMargin = a.getDimensionPixelSize(
5386                        R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0);
5387                bottomMargin = a.getDimensionPixelSize(
5388                        R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0);
5389                startMargin = a.getDimensionPixelSize(
5390                        R.styleable.ViewGroup_MarginLayout_layout_marginStart, DEFAULT_RELATIVE);
5391                endMargin = a.getDimensionPixelSize(
5392                        R.styleable.ViewGroup_MarginLayout_layout_marginEnd, DEFAULT_RELATIVE);
5393            }
5394
5395            a.recycle();
5396        }
5397
5398        /**
5399         * {@inheritDoc}
5400         */
5401        public MarginLayoutParams(int width, int height) {
5402            super(width, height);
5403        }
5404
5405        /**
5406         * Copy constructor. Clones the width, height and margin values of the source.
5407         *
5408         * @param source The layout params to copy from.
5409         */
5410        public MarginLayoutParams(MarginLayoutParams source) {
5411            this.width = source.width;
5412            this.height = source.height;
5413
5414            this.leftMargin = source.leftMargin;
5415            this.topMargin = source.topMargin;
5416            this.rightMargin = source.rightMargin;
5417            this.bottomMargin = source.bottomMargin;
5418            this.startMargin = source.startMargin;
5419            this.endMargin = source.endMargin;
5420        }
5421
5422        /**
5423         * {@inheritDoc}
5424         */
5425        public MarginLayoutParams(LayoutParams source) {
5426            super(source);
5427        }
5428
5429        /**
5430         * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs
5431         * to be done so that the new margins are taken into account. Left and right margins may be
5432         * overriden by {@link android.view.View#requestLayout()} depending on layout direction.
5433         *
5434         * @param left the left margin size
5435         * @param top the top margin size
5436         * @param right the right margin size
5437         * @param bottom the bottom margin size
5438         *
5439         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
5440         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5441         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
5442         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5443         */
5444        public void setMargins(int left, int top, int right, int bottom) {
5445            leftMargin = left;
5446            topMargin = top;
5447            rightMargin = right;
5448            bottomMargin = bottom;
5449        }
5450
5451        /**
5452         * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()}
5453         * needs to be done so that the new relative margins are taken into account. Left and right
5454         * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout
5455         * direction.
5456         *
5457         * @param start the start margin size
5458         * @param top the top margin size
5459         * @param end the right margin size
5460         * @param bottom the bottom margin size
5461         *
5462         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5463         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5464         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5465         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5466         *
5467         * @hide
5468         */
5469        public void setMarginsRelative(int start, int top, int end, int bottom) {
5470            startMargin = start;
5471            topMargin = top;
5472            endMargin = end;
5473            bottomMargin = bottom;
5474        }
5475
5476        /**
5477         * Returns the start margin in pixels.
5478         *
5479         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5480         *
5481         * @return the start margin in pixels.
5482         *
5483         * @hide
5484         */
5485        public int getMarginStart() {
5486            return startMargin;
5487        }
5488
5489        /**
5490         * Returns the end margin in pixels.
5491         *
5492         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5493         *
5494         * @return the end margin in pixels.
5495         *
5496         * @hide
5497         */
5498        public int getMarginEnd() {
5499            return endMargin;
5500        }
5501
5502        /**
5503         * Check if margins are relative.
5504         *
5505         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5506         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5507         *
5508         * @return true if either marginStart or marginEnd has been set
5509         *
5510         * @hide
5511         */
5512        public boolean isMarginRelative() {
5513            return (startMargin != DEFAULT_RELATIVE) || (endMargin != DEFAULT_RELATIVE);
5514        }
5515
5516        /**
5517         * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins
5518         * maybe overriden depending on layout direction.
5519         *
5520         * @hide
5521         */
5522        @Override
5523        protected void resolveWithDirection(int layoutDirection) {
5524            switch(layoutDirection) {
5525                case View.LAYOUT_DIRECTION_RTL:
5526                    leftMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : leftMargin;
5527                    rightMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : rightMargin;
5528                    break;
5529                case View.LAYOUT_DIRECTION_LTR:
5530                default:
5531                    leftMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : leftMargin;
5532                    rightMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : rightMargin;
5533                    break;
5534            }
5535        }
5536    }
5537
5538    /* Describes a touched view and the ids of the pointers that it has captured.
5539     *
5540     * This code assumes that pointer ids are always in the range 0..31 such that
5541     * it can use a bitfield to track which pointer ids are present.
5542     * As it happens, the lower layers of the input dispatch pipeline also use the
5543     * same trick so the assumption should be safe here...
5544     */
5545    private static final class TouchTarget {
5546        private static final int MAX_RECYCLED = 32;
5547        private static final Object sRecycleLock = new Object();
5548        private static TouchTarget sRecycleBin;
5549        private static int sRecycledCount;
5550
5551        public static final int ALL_POINTER_IDS = -1; // all ones
5552
5553        // The touched child view.
5554        public View child;
5555
5556        // The combined bit mask of pointer ids for all pointers captured by the target.
5557        public int pointerIdBits;
5558
5559        // The next target in the target list.
5560        public TouchTarget next;
5561
5562        private TouchTarget() {
5563        }
5564
5565        public static TouchTarget obtain(View child, int pointerIdBits) {
5566            final TouchTarget target;
5567            synchronized (sRecycleLock) {
5568                if (sRecycleBin == null) {
5569                    target = new TouchTarget();
5570                } else {
5571                    target = sRecycleBin;
5572                    sRecycleBin = target.next;
5573                     sRecycledCount--;
5574                    target.next = null;
5575                }
5576            }
5577            target.child = child;
5578            target.pointerIdBits = pointerIdBits;
5579            return target;
5580        }
5581
5582        public void recycle() {
5583            synchronized (sRecycleLock) {
5584                if (sRecycledCount < MAX_RECYCLED) {
5585                    next = sRecycleBin;
5586                    sRecycleBin = this;
5587                    sRecycledCount += 1;
5588                } else {
5589                    next = null;
5590                }
5591                child = null;
5592            }
5593        }
5594    }
5595
5596    /* Describes a hovered view. */
5597    private static final class HoverTarget {
5598        private static final int MAX_RECYCLED = 32;
5599        private static final Object sRecycleLock = new Object();
5600        private static HoverTarget sRecycleBin;
5601        private static int sRecycledCount;
5602
5603        // The hovered child view.
5604        public View child;
5605
5606        // The next target in the target list.
5607        public HoverTarget next;
5608
5609        private HoverTarget() {
5610        }
5611
5612        public static HoverTarget obtain(View child) {
5613            final HoverTarget target;
5614            synchronized (sRecycleLock) {
5615                if (sRecycleBin == null) {
5616                    target = new HoverTarget();
5617                } else {
5618                    target = sRecycleBin;
5619                    sRecycleBin = target.next;
5620                     sRecycledCount--;
5621                    target.next = null;
5622                }
5623            }
5624            target.child = child;
5625            return target;
5626        }
5627
5628        public void recycle() {
5629            synchronized (sRecycleLock) {
5630                if (sRecycledCount < MAX_RECYCLED) {
5631                    next = sRecycleBin;
5632                    sRecycleBin = this;
5633                    sRecycledCount += 1;
5634                } else {
5635                    next = null;
5636                }
5637                child = null;
5638            }
5639        }
5640    }
5641}
5642