ViewGroup.java revision f37df070ea84c353ff8bed4b2591932126d7e2ca
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 com.android.internal.R;
21
22import android.content.Context;
23import android.content.res.Configuration;
24import android.content.res.TypedArray;
25import android.graphics.Bitmap;
26import android.graphics.Canvas;
27import android.graphics.Matrix;
28import android.graphics.Paint;
29import android.graphics.Rect;
30import android.graphics.RectF;
31import android.graphics.Region;
32import android.os.Parcelable;
33import android.os.SystemClock;
34import android.util.AttributeSet;
35import android.util.Log;
36import android.util.SparseArray;
37import android.view.accessibility.AccessibilityEvent;
38import android.view.animation.Animation;
39import android.view.animation.AnimationUtils;
40import android.view.animation.LayoutAnimationController;
41import android.view.animation.Transformation;
42
43import java.util.ArrayList;
44
45/**
46 * <p>
47 * A <code>ViewGroup</code> is a special view that can contain other views
48 * (called children.) The view group is the base class for layouts and views
49 * containers. This class also defines the
50 * {@link android.view.ViewGroup.LayoutParams} class which serves as the base
51 * class for layouts parameters.
52 * </p>
53 *
54 * <p>
55 * Also see {@link LayoutParams} for layout attributes.
56 * </p>
57 *
58 * @attr ref android.R.styleable#ViewGroup_clipChildren
59 * @attr ref android.R.styleable#ViewGroup_clipToPadding
60 * @attr ref android.R.styleable#ViewGroup_layoutAnimation
61 * @attr ref android.R.styleable#ViewGroup_animationCache
62 * @attr ref android.R.styleable#ViewGroup_persistentDrawingCache
63 * @attr ref android.R.styleable#ViewGroup_alwaysDrawnWithCache
64 * @attr ref android.R.styleable#ViewGroup_addStatesFromChildren
65 * @attr ref android.R.styleable#ViewGroup_descendantFocusability
66 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
67 */
68public abstract class ViewGroup extends View implements ViewParent, ViewManager {
69
70    private static final boolean DBG = false;
71
72    /**
73     * Views which have been hidden or removed which need to be animated on
74     * their way out.
75     * This field should be made private, so it is hidden from the SDK.
76     * {@hide}
77     */
78    protected ArrayList<View> mDisappearingChildren;
79
80    /**
81     * Listener used to propagate events indicating when children are added
82     * and/or removed from a view group.
83     * This field should be made private, so it is hidden from the SDK.
84     * {@hide}
85     */
86    protected OnHierarchyChangeListener mOnHierarchyChangeListener;
87
88    // The view contained within this ViewGroup that has or contains focus.
89    private View mFocused;
90
91    /**
92     * A Transformation used when drawing children, to
93     * apply on the child being drawn.
94     */
95    private final Transformation mChildTransformation = new Transformation();
96
97    /**
98     * Used to track the current invalidation region.
99     */
100    private RectF mInvalidateRegion;
101
102    /**
103     * A Transformation used to calculate a correct
104     * invalidation area when the application is autoscaled.
105     */
106    private Transformation mInvalidationTransformation;
107
108    // Target of Motion events
109    private View mMotionTarget;
110
111    // Targets of MotionEvents in split mode
112    private SplitMotionTargets mSplitMotionTargets;
113
114    // Layout animation
115    private LayoutAnimationController mLayoutAnimationController;
116    private Animation.AnimationListener mAnimationListener;
117
118    /**
119     * Internal flags.
120     *
121     * This field should be made private, so it is hidden from the SDK.
122     * {@hide}
123     */
124    protected int mGroupFlags;
125
126    // When set, ViewGroup invalidates only the child's rectangle
127    // Set by default
128    private static final int FLAG_CLIP_CHILDREN = 0x1;
129
130    // When set, ViewGroup excludes the padding area from the invalidate rectangle
131    // Set by default
132    private static final int FLAG_CLIP_TO_PADDING = 0x2;
133
134    // When set, dispatchDraw() will invoke invalidate(); this is set by drawChild() when
135    // a child needs to be invalidated and FLAG_OPTIMIZE_INVALIDATE is set
136    private static final int FLAG_INVALIDATE_REQUIRED  = 0x4;
137
138    // When set, dispatchDraw() will run the layout animation and unset the flag
139    private static final int FLAG_RUN_ANIMATION = 0x8;
140
141    // When set, there is either no layout animation on the ViewGroup or the layout
142    // animation is over
143    // Set by default
144    private static final int FLAG_ANIMATION_DONE = 0x10;
145
146    // If set, this ViewGroup has padding; if unset there is no padding and we don't need
147    // to clip it, even if FLAG_CLIP_TO_PADDING is set
148    private static final int FLAG_PADDING_NOT_NULL = 0x20;
149
150    // When set, this ViewGroup caches its children in a Bitmap before starting a layout animation
151    // Set by default
152    private static final int FLAG_ANIMATION_CACHE = 0x40;
153
154    // When set, this ViewGroup converts calls to invalidate(Rect) to invalidate() during a
155    // layout animation; this avoid clobbering the hierarchy
156    // Automatically set when the layout animation starts, depending on the animation's
157    // characteristics
158    private static final int FLAG_OPTIMIZE_INVALIDATE = 0x80;
159
160    // When set, the next call to drawChild() will clear mChildTransformation's matrix
161    private static final int FLAG_CLEAR_TRANSFORMATION = 0x100;
162
163    // When set, this ViewGroup invokes mAnimationListener.onAnimationEnd() and removes
164    // the children's Bitmap caches if necessary
165    // This flag is set when the layout animation is over (after FLAG_ANIMATION_DONE is set)
166    private static final int FLAG_NOTIFY_ANIMATION_LISTENER = 0x200;
167
168    /**
169     * When set, the drawing method will call {@link #getChildDrawingOrder(int, int)}
170     * to get the index of the child to draw for that iteration.
171     *
172     * @hide
173     */
174    protected static final int FLAG_USE_CHILD_DRAWING_ORDER = 0x400;
175
176    /**
177     * When set, this ViewGroup supports static transformations on children; this causes
178     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
179     * invoked when a child is drawn.
180     *
181     * Any subclass overriding
182     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
183     * set this flags in {@link #mGroupFlags}.
184     *
185     * {@hide}
186     */
187    protected static final int FLAG_SUPPORT_STATIC_TRANSFORMATIONS = 0x800;
188
189    // When the previous drawChild() invocation used an alpha value that was lower than
190    // 1.0 and set it in mCachePaint
191    private static final int FLAG_ALPHA_LOWER_THAN_ONE = 0x1000;
192
193    /**
194     * When set, this ViewGroup's drawable states also include those
195     * of its children.
196     */
197    private static final int FLAG_ADD_STATES_FROM_CHILDREN = 0x2000;
198
199    /**
200     * When set, this ViewGroup tries to always draw its children using their drawing cache.
201     */
202    private static final int FLAG_ALWAYS_DRAWN_WITH_CACHE = 0x4000;
203
204    /**
205     * When set, and if FLAG_ALWAYS_DRAWN_WITH_CACHE is not set, this ViewGroup will try to
206     * draw its children with their drawing cache.
207     */
208    private static final int FLAG_CHILDREN_DRAWN_WITH_CACHE = 0x8000;
209
210    /**
211     * When set, this group will go through its list of children to notify them of
212     * any drawable state change.
213     */
214    private static final int FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE = 0x10000;
215
216    private static final int FLAG_MASK_FOCUSABILITY = 0x60000;
217
218    /**
219     * This view will get focus before any of its descendants.
220     */
221    public static final int FOCUS_BEFORE_DESCENDANTS = 0x20000;
222
223    /**
224     * This view will get focus only if none of its descendants want it.
225     */
226    public static final int FOCUS_AFTER_DESCENDANTS = 0x40000;
227
228    /**
229     * This view will block any of its descendants from getting focus, even
230     * if they are focusable.
231     */
232    public static final int FOCUS_BLOCK_DESCENDANTS = 0x60000;
233
234    /**
235     * Used to map between enum in attrubutes and flag values.
236     */
237    private static final int[] DESCENDANT_FOCUSABILITY_FLAGS =
238            {FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS,
239                    FOCUS_BLOCK_DESCENDANTS};
240
241    /**
242     * When set, this ViewGroup should not intercept touch events.
243     * {@hide}
244     */
245    protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000;
246
247    /**
248     * When set, at least one child of this ViewGroup will return true from hasOverlay.
249     */
250    private static final int FLAG_CHILD_HAS_OVERLAY = 0x100000;
251
252    /**
253     * When set, this ViewGroup will split MotionEvents to multiple child Views when appropriate.
254     */
255    private static final int FLAG_SPLIT_MOTION_EVENTS = 0x200000;
256
257    /**
258     * Indicates which types of drawing caches are to be kept in memory.
259     * This field should be made private, so it is hidden from the SDK.
260     * {@hide}
261     */
262    protected int mPersistentDrawingCache;
263
264    /**
265     * Used to indicate that no drawing cache should be kept in memory.
266     */
267    public static final int PERSISTENT_NO_CACHE = 0x0;
268
269    /**
270     * Used to indicate that the animation drawing cache should be kept in memory.
271     */
272    public static final int PERSISTENT_ANIMATION_CACHE = 0x1;
273
274    /**
275     * Used to indicate that the scrolling drawing cache should be kept in memory.
276     */
277    public static final int PERSISTENT_SCROLLING_CACHE = 0x2;
278
279    /**
280     * Used to indicate that all drawing caches should be kept in memory.
281     */
282    public static final int PERSISTENT_ALL_CACHES = 0x3;
283
284    /**
285     * We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL
286     * are set at the same time.
287     */
288    protected static final int CLIP_TO_PADDING_MASK = FLAG_CLIP_TO_PADDING | FLAG_PADDING_NOT_NULL;
289
290    // Index of the child's left position in the mLocation array
291    private static final int CHILD_LEFT_INDEX = 0;
292    // Index of the child's top position in the mLocation array
293    private static final int CHILD_TOP_INDEX = 1;
294
295    // Child views of this ViewGroup
296    private View[] mChildren;
297    // Number of valid children in the mChildren array, the rest should be null or not
298    // considered as children
299    private int mChildrenCount;
300
301    private static final int ARRAY_INITIAL_CAPACITY = 12;
302    private static final int ARRAY_CAPACITY_INCREMENT = 12;
303
304    // Used to draw cached views
305    private final Paint mCachePaint = new Paint();
306
307    // Used to animate add/remove changes in layout
308    private LayoutTransition mTransition;
309
310    // The set of views that are currently being transitioned. This list is used to track views
311    // being removed that should not actually be removed from the parent yet because they are
312    // being animated.
313    private ArrayList<View> mTransitioningViews;
314
315    public ViewGroup(Context context) {
316        super(context);
317        initViewGroup();
318    }
319
320    public ViewGroup(Context context, AttributeSet attrs) {
321        super(context, attrs);
322        initViewGroup();
323        initFromAttributes(context, attrs);
324    }
325
326    public ViewGroup(Context context, AttributeSet attrs, int defStyle) {
327        super(context, attrs, defStyle);
328        initViewGroup();
329        initFromAttributes(context, attrs);
330    }
331
332    private void initViewGroup() {
333        // ViewGroup doesn't draw by default
334        setFlags(WILL_NOT_DRAW, DRAW_MASK);
335        mGroupFlags |= FLAG_CLIP_CHILDREN;
336        mGroupFlags |= FLAG_CLIP_TO_PADDING;
337        mGroupFlags |= FLAG_ANIMATION_DONE;
338        mGroupFlags |= FLAG_ANIMATION_CACHE;
339        mGroupFlags |= FLAG_ALWAYS_DRAWN_WITH_CACHE;
340
341        setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS);
342
343        mChildren = new View[ARRAY_INITIAL_CAPACITY];
344        mChildrenCount = 0;
345
346        mCachePaint.setDither(false);
347
348        mPersistentDrawingCache = PERSISTENT_SCROLLING_CACHE;
349    }
350
351    private void initFromAttributes(Context context, AttributeSet attrs) {
352        TypedArray a = context.obtainStyledAttributes(attrs,
353                R.styleable.ViewGroup);
354
355        final int N = a.getIndexCount();
356        for (int i = 0; i < N; i++) {
357            int attr = a.getIndex(i);
358            switch (attr) {
359                case R.styleable.ViewGroup_clipChildren:
360                    setClipChildren(a.getBoolean(attr, true));
361                    break;
362                case R.styleable.ViewGroup_clipToPadding:
363                    setClipToPadding(a.getBoolean(attr, true));
364                    break;
365                case R.styleable.ViewGroup_animationCache:
366                    setAnimationCacheEnabled(a.getBoolean(attr, true));
367                    break;
368                case R.styleable.ViewGroup_persistentDrawingCache:
369                    setPersistentDrawingCache(a.getInt(attr, PERSISTENT_SCROLLING_CACHE));
370                    break;
371                case R.styleable.ViewGroup_addStatesFromChildren:
372                    setAddStatesFromChildren(a.getBoolean(attr, false));
373                    break;
374                case R.styleable.ViewGroup_alwaysDrawnWithCache:
375                    setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true));
376                    break;
377                case R.styleable.ViewGroup_layoutAnimation:
378                    int id = a.getResourceId(attr, -1);
379                    if (id > 0) {
380                        setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id));
381                    }
382                    break;
383                case R.styleable.ViewGroup_descendantFocusability:
384                    setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]);
385                    break;
386                case R.styleable.ViewGroup_splitMotionEvents:
387                    setMotionEventSplittingEnabled(a.getBoolean(attr, false));
388                    break;
389                case R.styleable.ViewGroup_animateLayoutChanges:
390                    boolean animateLayoutChanges = a.getBoolean(attr, false);
391                    if (animateLayoutChanges) {
392                        setLayoutTransition(new LayoutTransition());
393                    }
394                    break;
395            }
396        }
397
398        a.recycle();
399    }
400
401    /**
402     * Gets the descendant focusability of this view group.  The descendant
403     * focusability defines the relationship between this view group and its
404     * descendants when looking for a view to take focus in
405     * {@link #requestFocus(int, android.graphics.Rect)}.
406     *
407     * @return one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
408     *   {@link #FOCUS_BLOCK_DESCENDANTS}.
409     */
410    @ViewDebug.ExportedProperty(category = "focus", mapping = {
411        @ViewDebug.IntToString(from = FOCUS_BEFORE_DESCENDANTS, to = "FOCUS_BEFORE_DESCENDANTS"),
412        @ViewDebug.IntToString(from = FOCUS_AFTER_DESCENDANTS, to = "FOCUS_AFTER_DESCENDANTS"),
413        @ViewDebug.IntToString(from = FOCUS_BLOCK_DESCENDANTS, to = "FOCUS_BLOCK_DESCENDANTS")
414    })
415    public int getDescendantFocusability() {
416        return mGroupFlags & FLAG_MASK_FOCUSABILITY;
417    }
418
419    /**
420     * Set the descendant focusability of this view group. This defines the relationship
421     * between this view group and its descendants when looking for a view to
422     * take focus in {@link #requestFocus(int, android.graphics.Rect)}.
423     *
424     * @param focusability one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
425     *   {@link #FOCUS_BLOCK_DESCENDANTS}.
426     */
427    public void setDescendantFocusability(int focusability) {
428        switch (focusability) {
429            case FOCUS_BEFORE_DESCENDANTS:
430            case FOCUS_AFTER_DESCENDANTS:
431            case FOCUS_BLOCK_DESCENDANTS:
432                break;
433            default:
434                throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, "
435                        + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS");
436        }
437        mGroupFlags &= ~FLAG_MASK_FOCUSABILITY;
438        mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY);
439    }
440
441    /**
442     * {@inheritDoc}
443     */
444    @Override
445    void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
446        if (mFocused != null) {
447            mFocused.unFocus();
448            mFocused = null;
449        }
450        super.handleFocusGainInternal(direction, previouslyFocusedRect);
451    }
452
453    /**
454     * {@inheritDoc}
455     */
456    public void requestChildFocus(View child, View focused) {
457        if (DBG) {
458            System.out.println(this + " requestChildFocus()");
459        }
460        if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
461            return;
462        }
463
464        // Unfocus us, if necessary
465        super.unFocus();
466
467        // We had a previous notion of who had focus. Clear it.
468        if (mFocused != child) {
469            if (mFocused != null) {
470                mFocused.unFocus();
471            }
472
473            mFocused = child;
474        }
475        if (mParent != null) {
476            mParent.requestChildFocus(this, focused);
477        }
478    }
479
480    /**
481     * {@inheritDoc}
482     */
483    public void focusableViewAvailable(View v) {
484        if (mParent != null
485                // shortcut: don't report a new focusable view if we block our descendants from
486                // getting focus
487                && (getDescendantFocusability() != FOCUS_BLOCK_DESCENDANTS)
488                // shortcut: don't report a new focusable view if we already are focused
489                // (and we don't prefer our descendants)
490                //
491                // note: knowing that mFocused is non-null is not a good enough reason
492                // to break the traversal since in that case we'd actually have to find
493                // the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and
494                // an ancestor of v; this will get checked for at ViewRoot
495                && !(isFocused() && getDescendantFocusability() != FOCUS_AFTER_DESCENDANTS)) {
496            mParent.focusableViewAvailable(v);
497        }
498    }
499
500    /**
501     * {@inheritDoc}
502     */
503    public boolean showContextMenuForChild(View originalView) {
504        return mParent != null && mParent.showContextMenuForChild(originalView);
505    }
506
507    /**
508     * {@inheritDoc}
509     */
510    public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
511        return mParent != null ? mParent.startActionModeForChild(originalView, callback) : null;
512    }
513
514    /**
515     * Find the nearest view in the specified direction that wants to take
516     * focus.
517     *
518     * @param focused The view that currently has focus
519     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and
520     *        FOCUS_RIGHT, or 0 for not applicable.
521     */
522    public View focusSearch(View focused, int direction) {
523        if (isRootNamespace()) {
524            // root namespace means we should consider ourselves the top of the
525            // tree for focus searching; otherwise we could be focus searching
526            // into other tabs.  see LocalActivityManager and TabHost for more info
527            return FocusFinder.getInstance().findNextFocus(this, focused, direction);
528        } else if (mParent != null) {
529            return mParent.focusSearch(focused, direction);
530        }
531        return null;
532    }
533
534    /**
535     * {@inheritDoc}
536     */
537    public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
538        return false;
539    }
540
541    /**
542     * {@inheritDoc}
543     */
544    @Override
545    public boolean dispatchUnhandledMove(View focused, int direction) {
546        return mFocused != null &&
547                mFocused.dispatchUnhandledMove(focused, direction);
548    }
549
550    /**
551     * {@inheritDoc}
552     */
553    public void clearChildFocus(View child) {
554        if (DBG) {
555            System.out.println(this + " clearChildFocus()");
556        }
557
558        mFocused = null;
559        if (mParent != null) {
560            mParent.clearChildFocus(this);
561        }
562    }
563
564    /**
565     * {@inheritDoc}
566     */
567    @Override
568    public void clearFocus() {
569        super.clearFocus();
570
571        // clear any child focus if it exists
572        if (mFocused != null) {
573            mFocused.clearFocus();
574        }
575    }
576
577    /**
578     * {@inheritDoc}
579     */
580    @Override
581    void unFocus() {
582        if (DBG) {
583            System.out.println(this + " unFocus()");
584        }
585
586        super.unFocus();
587        if (mFocused != null) {
588            mFocused.unFocus();
589        }
590        mFocused = null;
591    }
592
593    /**
594     * Returns the focused child of this view, if any. The child may have focus
595     * or contain focus.
596     *
597     * @return the focused child or null.
598     */
599    public View getFocusedChild() {
600        return mFocused;
601    }
602
603    /**
604     * Returns true if this view has or contains focus
605     *
606     * @return true if this view has or contains focus
607     */
608    @Override
609    public boolean hasFocus() {
610        return (mPrivateFlags & FOCUSED) != 0 || mFocused != null;
611    }
612
613    /*
614     * (non-Javadoc)
615     *
616     * @see android.view.View#findFocus()
617     */
618    @Override
619    public View findFocus() {
620        if (DBG) {
621            System.out.println("Find focus in " + this + ": flags="
622                    + isFocused() + ", child=" + mFocused);
623        }
624
625        if (isFocused()) {
626            return this;
627        }
628
629        if (mFocused != null) {
630            return mFocused.findFocus();
631        }
632        return null;
633    }
634
635    /**
636     * {@inheritDoc}
637     */
638    @Override
639    public boolean hasFocusable() {
640        if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
641            return false;
642        }
643
644        if (isFocusable()) {
645            return true;
646        }
647
648        final int descendantFocusability = getDescendantFocusability();
649        if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
650            final int count = mChildrenCount;
651            final View[] children = mChildren;
652
653            for (int i = 0; i < count; i++) {
654                final View child = children[i];
655                if (child.hasFocusable()) {
656                    return true;
657                }
658            }
659        }
660
661        return false;
662    }
663
664    /**
665     * {@inheritDoc}
666     */
667    @Override
668    public void addFocusables(ArrayList<View> views, int direction) {
669        addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
670    }
671
672    /**
673     * {@inheritDoc}
674     */
675    @Override
676    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
677        final int focusableCount = views.size();
678
679        final int descendantFocusability = getDescendantFocusability();
680
681        if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
682            final int count = mChildrenCount;
683            final View[] children = mChildren;
684
685            for (int i = 0; i < count; i++) {
686                final View child = children[i];
687                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
688                    child.addFocusables(views, direction, focusableMode);
689                }
690            }
691        }
692
693        // we add ourselves (if focusable) in all cases except for when we are
694        // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable.  this is
695        // to avoid the focus search finding layouts when a more precise search
696        // among the focusable children would be more interesting.
697        if (
698            descendantFocusability != FOCUS_AFTER_DESCENDANTS ||
699                // No focusable descendants
700                (focusableCount == views.size())) {
701            super.addFocusables(views, direction, focusableMode);
702        }
703    }
704
705    /**
706     * {@inheritDoc}
707     */
708    @Override
709    public void dispatchWindowFocusChanged(boolean hasFocus) {
710        super.dispatchWindowFocusChanged(hasFocus);
711        final int count = mChildrenCount;
712        final View[] children = mChildren;
713        for (int i = 0; i < count; i++) {
714            children[i].dispatchWindowFocusChanged(hasFocus);
715        }
716    }
717
718    /**
719     * {@inheritDoc}
720     */
721    @Override
722    public void addTouchables(ArrayList<View> views) {
723        super.addTouchables(views);
724
725        final int count = mChildrenCount;
726        final View[] children = mChildren;
727
728        for (int i = 0; i < count; i++) {
729            final View child = children[i];
730            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
731                child.addTouchables(views);
732            }
733        }
734    }
735
736    /**
737     * {@inheritDoc}
738     */
739    @Override
740    public void dispatchDisplayHint(int hint) {
741        super.dispatchDisplayHint(hint);
742        final int count = mChildrenCount;
743        final View[] children = mChildren;
744        for (int i = 0; i < count; i++) {
745            children[i].dispatchDisplayHint(hint);
746        }
747    }
748
749    /**
750     * {@inheritDoc}
751     */
752    @Override
753    protected void dispatchVisibilityChanged(View changedView, int visibility) {
754        super.dispatchVisibilityChanged(changedView, visibility);
755        final int count = mChildrenCount;
756        final View[] children = mChildren;
757        for (int i = 0; i < count; i++) {
758            children[i].dispatchVisibilityChanged(changedView, visibility);
759        }
760    }
761
762    /**
763     * {@inheritDoc}
764     */
765    @Override
766    public void dispatchWindowVisibilityChanged(int visibility) {
767        super.dispatchWindowVisibilityChanged(visibility);
768        final int count = mChildrenCount;
769        final View[] children = mChildren;
770        for (int i = 0; i < count; i++) {
771            children[i].dispatchWindowVisibilityChanged(visibility);
772        }
773    }
774
775    /**
776     * {@inheritDoc}
777     */
778    @Override
779    public void dispatchConfigurationChanged(Configuration newConfig) {
780        super.dispatchConfigurationChanged(newConfig);
781        final int count = mChildrenCount;
782        final View[] children = mChildren;
783        for (int i = 0; i < count; i++) {
784            children[i].dispatchConfigurationChanged(newConfig);
785        }
786    }
787
788    /**
789     * {@inheritDoc}
790     */
791    public void recomputeViewAttributes(View child) {
792        ViewParent parent = mParent;
793        if (parent != null) parent.recomputeViewAttributes(this);
794    }
795
796    @Override
797    void dispatchCollectViewAttributes(int visibility) {
798        visibility |= mViewFlags&VISIBILITY_MASK;
799        super.dispatchCollectViewAttributes(visibility);
800        final int count = mChildrenCount;
801        final View[] children = mChildren;
802        for (int i = 0; i < count; i++) {
803            children[i].dispatchCollectViewAttributes(visibility);
804        }
805    }
806
807    /**
808     * {@inheritDoc}
809     */
810    public void bringChildToFront(View child) {
811        int index = indexOfChild(child);
812        if (index >= 0) {
813            removeFromArray(index);
814            addInArray(child, mChildrenCount);
815            child.mParent = this;
816        }
817    }
818
819    /**
820     * {@inheritDoc}
821     */
822    @Override
823    public boolean dispatchKeyEventPreIme(KeyEvent event) {
824        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
825            return super.dispatchKeyEventPreIme(event);
826        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
827            return mFocused.dispatchKeyEventPreIme(event);
828        }
829        return false;
830    }
831
832    /**
833     * {@inheritDoc}
834     */
835    @Override
836    public boolean dispatchKeyEvent(KeyEvent event) {
837        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
838            return super.dispatchKeyEvent(event);
839        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
840            return mFocused.dispatchKeyEvent(event);
841        }
842        return false;
843    }
844
845    /**
846     * {@inheritDoc}
847     */
848    @Override
849    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
850        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
851            return super.dispatchKeyShortcutEvent(event);
852        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
853            return mFocused.dispatchKeyShortcutEvent(event);
854        }
855        return false;
856    }
857
858    /**
859     * {@inheritDoc}
860     */
861    @Override
862    public boolean dispatchTrackballEvent(MotionEvent event) {
863        if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
864            return super.dispatchTrackballEvent(event);
865        } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
866            return mFocused.dispatchTrackballEvent(event);
867        }
868        return false;
869    }
870
871    /**
872     * {@inheritDoc}
873     */
874    @Override
875    public boolean dispatchTouchEvent(MotionEvent ev) {
876        if (!onFilterTouchEventForSecurity(ev)) {
877            return false;
878        }
879
880        if ((mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS) {
881            if (mSplitMotionTargets == null) {
882                mSplitMotionTargets = new SplitMotionTargets();
883            }
884            return dispatchSplitTouchEvent(ev);
885        }
886
887        final int action = ev.getAction();
888        final float xf = ev.getX();
889        final float yf = ev.getY();
890        final float scrolledXFloat = xf + mScrollX;
891        final float scrolledYFloat = yf + mScrollY;
892
893        boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
894
895        if (action == MotionEvent.ACTION_DOWN) {
896            if (mMotionTarget != null) {
897                // this is weird, we got a pen down, but we thought it was
898                // already down!
899                // XXX: We should probably send an ACTION_UP to the current
900                // target.
901                mMotionTarget = null;
902            }
903            // If we're disallowing intercept or if we're allowing and we didn't
904            // intercept
905            if (disallowIntercept || !onInterceptTouchEvent(ev)) {
906                // reset this event's action (just to protect ourselves)
907                ev.setAction(MotionEvent.ACTION_DOWN);
908                // We know we want to dispatch the event down, find a child
909                // who can handle it, start with the front-most child.
910                final View[] children = mChildren;
911                final int count = mChildrenCount;
912
913                // Check for children with overlays first. They don't rely on hit rects to determine
914                // if they can accept a new touch event.
915                if ((mGroupFlags & FLAG_CHILD_HAS_OVERLAY) == FLAG_CHILD_HAS_OVERLAY) {
916                    for (int i = count - 1; i >= 0; i--) {
917                        final View child = children[i];
918                        // Don't let children respond to events as an overlay during an animation.
919                        if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
920                                && child.getAnimation() == null
921                                && child.isOverlayEnabled()) {
922                            // offset the event to the view's coordinate system
923                            final float xc = scrolledXFloat - child.mLeft;
924                            final float yc = scrolledYFloat - child.mTop;
925                            ev.setLocation(xc, yc);
926                            child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
927                            if (child.dispatchTouchEvent(ev))  {
928                                // Event handled, we have a target now.
929                                mMotionTarget = child;
930                                return true;
931                            }
932                            // The event didn't get handled, try the next view.
933                            // Don't reset the event's location, it's not
934                            // necessary here.
935                        }
936                    }
937                }
938
939                // Now check views normally.
940                for (int i = count - 1; i >= 0; i--) {
941                    final View child = children[i];
942                    if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
943                            || child.getAnimation() != null) {
944                        // Single dispatch always picks its target based on the initial down
945                        // event's position - index 0
946                        if (dispatchTouchEventIfInView(child, ev, 0)) {
947                            mMotionTarget = child;
948                            return true;
949                        }
950                    }
951                }
952            }
953        }
954
955        boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||
956                (action == MotionEvent.ACTION_CANCEL);
957
958        if (isUpOrCancel) {
959            // Note, we've already copied the previous state to our local
960            // variable, so this takes effect on the next event
961            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
962        }
963
964        // The event wasn't an ACTION_DOWN, dispatch it to our target if
965        // we have one.
966        final View target = mMotionTarget;
967        if (target == null) {
968            // We don't have a target, this means we're handling the
969            // event as a regular view.
970            ev.setLocation(xf, yf);
971            if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
972                ev.setAction(MotionEvent.ACTION_CANCEL);
973                mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
974            }
975            return super.dispatchTouchEvent(ev);
976        }
977
978        // Calculate the offset point into the target's local coordinates
979        float xc = scrolledXFloat - (float) target.mLeft;
980        float yc = scrolledYFloat - (float) target.mTop;
981        if (!target.hasIdentityMatrix() && mAttachInfo != null) {
982            // non-identity matrix: transform the point into the view's coordinates
983            final float[] localXY = mAttachInfo.mTmpTransformLocation;
984            localXY[0] = xc;
985            localXY[1] = yc;
986            target.getInverseMatrix().mapPoints(localXY);
987            xc = localXY[0];
988            yc = localXY[1];
989        }
990
991        // if have a target, see if we're allowed to and want to intercept its
992        // events
993        if (!disallowIntercept && onInterceptTouchEvent(ev)) {
994            mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
995            ev.setAction(MotionEvent.ACTION_CANCEL);
996            ev.setLocation(xc, yc);
997            if (!target.dispatchTouchEvent(ev)) {
998                // target didn't handle ACTION_CANCEL. not much we can do
999                // but they should have.
1000            }
1001            // clear the target
1002            mMotionTarget = null;
1003            // Don't dispatch this event to our own view, because we already
1004            // saw it when intercepting; we just want to give the following
1005            // event to the normal onTouchEvent().
1006            return true;
1007        }
1008
1009        if (isUpOrCancel) {
1010            mMotionTarget = null;
1011        }
1012
1013        // finally offset the event to the target's coordinate system and
1014        // dispatch the event.
1015        ev.setLocation(xc, yc);
1016
1017        if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
1018            ev.setAction(MotionEvent.ACTION_CANCEL);
1019            target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1020            mMotionTarget = null;
1021        }
1022
1023        if (target.dispatchTouchEvent(ev)) {
1024            return true;
1025        } else {
1026            ev.setLocation(xf, yf);
1027        }
1028        return false;
1029    }
1030
1031    /**
1032     * This method detects whether the pointer location at <code>pointerIndex</code> within
1033     * <code>ev</code> is inside the specified view. If so, the transformed event is dispatched to
1034     * <code>child</code>.
1035     *
1036     * @param child View to hit test against
1037     * @param ev MotionEvent to test
1038     * @param pointerIndex Index of the pointer within <code>ev</code> to test
1039     * @return <code>false</code> if the hit test failed, or the result of
1040     *         <code>child.dispatchTouchEvent</code>
1041     */
1042    private boolean dispatchTouchEventIfInView(View child, MotionEvent ev, int pointerIndex) {
1043        final float x = ev.getX(pointerIndex);
1044        final float y = ev.getY(pointerIndex);
1045        final float scrolledX = x + mScrollX;
1046        final float scrolledY = y + mScrollY;
1047        float localX = scrolledX - child.mLeft;
1048        float localY = scrolledY - child.mTop;
1049        if (!child.hasIdentityMatrix() && mAttachInfo != null) {
1050            // non-identity matrix: transform the point into the view's coordinates
1051            final float[] localXY = mAttachInfo.mTmpTransformLocation;
1052            localXY[0] = localX;
1053            localXY[1] = localY;
1054            child.getInverseMatrix().mapPoints(localXY);
1055            localX = localXY[0];
1056            localY = localXY[1];
1057        }
1058        if (localX >= 0 && localY >= 0 && localX < (child.mRight - child.mLeft) &&
1059                localY < (child.mBottom - child.mTop)) {
1060            // It would be safer to clone the event here but we don't for performance.
1061            // There are many subtle interactions in touch event dispatch; change at your own risk.
1062            child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1063            ev.offsetLocation(localX - x, localY - y);
1064            if (child.dispatchTouchEvent(ev)) {
1065                return true;
1066            } else {
1067                ev.offsetLocation(x - localX, y - localY);
1068                return false;
1069            }
1070        }
1071        return false;
1072    }
1073
1074    private boolean dispatchSplitTouchEvent(MotionEvent ev) {
1075        final SplitMotionTargets targets = mSplitMotionTargets;
1076        final int action = ev.getAction();
1077        final int maskedAction = ev.getActionMasked();
1078        float xf = ev.getX();
1079        float yf = ev.getY();
1080        float scrolledXFloat = xf + mScrollX;
1081        float scrolledYFloat = yf + mScrollY;
1082
1083        boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
1084
1085        if (maskedAction == MotionEvent.ACTION_DOWN ||
1086                maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
1087            final int actionIndex = ev.getActionIndex();
1088            final int actionId = ev.getPointerId(actionIndex);
1089
1090            // Clear out any current target for this ID.
1091            // XXX: We should probably send an ACTION_UP to the current
1092            // target if present.
1093            targets.removeById(actionId);
1094
1095            // If we're disallowing intercept or if we're allowing and we didn't
1096            // intercept
1097            if (disallowIntercept || !onInterceptTouchEvent(ev)) {
1098                // reset this event's action (just to protect ourselves)
1099                ev.setAction(action);
1100                // We know we want to dispatch the event down, try to find a child
1101                // who can handle it, start with the front-most child.
1102                final long downTime = ev.getEventTime();
1103                final View[] children = mChildren;
1104                final int count = mChildrenCount;
1105                for (int i = count - 1; i >= 0; i--) {
1106                    final View child = children[i];
1107                    if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
1108                            || child.getAnimation() != null) {
1109                        final MotionEvent childEvent =
1110                                targets.filterMotionEventForChild(ev, child, downTime);
1111                        if (childEvent != null) {
1112                            try {
1113                                final int childActionIndex = childEvent.findPointerIndex(actionId);
1114                                if (dispatchTouchEventIfInView(child, childEvent,
1115                                        childActionIndex)) {
1116                                    targets.add(actionId, child, downTime);
1117
1118                                    return true;
1119                                }
1120                            } finally {
1121                                childEvent.recycle();
1122                            }
1123                        }
1124                    }
1125                }
1126
1127                // Didn't find a new target. Do we have a "primary" target to send to?
1128                final SplitMotionTargets.TargetInfo primaryTargetInfo = targets.getPrimaryTarget();
1129                if (primaryTargetInfo != null) {
1130                    final View primaryTarget = primaryTargetInfo.view;
1131                    final MotionEvent childEvent = targets.filterMotionEventForChild(ev,
1132                            primaryTarget, primaryTargetInfo.downTime);
1133                    if (childEvent != null) {
1134                        try {
1135                            // Calculate the offset point into the target's local coordinates
1136                            float xc = scrolledXFloat - (float) primaryTarget.mLeft;
1137                            float yc = scrolledYFloat - (float) primaryTarget.mTop;
1138                            if (!primaryTarget.hasIdentityMatrix() && mAttachInfo != null) {
1139                                // non-identity matrix: transform the point into the view's
1140                                // coordinates
1141                                final float[] localXY = mAttachInfo.mTmpTransformLocation;
1142                                localXY[0] = xc;
1143                                localXY[1] = yc;
1144                                primaryTarget.getInverseMatrix().mapPoints(localXY);
1145                                xc = localXY[0];
1146                                yc = localXY[1];
1147                            }
1148                            childEvent.setLocation(xc, yc);
1149                            if (primaryTarget.dispatchTouchEvent(childEvent)) {
1150                                targets.add(actionId, primaryTarget, primaryTargetInfo.downTime);
1151                                return true;
1152                            }
1153                        } finally {
1154                            childEvent.recycle();
1155                        }
1156                    }
1157                }
1158            }
1159        }
1160
1161        boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||
1162                (action == MotionEvent.ACTION_CANCEL);
1163
1164        if (isUpOrCancel) {
1165            // Note, we've already copied the previous state to our local
1166            // variable, so this takes effect on the next event
1167            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
1168        }
1169
1170        if (targets.isEmpty()) {
1171            // We don't have any targets, this means we're handling the
1172            // event as a regular view.
1173            ev.setLocation(xf, yf);
1174            if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
1175                ev.setAction(MotionEvent.ACTION_CANCEL);
1176                mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1177            }
1178            return super.dispatchTouchEvent(ev);
1179        }
1180
1181        // if we have targets, see if we're allowed to and want to intercept their
1182        // events
1183        int uniqueTargetCount = targets.getUniqueTargetCount();
1184        if (!disallowIntercept && onInterceptTouchEvent(ev)) {
1185            mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1186
1187            for (int uniqueIndex = 0; uniqueIndex < uniqueTargetCount; uniqueIndex++) {
1188                final View target = targets.getUniqueTargetAt(uniqueIndex).view;
1189
1190                // Calculate the offset point into the target's local coordinates
1191                float xc = scrolledXFloat - (float) target.mLeft;
1192                float yc = scrolledYFloat - (float) target.mTop;
1193                if (!target.hasIdentityMatrix() && mAttachInfo != null) {
1194                    // non-identity matrix: transform the point into the view's coordinates
1195                    final float[] localXY = mAttachInfo.mTmpTransformLocation;
1196                    localXY[0] = xc;
1197                    localXY[1] = yc;
1198                    target.getInverseMatrix().mapPoints(localXY);
1199                    xc = localXY[0];
1200                    yc = localXY[1];
1201                }
1202
1203                ev.setAction(MotionEvent.ACTION_CANCEL);
1204                ev.setLocation(xc, yc);
1205                if (!target.dispatchTouchEvent(ev)) {
1206                    // target didn't handle ACTION_CANCEL. not much we can do
1207                    // but they should have.
1208                }
1209            }
1210            targets.clear();
1211            // Don't dispatch this event to our own view, because we already
1212            // saw it when intercepting; we just want to give the following
1213            // event to the normal onTouchEvent().
1214            return true;
1215        }
1216
1217        boolean handled = false;
1218        for (int uniqueIndex = 0; uniqueIndex < uniqueTargetCount; uniqueIndex++) {
1219            final SplitMotionTargets.TargetInfo targetInfo = targets.getUniqueTargetAt(uniqueIndex);
1220            final View target = targetInfo.view;
1221
1222            final MotionEvent targetEvent =
1223                    targets.filterMotionEventForChild(ev, target, targetInfo.downTime);
1224            if (targetEvent == null) {
1225                continue;
1226            }
1227
1228            try {
1229                // Calculate the offset point into the target's local coordinates
1230                xf = targetEvent.getX();
1231                yf = targetEvent.getY();
1232                scrolledXFloat = xf + mScrollX;
1233                scrolledYFloat = yf + mScrollY;
1234                float xc = scrolledXFloat - (float) target.mLeft;
1235                float yc = scrolledYFloat - (float) target.mTop;
1236                if (!target.hasIdentityMatrix() && mAttachInfo != null) {
1237                    // non-identity matrix: transform the point into the view's coordinates
1238                    final float[] localXY = mAttachInfo.mTmpTransformLocation;
1239                    localXY[0] = xc;
1240                    localXY[1] = yc;
1241                    target.getInverseMatrix().mapPoints(localXY);
1242                    xc = localXY[0];
1243                    yc = localXY[1];
1244                }
1245
1246                // finally offset the event to the target's coordinate system and
1247                // dispatch the event.
1248                targetEvent.setLocation(xc, yc);
1249
1250                if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
1251                    targetEvent.setAction(MotionEvent.ACTION_CANCEL);
1252                    target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1253                    targets.removeView(target);
1254                    uniqueIndex--;
1255                    uniqueTargetCount--;
1256                }
1257
1258                handled |= target.dispatchTouchEvent(targetEvent);
1259            } finally {
1260                targetEvent.recycle();
1261            }
1262        }
1263
1264        if (maskedAction == MotionEvent.ACTION_POINTER_UP) {
1265            final int removeId = ev.getPointerId(ev.getActionIndex());
1266            targets.removeById(removeId);
1267        }
1268
1269        if (isUpOrCancel) {
1270            targets.clear();
1271        }
1272
1273        return handled;
1274    }
1275
1276    /**
1277     * Enable or disable the splitting of MotionEvents to multiple children during touch event
1278     * dispatch. This behavior is disabled by default.
1279     *
1280     * <p>When this option is enabled MotionEvents may be split and dispatched to different child
1281     * views depending on where each pointer initially went down. This allows for user interactions
1282     * such as scrolling two panes of content independently, chording of buttons, and performing
1283     * independent gestures on different pieces of content.
1284     *
1285     * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple
1286     *              child views. <code>false</code> to only allow one child view to be the target of
1287     *              any MotionEvent received by this ViewGroup.
1288     */
1289    public void setMotionEventSplittingEnabled(boolean split) {
1290        // TODO Applications really shouldn't change this setting mid-touch event,
1291        // but perhaps this should handle that case and send ACTION_CANCELs to any child views
1292        // with gestures in progress when this is changed.
1293        if (split) {
1294            mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
1295        } else {
1296            mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
1297            mSplitMotionTargets = null;
1298        }
1299    }
1300
1301    /**
1302     * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
1303     */
1304    public boolean isMotionEventSplittingEnabled() {
1305        return (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS;
1306    }
1307
1308    /**
1309     * {@inheritDoc}
1310     */
1311    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1312
1313        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
1314            // We're already in this state, assume our ancestors are too
1315            return;
1316        }
1317
1318        if (disallowIntercept) {
1319            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
1320        } else {
1321            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
1322        }
1323
1324        // Pass it up to our parent
1325        if (mParent != null) {
1326            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
1327        }
1328    }
1329
1330    /**
1331     * Implement this method to intercept all touch screen motion events.  This
1332     * allows you to watch events as they are dispatched to your children, and
1333     * take ownership of the current gesture at any point.
1334     *
1335     * <p>Using this function takes some care, as it has a fairly complicated
1336     * interaction with {@link View#onTouchEvent(MotionEvent)
1337     * View.onTouchEvent(MotionEvent)}, and using it requires implementing
1338     * that method as well as this one in the correct way.  Events will be
1339     * received in the following order:
1340     *
1341     * <ol>
1342     * <li> You will receive the down event here.
1343     * <li> The down event will be handled either by a child of this view
1344     * group, or given to your own onTouchEvent() method to handle; this means
1345     * you should implement onTouchEvent() to return true, so you will
1346     * continue to see the rest of the gesture (instead of looking for
1347     * a parent view to handle it).  Also, by returning true from
1348     * onTouchEvent(), you will not receive any following
1349     * events in onInterceptTouchEvent() and all touch processing must
1350     * happen in onTouchEvent() like normal.
1351     * <li> For as long as you return false from this function, each following
1352     * event (up to and including the final up) will be delivered first here
1353     * and then to the target's onTouchEvent().
1354     * <li> If you return true from here, you will not receive any
1355     * following events: the target view will receive the same event but
1356     * with the action {@link MotionEvent#ACTION_CANCEL}, and all further
1357     * events will be delivered to your onTouchEvent() method and no longer
1358     * appear here.
1359     * </ol>
1360     *
1361     * @param ev The motion event being dispatched down the hierarchy.
1362     * @return Return true to steal motion events from the children and have
1363     * them dispatched to this ViewGroup through onTouchEvent().
1364     * The current target will receive an ACTION_CANCEL event, and no further
1365     * messages will be delivered here.
1366     */
1367    public boolean onInterceptTouchEvent(MotionEvent ev) {
1368        return false;
1369    }
1370
1371    /**
1372     * {@inheritDoc}
1373     *
1374     * Looks for a view to give focus to respecting the setting specified by
1375     * {@link #getDescendantFocusability()}.
1376     *
1377     * Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to
1378     * find focus within the children of this group when appropriate.
1379     *
1380     * @see #FOCUS_BEFORE_DESCENDANTS
1381     * @see #FOCUS_AFTER_DESCENDANTS
1382     * @see #FOCUS_BLOCK_DESCENDANTS
1383     * @see #onRequestFocusInDescendants
1384     */
1385    @Override
1386    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
1387        if (DBG) {
1388            System.out.println(this + " ViewGroup.requestFocus direction="
1389                    + direction);
1390        }
1391        int descendantFocusability = getDescendantFocusability();
1392
1393        switch (descendantFocusability) {
1394            case FOCUS_BLOCK_DESCENDANTS:
1395                return super.requestFocus(direction, previouslyFocusedRect);
1396            case FOCUS_BEFORE_DESCENDANTS: {
1397                final boolean took = super.requestFocus(direction, previouslyFocusedRect);
1398                return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect);
1399            }
1400            case FOCUS_AFTER_DESCENDANTS: {
1401                final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);
1402                return took ? took : super.requestFocus(direction, previouslyFocusedRect);
1403            }
1404            default:
1405                throw new IllegalStateException("descendant focusability must be "
1406                        + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS "
1407                        + "but is " + descendantFocusability);
1408        }
1409    }
1410
1411    /**
1412     * Look for a descendant to call {@link View#requestFocus} on.
1413     * Called by {@link ViewGroup#requestFocus(int, android.graphics.Rect)}
1414     * when it wants to request focus within its children.  Override this to
1415     * customize how your {@link ViewGroup} requests focus within its children.
1416     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
1417     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
1418     *        to give a finer grained hint about where focus is coming from.  May be null
1419     *        if there is no hint.
1420     * @return Whether focus was taken.
1421     */
1422    @SuppressWarnings({"ConstantConditions"})
1423    protected boolean onRequestFocusInDescendants(int direction,
1424            Rect previouslyFocusedRect) {
1425        int index;
1426        int increment;
1427        int end;
1428        int count = mChildrenCount;
1429        if ((direction & FOCUS_FORWARD) != 0) {
1430            index = 0;
1431            increment = 1;
1432            end = count;
1433        } else {
1434            index = count - 1;
1435            increment = -1;
1436            end = -1;
1437        }
1438        final View[] children = mChildren;
1439        for (int i = index; i != end; i += increment) {
1440            View child = children[i];
1441            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1442                if (child.requestFocus(direction, previouslyFocusedRect)) {
1443                    return true;
1444                }
1445            }
1446        }
1447        return false;
1448    }
1449
1450    /**
1451     * {@inheritDoc}
1452     *
1453     * @hide
1454     */
1455    @Override
1456    public void dispatchStartTemporaryDetach() {
1457        super.dispatchStartTemporaryDetach();
1458        final int count = mChildrenCount;
1459        final View[] children = mChildren;
1460        for (int i = 0; i < count; i++) {
1461            children[i].dispatchStartTemporaryDetach();
1462        }
1463    }
1464
1465    /**
1466     * {@inheritDoc}
1467     *
1468     * @hide
1469     */
1470    @Override
1471    public void dispatchFinishTemporaryDetach() {
1472        super.dispatchFinishTemporaryDetach();
1473        final int count = mChildrenCount;
1474        final View[] children = mChildren;
1475        for (int i = 0; i < count; i++) {
1476            children[i].dispatchFinishTemporaryDetach();
1477        }
1478    }
1479
1480    /**
1481     * {@inheritDoc}
1482     */
1483    @Override
1484    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
1485        super.dispatchAttachedToWindow(info, visibility);
1486        visibility |= mViewFlags & VISIBILITY_MASK;
1487        final int count = mChildrenCount;
1488        final View[] children = mChildren;
1489        for (int i = 0; i < count; i++) {
1490            children[i].dispatchAttachedToWindow(info, visibility);
1491        }
1492    }
1493
1494    @Override
1495    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1496        boolean populated = false;
1497        for (int i = 0, count = getChildCount(); i < count; i++) {
1498            populated |= getChildAt(i).dispatchPopulateAccessibilityEvent(event);
1499        }
1500        return populated;
1501    }
1502
1503    /**
1504     * {@inheritDoc}
1505     */
1506    @Override
1507    void dispatchDetachedFromWindow() {
1508        // If we still have a motion target, we are still in the process of
1509        // dispatching motion events to a child; we need to get rid of that
1510        // child to avoid dispatching events to it after the window is torn
1511        // down. To make sure we keep the child in a consistent state, we
1512        // first send it an ACTION_CANCEL motion event.
1513        if (mMotionTarget != null) {
1514            final long now = SystemClock.uptimeMillis();
1515            final MotionEvent event = MotionEvent.obtain(now, now,
1516                    MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
1517            mMotionTarget.dispatchTouchEvent(event);
1518            event.recycle();
1519            mMotionTarget = null;
1520        }
1521
1522        final int count = mChildrenCount;
1523        final View[] children = mChildren;
1524        for (int i = 0; i < count; i++) {
1525            children[i].dispatchDetachedFromWindow();
1526        }
1527        super.dispatchDetachedFromWindow();
1528    }
1529
1530    /**
1531     * {@inheritDoc}
1532     */
1533    @Override
1534    public void setPadding(int left, int top, int right, int bottom) {
1535        super.setPadding(left, top, right, bottom);
1536
1537        if ((mPaddingLeft | mPaddingTop | mPaddingRight | mPaddingRight) != 0) {
1538            mGroupFlags |= FLAG_PADDING_NOT_NULL;
1539        } else {
1540            mGroupFlags &= ~FLAG_PADDING_NOT_NULL;
1541        }
1542    }
1543
1544    /**
1545     * {@inheritDoc}
1546     */
1547    @Override
1548    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
1549        super.dispatchSaveInstanceState(container);
1550        final int count = mChildrenCount;
1551        final View[] children = mChildren;
1552        for (int i = 0; i < count; i++) {
1553            View c = children[i];
1554            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
1555                c.dispatchSaveInstanceState(container);
1556            }
1557        }
1558    }
1559
1560    /**
1561     * Perform dispatching of a {@link #saveHierarchyState freeze()} to only this view,
1562     * not to its children.  For use when overriding
1563     * {@link #dispatchSaveInstanceState dispatchFreeze()} to allow subclasses to freeze
1564     * their own state but not the state of their children.
1565     *
1566     * @param container the container
1567     */
1568    protected void dispatchFreezeSelfOnly(SparseArray<Parcelable> container) {
1569        super.dispatchSaveInstanceState(container);
1570    }
1571
1572    /**
1573     * {@inheritDoc}
1574     */
1575    @Override
1576    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
1577        super.dispatchRestoreInstanceState(container);
1578        final int count = mChildrenCount;
1579        final View[] children = mChildren;
1580        for (int i = 0; i < count; i++) {
1581            View c = children[i];
1582            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
1583                c.dispatchRestoreInstanceState(container);
1584            }
1585        }
1586    }
1587
1588    /**
1589     * Perform dispatching of a {@link #restoreHierarchyState thaw()} to only this view,
1590     * not to its children.  For use when overriding
1591     * {@link #dispatchRestoreInstanceState dispatchThaw()} to allow subclasses to thaw
1592     * their own state but not the state of their children.
1593     *
1594     * @param container the container
1595     */
1596    protected void dispatchThawSelfOnly(SparseArray<Parcelable> container) {
1597        super.dispatchRestoreInstanceState(container);
1598    }
1599
1600    /**
1601     * Enables or disables the drawing cache for each child of this view group.
1602     *
1603     * @param enabled true to enable the cache, false to dispose of it
1604     */
1605    protected void setChildrenDrawingCacheEnabled(boolean enabled) {
1606        if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) {
1607            final View[] children = mChildren;
1608            final int count = mChildrenCount;
1609            for (int i = 0; i < count; i++) {
1610                children[i].setDrawingCacheEnabled(enabled);
1611            }
1612        }
1613    }
1614
1615    @Override
1616    protected void onAnimationStart() {
1617        super.onAnimationStart();
1618
1619        // When this ViewGroup's animation starts, build the cache for the children
1620        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
1621            final int count = mChildrenCount;
1622            final View[] children = mChildren;
1623
1624            for (int i = 0; i < count; i++) {
1625                final View child = children[i];
1626                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1627                    child.setDrawingCacheEnabled(true);
1628                    child.buildDrawingCache(true);
1629                }
1630            }
1631
1632            mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
1633        }
1634    }
1635
1636    @Override
1637    protected void onAnimationEnd() {
1638        super.onAnimationEnd();
1639
1640        // When this ViewGroup's animation ends, destroy the cache of the children
1641        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
1642            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
1643
1644            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
1645                setChildrenDrawingCacheEnabled(false);
1646            }
1647        }
1648    }
1649
1650    @Override
1651    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
1652        int count = mChildrenCount;
1653        int[] visibilities = null;
1654
1655        if (skipChildren) {
1656            visibilities = new int[count];
1657            for (int i = 0; i < count; i++) {
1658                View child = getChildAt(i);
1659                visibilities[i] = child.getVisibility();
1660                if (visibilities[i] == View.VISIBLE) {
1661                    child.setVisibility(INVISIBLE);
1662                }
1663            }
1664        }
1665
1666        Bitmap b = super.createSnapshot(quality, backgroundColor, skipChildren);
1667
1668        if (skipChildren) {
1669            for (int i = 0; i < count; i++) {
1670                getChildAt(i).setVisibility(visibilities[i]);
1671            }
1672        }
1673
1674        return b;
1675    }
1676
1677    /**
1678     * {@inheritDoc}
1679     */
1680    @Override
1681    protected void dispatchDraw(Canvas canvas) {
1682        final int count = mChildrenCount;
1683        final View[] children = mChildren;
1684        int flags = mGroupFlags;
1685
1686        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
1687            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
1688
1689            for (int i = 0; i < count; i++) {
1690                final View child = children[i];
1691                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1692                    final LayoutParams params = child.getLayoutParams();
1693                    attachLayoutAnimationParameters(child, params, i, count);
1694                    bindLayoutAnimation(child);
1695                    if (cache) {
1696                        child.setDrawingCacheEnabled(true);
1697                        child.buildDrawingCache(true);
1698                    }
1699                }
1700            }
1701
1702            final LayoutAnimationController controller = mLayoutAnimationController;
1703            if (controller.willOverlap()) {
1704                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
1705            }
1706
1707            controller.start();
1708
1709            mGroupFlags &= ~FLAG_RUN_ANIMATION;
1710            mGroupFlags &= ~FLAG_ANIMATION_DONE;
1711
1712            if (cache) {
1713                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
1714            }
1715
1716            if (mAnimationListener != null) {
1717                mAnimationListener.onAnimationStart(controller.getAnimation());
1718            }
1719        }
1720
1721        int saveCount = 0;
1722        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
1723        if (clipToPadding) {
1724            saveCount = canvas.save();
1725            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
1726                    mScrollX + mRight - mLeft - mPaddingRight,
1727                    mScrollY + mBottom - mTop - mPaddingBottom);
1728
1729        }
1730
1731        // We will draw our child's animation, let's reset the flag
1732        mPrivateFlags &= ~DRAW_ANIMATION;
1733        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
1734
1735        boolean more = false;
1736        final long drawingTime = getDrawingTime();
1737
1738        if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {
1739            for (int i = 0; i < count; i++) {
1740                final View child = children[i];
1741                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
1742                    more |= drawChild(canvas, child, drawingTime);
1743                }
1744            }
1745        } else {
1746            for (int i = 0; i < count; i++) {
1747                final View child = children[getChildDrawingOrder(count, i)];
1748                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
1749                    more |= drawChild(canvas, child, drawingTime);
1750                }
1751            }
1752        }
1753
1754        // Draw any disappearing views that have animations
1755        if (mDisappearingChildren != null) {
1756            final ArrayList<View> disappearingChildren = mDisappearingChildren;
1757            final int disappearingCount = disappearingChildren.size() - 1;
1758            // Go backwards -- we may delete as animations finish
1759            for (int i = disappearingCount; i >= 0; i--) {
1760                final View child = disappearingChildren.get(i);
1761                more |= drawChild(canvas, child, drawingTime);
1762            }
1763        }
1764
1765        if (clipToPadding) {
1766            canvas.restoreToCount(saveCount);
1767        }
1768
1769        // mGroupFlags might have been updated by drawChild()
1770        flags = mGroupFlags;
1771
1772        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
1773            invalidate();
1774        }
1775
1776        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
1777                mLayoutAnimationController.isDone() && !more) {
1778            // We want to erase the drawing cache and notify the listener after the
1779            // next frame is drawn because one extra invalidate() is caused by
1780            // drawChild() after the animation is over
1781            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
1782            final Runnable end = new Runnable() {
1783               public void run() {
1784                   notifyAnimationListener();
1785               }
1786            };
1787            post(end);
1788        }
1789    }
1790
1791    /**
1792     * Returns the index of the child to draw for this iteration. Override this
1793     * if you want to change the drawing order of children. By default, it
1794     * returns i.
1795     * <p>
1796     * NOTE: In order for this method to be called, you must enable child ordering
1797     * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}.
1798     *
1799     * @param i The current iteration.
1800     * @return The index of the child to draw this iteration.
1801     *
1802     * @see #setChildrenDrawingOrderEnabled(boolean)
1803     * @see #isChildrenDrawingOrderEnabled()
1804     */
1805    protected int getChildDrawingOrder(int childCount, int i) {
1806        return i;
1807    }
1808
1809    private void notifyAnimationListener() {
1810        mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER;
1811        mGroupFlags |= FLAG_ANIMATION_DONE;
1812
1813        if (mAnimationListener != null) {
1814           final Runnable end = new Runnable() {
1815               public void run() {
1816                   mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation());
1817               }
1818           };
1819           post(end);
1820        }
1821
1822        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
1823            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
1824            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
1825                setChildrenDrawingCacheEnabled(false);
1826            }
1827        }
1828
1829        invalidate();
1830    }
1831
1832    /**
1833     * Draw one child of this View Group. This method is responsible for getting
1834     * the canvas in the right state. This includes clipping, translating so
1835     * that the child's scrolled origin is at 0, 0, and applying any animation
1836     * transformations.
1837     *
1838     * @param canvas The canvas on which to draw the child
1839     * @param child Who to draw
1840     * @param drawingTime The time at which draw is occuring
1841     * @return True if an invalidate() was issued
1842     */
1843    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
1844        boolean more = false;
1845
1846        final int cl = child.mLeft;
1847        final int ct = child.mTop;
1848        final int cr = child.mRight;
1849        final int cb = child.mBottom;
1850
1851        final int flags = mGroupFlags;
1852
1853        if ((flags & FLAG_CLEAR_TRANSFORMATION) == FLAG_CLEAR_TRANSFORMATION) {
1854            mChildTransformation.clear();
1855            mGroupFlags &= ~FLAG_CLEAR_TRANSFORMATION;
1856        }
1857
1858        Transformation transformToApply = null;
1859        Transformation invalidationTransform;
1860        final Animation a = child.getAnimation();
1861        boolean concatMatrix = false;
1862
1863        boolean scalingRequired = false;
1864        boolean caching = false;
1865        if (!canvas.isHardwareAccelerated() &&
1866                (flags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE ||
1867                (flags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE) {
1868            caching = true;
1869            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
1870        }
1871
1872        if (a != null) {
1873            final boolean initialized = a.isInitialized();
1874            if (!initialized) {
1875                a.initialize(cr - cl, cb - ct, getWidth(), getHeight());
1876                a.initializeInvalidateRegion(0, 0, cr - cl, cb - ct);
1877                child.onAnimationStart();
1878            }
1879
1880            more = a.getTransformation(drawingTime, mChildTransformation,
1881                    scalingRequired ? mAttachInfo.mApplicationScale : 1f);
1882            if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
1883                if (mInvalidationTransformation == null) {
1884                    mInvalidationTransformation = new Transformation();
1885                }
1886                invalidationTransform = mInvalidationTransformation;
1887                a.getTransformation(drawingTime, invalidationTransform, 1f);
1888            } else {
1889                invalidationTransform = mChildTransformation;
1890            }
1891            transformToApply = mChildTransformation;
1892
1893            concatMatrix = a.willChangeTransformationMatrix();
1894
1895            if (more) {
1896                if (!a.willChangeBounds()) {
1897                    if ((flags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) ==
1898                            FLAG_OPTIMIZE_INVALIDATE) {
1899                        mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
1900                    } else if ((flags & FLAG_INVALIDATE_REQUIRED) == 0) {
1901                        // The child need to draw an animation, potentially offscreen, so
1902                        // make sure we do not cancel invalidate requests
1903                        mPrivateFlags |= DRAW_ANIMATION;
1904                        invalidate(cl, ct, cr, cb);
1905                    }
1906                } else {
1907                    if (mInvalidateRegion == null) {
1908                        mInvalidateRegion = new RectF();
1909                    }
1910                    final RectF region = mInvalidateRegion;
1911                    a.getInvalidateRegion(0, 0, cr - cl, cb - ct, region, invalidationTransform);
1912
1913                    // The child need to draw an animation, potentially offscreen, so
1914                    // make sure we do not cancel invalidate requests
1915                    mPrivateFlags |= DRAW_ANIMATION;
1916
1917                    final int left = cl + (int) region.left;
1918                    final int top = ct + (int) region.top;
1919                    invalidate(left, top, left + (int) region.width(), top + (int) region.height());
1920                }
1921            }
1922        } else if ((flags & FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
1923                FLAG_SUPPORT_STATIC_TRANSFORMATIONS) {
1924            final boolean hasTransform = getChildStaticTransformation(child, mChildTransformation);
1925            if (hasTransform) {
1926                final int transformType = mChildTransformation.getTransformationType();
1927                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
1928                        mChildTransformation : null;
1929                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
1930            }
1931        }
1932
1933        concatMatrix |= !child.hasIdentityMatrix();
1934
1935        // Sets the flag as early as possible to allow draw() implementations
1936        // to call invalidate() successfully when doing animations
1937        child.mPrivateFlags |= DRAWN;
1938
1939        if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW) &&
1940                (child.mPrivateFlags & DRAW_ANIMATION) == 0) {
1941            return more;
1942        }
1943
1944        child.computeScroll();
1945
1946        final int sx = child.mScrollX;
1947        final int sy = child.mScrollY;
1948
1949        Bitmap cache = null;
1950        if (caching) {
1951            cache = child.getDrawingCache(true);
1952        }
1953
1954        final boolean hasNoCache = cache == null;
1955
1956        final int restoreTo = canvas.save();
1957        if (hasNoCache) {
1958            canvas.translate(cl - sx, ct - sy);
1959        } else {
1960            canvas.translate(cl, ct);
1961            if (scalingRequired) {
1962                // mAttachInfo cannot be null, otherwise scalingRequired == false
1963                final float scale = 1.0f / mAttachInfo.mApplicationScale;
1964                canvas.scale(scale, scale);
1965            }
1966        }
1967
1968        float alpha = child.getAlpha();
1969
1970        if (transformToApply != null || alpha < 1.0f || !child.hasIdentityMatrix()) {
1971            int transX = 0;
1972            int transY = 0;
1973
1974            if (hasNoCache) {
1975                transX = -sx;
1976                transY = -sy;
1977            }
1978
1979            if (transformToApply != null) {
1980                if (concatMatrix) {
1981                    // Undo the scroll translation, apply the transformation matrix,
1982                    // then redo the scroll translate to get the correct result.
1983                    canvas.translate(-transX, -transY);
1984                    canvas.concat(transformToApply.getMatrix());
1985                    canvas.translate(transX, transY);
1986                    mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
1987                }
1988
1989                float transformAlpha = transformToApply.getAlpha();
1990                if (transformAlpha < 1.0f) {
1991                    alpha *= transformToApply.getAlpha();
1992                    mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
1993                }
1994            }
1995
1996            if (!child.hasIdentityMatrix()) {
1997                canvas.translate(-transX, -transY);
1998                canvas.concat(child.getMatrix());
1999                canvas.translate(transX, transY);
2000            }
2001
2002            if (alpha < 1.0f) {
2003                mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
2004
2005                if (hasNoCache) {
2006                    final int multipliedAlpha = (int) (255 * alpha);
2007                    if (!child.onSetAlpha(multipliedAlpha)) {
2008                        canvas.saveLayerAlpha(sx, sy, sx + cr - cl, sy + cb - ct, multipliedAlpha,
2009                                Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
2010                    } else {
2011                        child.mPrivateFlags |= ALPHA_SET;
2012                    }
2013                }
2014            }
2015        } else if ((child.mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
2016            child.onSetAlpha(255);
2017            child.mPrivateFlags &= ~ALPHA_SET;
2018        }
2019
2020        if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
2021            if (hasNoCache) {
2022                canvas.clipRect(sx, sy, sx + (cr - cl), sy + (cb - ct));
2023            } else {
2024                if (!scalingRequired) {
2025                    canvas.clipRect(0, 0, cr - cl, cb - ct);
2026                } else {
2027                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
2028                }
2029            }
2030        }
2031
2032        if (hasNoCache) {
2033            // Fast path for layouts with no backgrounds
2034            if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
2035                if (ViewDebug.TRACE_HIERARCHY) {
2036                    ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
2037                }
2038                child.mPrivateFlags &= ~DIRTY_MASK;
2039                child.dispatchDraw(canvas);
2040            } else {
2041                child.draw(canvas);
2042            }
2043        } else {
2044            final Paint cachePaint = mCachePaint;
2045            if (alpha < 1.0f) {
2046                cachePaint.setAlpha((int) (alpha * 255));
2047                mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE;
2048            } else if  ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) {
2049                cachePaint.setAlpha(255);
2050                mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE;
2051            }
2052            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
2053        }
2054
2055        canvas.restoreToCount(restoreTo);
2056
2057        if (a != null && !more) {
2058            child.onSetAlpha(255);
2059            finishAnimatingView(child, a);
2060        }
2061
2062        return more;
2063    }
2064
2065    /**
2066     * By default, children are clipped to their bounds before drawing. This
2067     * allows view groups to override this behavior for animations, etc.
2068     *
2069     * @param clipChildren true to clip children to their bounds,
2070     *        false otherwise
2071     * @attr ref android.R.styleable#ViewGroup_clipChildren
2072     */
2073    public void setClipChildren(boolean clipChildren) {
2074        setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren);
2075    }
2076
2077    /**
2078     * By default, children are clipped to the padding of the ViewGroup. This
2079     * allows view groups to override this behavior
2080     *
2081     * @param clipToPadding true to clip children to the padding of the
2082     *        group, false otherwise
2083     * @attr ref android.R.styleable#ViewGroup_clipToPadding
2084     */
2085    public void setClipToPadding(boolean clipToPadding) {
2086        setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
2087    }
2088
2089    /**
2090     * {@inheritDoc}
2091     */
2092    @Override
2093    public void dispatchSetSelected(boolean selected) {
2094        final View[] children = mChildren;
2095        final int count = mChildrenCount;
2096        for (int i = 0; i < count; i++) {
2097
2098            children[i].setSelected(selected);
2099        }
2100    }
2101
2102    /**
2103     * {@inheritDoc}
2104     */
2105    @Override
2106    public void dispatchSetActivated(boolean activated) {
2107        final View[] children = mChildren;
2108        final int count = mChildrenCount;
2109        for (int i = 0; i < count; i++) {
2110
2111            children[i].setActivated(activated);
2112        }
2113    }
2114
2115    @Override
2116    protected void dispatchSetPressed(boolean pressed) {
2117        final View[] children = mChildren;
2118        final int count = mChildrenCount;
2119        for (int i = 0; i < count; i++) {
2120            children[i].setPressed(pressed);
2121        }
2122    }
2123
2124    /**
2125     * When this property is set to true, this ViewGroup supports static transformations on
2126     * children; this causes
2127     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
2128     * invoked when a child is drawn.
2129     *
2130     * Any subclass overriding
2131     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
2132     * set this property to true.
2133     *
2134     * @param enabled True to enable static transformations on children, false otherwise.
2135     *
2136     * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS
2137     */
2138    protected void setStaticTransformationsEnabled(boolean enabled) {
2139        setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled);
2140    }
2141
2142    /**
2143     * {@inheritDoc}
2144     *
2145     * @see #setStaticTransformationsEnabled(boolean)
2146     */
2147    protected boolean getChildStaticTransformation(View child, Transformation t) {
2148        return false;
2149    }
2150
2151    /**
2152     * {@hide}
2153     */
2154    @Override
2155    protected View findViewTraversal(int id) {
2156        if (id == mID) {
2157            return this;
2158        }
2159
2160        final View[] where = mChildren;
2161        final int len = mChildrenCount;
2162
2163        for (int i = 0; i < len; i++) {
2164            View v = where[i];
2165
2166            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
2167                v = v.findViewById(id);
2168
2169                if (v != null) {
2170                    return v;
2171                }
2172            }
2173        }
2174
2175        return null;
2176    }
2177
2178    /**
2179     * {@hide}
2180     */
2181    @Override
2182    protected View findViewWithTagTraversal(Object tag) {
2183        if (tag != null && tag.equals(mTag)) {
2184            return this;
2185        }
2186
2187        final View[] where = mChildren;
2188        final int len = mChildrenCount;
2189
2190        for (int i = 0; i < len; i++) {
2191            View v = where[i];
2192
2193            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
2194                v = v.findViewWithTag(tag);
2195
2196                if (v != null) {
2197                    return v;
2198                }
2199            }
2200        }
2201
2202        return null;
2203    }
2204
2205    /**
2206     * Adds a child view. If no layout parameters are already set on the child, the
2207     * default parameters for this ViewGroup are set on the child.
2208     *
2209     * @param child the child view to add
2210     *
2211     * @see #generateDefaultLayoutParams()
2212     */
2213    public void addView(View child) {
2214        addView(child, -1);
2215    }
2216
2217    /**
2218     * Adds a child view. If no layout parameters are already set on the child, the
2219     * default parameters for this ViewGroup are set on the child.
2220     *
2221     * @param child the child view to add
2222     * @param index the position at which to add the child
2223     *
2224     * @see #generateDefaultLayoutParams()
2225     */
2226    public void addView(View child, int index) {
2227        LayoutParams params = child.getLayoutParams();
2228        if (params == null) {
2229            params = generateDefaultLayoutParams();
2230            if (params == null) {
2231                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
2232            }
2233        }
2234        addView(child, index, params);
2235    }
2236
2237    /**
2238     * Adds a child view with this ViewGroup's default layout parameters and the
2239     * specified width and height.
2240     *
2241     * @param child the child view to add
2242     */
2243    public void addView(View child, int width, int height) {
2244        final LayoutParams params = generateDefaultLayoutParams();
2245        params.width = width;
2246        params.height = height;
2247        addView(child, -1, params);
2248    }
2249
2250    /**
2251     * Adds a child view with the specified layout parameters.
2252     *
2253     * @param child the child view to add
2254     * @param params the layout parameters to set on the child
2255     */
2256    public void addView(View child, LayoutParams params) {
2257        addView(child, -1, params);
2258    }
2259
2260    /**
2261     * Adds a child view with the specified layout parameters.
2262     *
2263     * @param child the child view to add
2264     * @param index the position at which to add the child
2265     * @param params the layout parameters to set on the child
2266     */
2267    public void addView(View child, int index, LayoutParams params) {
2268        if (DBG) {
2269            System.out.println(this + " addView");
2270        }
2271
2272        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
2273        // therefore, we call requestLayout() on ourselves before, so that the child's request
2274        // will be blocked at our level
2275        requestLayout();
2276        invalidate();
2277        addViewInner(child, index, params, false);
2278    }
2279
2280    /**
2281     * {@inheritDoc}
2282     */
2283    public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
2284        if (!checkLayoutParams(params)) {
2285            throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this);
2286        }
2287        if (view.mParent != this) {
2288            throw new IllegalArgumentException("Given view not a child of " + this);
2289        }
2290        view.setLayoutParams(params);
2291    }
2292
2293    /**
2294     * {@inheritDoc}
2295     */
2296    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2297        return  p != null;
2298    }
2299
2300    /**
2301     * Interface definition for a callback to be invoked when the hierarchy
2302     * within this view changed. The hierarchy changes whenever a child is added
2303     * to or removed from this view.
2304     */
2305    public interface OnHierarchyChangeListener {
2306        /**
2307         * Called when a new child is added to a parent view.
2308         *
2309         * @param parent the view in which a child was added
2310         * @param child the new child view added in the hierarchy
2311         */
2312        void onChildViewAdded(View parent, View child);
2313
2314        /**
2315         * Called when a child is removed from a parent view.
2316         *
2317         * @param parent the view from which the child was removed
2318         * @param child the child removed from the hierarchy
2319         */
2320        void onChildViewRemoved(View parent, View child);
2321    }
2322
2323    /**
2324     * Register a callback to be invoked when a child is added to or removed
2325     * from this view.
2326     *
2327     * @param listener the callback to invoke on hierarchy change
2328     */
2329    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
2330        mOnHierarchyChangeListener = listener;
2331    }
2332
2333    /**
2334     * Adds a view during layout. This is useful if in your onLayout() method,
2335     * you need to add more views (as does the list view for example).
2336     *
2337     * If index is negative, it means put it at the end of the list.
2338     *
2339     * @param child the view to add to the group
2340     * @param index the index at which the child must be added
2341     * @param params the layout parameters to associate with the child
2342     * @return true if the child was added, false otherwise
2343     */
2344    protected boolean addViewInLayout(View child, int index, LayoutParams params) {
2345        return addViewInLayout(child, index, params, false);
2346    }
2347
2348    /**
2349     * Adds a view during layout. This is useful if in your onLayout() method,
2350     * you need to add more views (as does the list view for example).
2351     *
2352     * If index is negative, it means put it at the end of the list.
2353     *
2354     * @param child the view to add to the group
2355     * @param index the index at which the child must be added
2356     * @param params the layout parameters to associate with the child
2357     * @param preventRequestLayout if true, calling this method will not trigger a
2358     *        layout request on child
2359     * @return true if the child was added, false otherwise
2360     */
2361    protected boolean addViewInLayout(View child, int index, LayoutParams params,
2362            boolean preventRequestLayout) {
2363        child.mParent = null;
2364        addViewInner(child, index, params, preventRequestLayout);
2365        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN;
2366        return true;
2367    }
2368
2369    /**
2370     * Prevents the specified child to be laid out during the next layout pass.
2371     *
2372     * @param child the child on which to perform the cleanup
2373     */
2374    protected void cleanupLayoutState(View child) {
2375        child.mPrivateFlags &= ~View.FORCE_LAYOUT;
2376    }
2377
2378    private void addViewInner(View child, int index, LayoutParams params,
2379            boolean preventRequestLayout) {
2380
2381        if (child.getParent() != null) {
2382            throw new IllegalStateException("The specified child already has a parent. " +
2383                    "You must call removeView() on the child's parent first.");
2384        }
2385
2386        if (mTransition != null) {
2387            mTransition.childAdd(this, child);
2388        }
2389
2390        if (!checkLayoutParams(params)) {
2391            params = generateLayoutParams(params);
2392        }
2393
2394        if (preventRequestLayout) {
2395            child.mLayoutParams = params;
2396        } else {
2397            child.setLayoutParams(params);
2398        }
2399
2400        if (index < 0) {
2401            index = mChildrenCount;
2402        }
2403
2404        addInArray(child, index);
2405
2406        // tell our children
2407        if (preventRequestLayout) {
2408            child.assignParent(this);
2409        } else {
2410            child.mParent = this;
2411        }
2412
2413        if (child.hasFocus()) {
2414            requestChildFocus(child, child.findFocus());
2415        }
2416
2417        AttachInfo ai = mAttachInfo;
2418        if (ai != null) {
2419            boolean lastKeepOn = ai.mKeepScreenOn;
2420            ai.mKeepScreenOn = false;
2421            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
2422            if (ai.mKeepScreenOn) {
2423                needGlobalAttributesUpdate(true);
2424            }
2425            ai.mKeepScreenOn = lastKeepOn;
2426        }
2427
2428        if (mOnHierarchyChangeListener != null) {
2429            mOnHierarchyChangeListener.onChildViewAdded(this, child);
2430        }
2431
2432        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
2433            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
2434        }
2435    }
2436
2437    private void addInArray(View child, int index) {
2438        View[] children = mChildren;
2439        final int count = mChildrenCount;
2440        final int size = children.length;
2441        if (index == count) {
2442            if (size == count) {
2443                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
2444                System.arraycopy(children, 0, mChildren, 0, size);
2445                children = mChildren;
2446            }
2447            children[mChildrenCount++] = child;
2448        } else if (index < count) {
2449            if (size == count) {
2450                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
2451                System.arraycopy(children, 0, mChildren, 0, index);
2452                System.arraycopy(children, index, mChildren, index + 1, count - index);
2453                children = mChildren;
2454            } else {
2455                System.arraycopy(children, index, children, index + 1, count - index);
2456            }
2457            children[index] = child;
2458            mChildrenCount++;
2459        } else {
2460            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
2461        }
2462    }
2463
2464    // This method also sets the child's mParent to null
2465    private void removeFromArray(int index) {
2466        final View[] children = mChildren;
2467        if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
2468            children[index].mParent = null;
2469        }
2470        final int count = mChildrenCount;
2471        if (index == count - 1) {
2472            children[--mChildrenCount] = null;
2473        } else if (index >= 0 && index < count) {
2474            System.arraycopy(children, index + 1, children, index, count - index - 1);
2475            children[--mChildrenCount] = null;
2476        } else {
2477            throw new IndexOutOfBoundsException();
2478        }
2479    }
2480
2481    // This method also sets the children's mParent to null
2482    private void removeFromArray(int start, int count) {
2483        final View[] children = mChildren;
2484        final int childrenCount = mChildrenCount;
2485
2486        start = Math.max(0, start);
2487        final int end = Math.min(childrenCount, start + count);
2488
2489        if (start == end) {
2490            return;
2491        }
2492
2493        if (end == childrenCount) {
2494            for (int i = start; i < end; i++) {
2495                children[i].mParent = null;
2496                children[i] = null;
2497            }
2498        } else {
2499            for (int i = start; i < end; i++) {
2500                children[i].mParent = null;
2501            }
2502
2503            // Since we're looping above, we might as well do the copy, but is arraycopy()
2504            // faster than the extra 2 bounds checks we would do in the loop?
2505            System.arraycopy(children, end, children, start, childrenCount - end);
2506
2507            for (int i = childrenCount - (end - start); i < childrenCount; i++) {
2508                children[i] = null;
2509            }
2510        }
2511
2512        mChildrenCount -= (end - start);
2513    }
2514
2515    private void bindLayoutAnimation(View child) {
2516        Animation a = mLayoutAnimationController.getAnimationForView(child);
2517        child.setAnimation(a);
2518    }
2519
2520    /**
2521     * Subclasses should override this method to set layout animation
2522     * parameters on the supplied child.
2523     *
2524     * @param child the child to associate with animation parameters
2525     * @param params the child's layout parameters which hold the animation
2526     *        parameters
2527     * @param index the index of the child in the view group
2528     * @param count the number of children in the view group
2529     */
2530    protected void attachLayoutAnimationParameters(View child,
2531            LayoutParams params, int index, int count) {
2532        LayoutAnimationController.AnimationParameters animationParams =
2533                    params.layoutAnimationParameters;
2534        if (animationParams == null) {
2535            animationParams = new LayoutAnimationController.AnimationParameters();
2536            params.layoutAnimationParameters = animationParams;
2537        }
2538
2539        animationParams.count = count;
2540        animationParams.index = index;
2541    }
2542
2543    /**
2544     * {@inheritDoc}
2545     */
2546    public void removeView(View view) {
2547        removeViewInternal(view);
2548        requestLayout();
2549        invalidate();
2550    }
2551
2552    /**
2553     * Removes a view during layout. This is useful if in your onLayout() method,
2554     * you need to remove more views.
2555     *
2556     * @param view the view to remove from the group
2557     */
2558    public void removeViewInLayout(View view) {
2559        removeViewInternal(view);
2560    }
2561
2562    /**
2563     * Removes a range of views during layout. This is useful if in your onLayout() method,
2564     * you need to remove more views.
2565     *
2566     * @param start the index of the first view to remove from the group
2567     * @param count the number of views to remove from the group
2568     */
2569    public void removeViewsInLayout(int start, int count) {
2570        removeViewsInternal(start, count);
2571    }
2572
2573    /**
2574     * Removes the view at the specified position in the group.
2575     *
2576     * @param index the position in the group of the view to remove
2577     */
2578    public void removeViewAt(int index) {
2579        removeViewInternal(index, getChildAt(index));
2580        requestLayout();
2581        invalidate();
2582    }
2583
2584    /**
2585     * Removes the specified range of views from the group.
2586     *
2587     * @param start the first position in the group of the range of views to remove
2588     * @param count the number of views to remove
2589     */
2590    public void removeViews(int start, int count) {
2591        removeViewsInternal(start, count);
2592        requestLayout();
2593        invalidate();
2594    }
2595
2596    private void removeViewInternal(View view) {
2597        final int index = indexOfChild(view);
2598        if (index >= 0) {
2599            removeViewInternal(index, view);
2600        }
2601    }
2602
2603    private void removeViewInternal(int index, View view) {
2604
2605        if (mTransition != null) {
2606            mTransition.childRemove(this, view);
2607        }
2608
2609        boolean clearChildFocus = false;
2610        if (view == mFocused) {
2611            view.clearFocusForRemoval();
2612            clearChildFocus = true;
2613        }
2614
2615        if (view.getAnimation() != null ||
2616                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
2617            addDisappearingView(view);
2618        } else if (view.mAttachInfo != null) {
2619           view.dispatchDetachedFromWindow();
2620        }
2621
2622        if (mOnHierarchyChangeListener != null) {
2623            mOnHierarchyChangeListener.onChildViewRemoved(this, view);
2624        }
2625
2626        needGlobalAttributesUpdate(false);
2627
2628        removeFromArray(index);
2629
2630        if (clearChildFocus) {
2631            clearChildFocus(view);
2632        }
2633    }
2634
2635    /**
2636     * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
2637     * not null, changes in layout which occur because of children being added to or removed from
2638     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
2639     * object. By default, the transition object is null (so layout changes are not animated).
2640     *
2641     * @param transition The LayoutTransition object that will animated changes in layout. A value
2642     * of <code>null</code> means no transition will run on layout changes.
2643     * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
2644     */
2645    public void setLayoutTransition(LayoutTransition transition) {
2646        if (mTransition != null) {
2647            mTransition.removeTransitionListener(mLayoutTransitionListener);
2648        }
2649        mTransition = transition;
2650        if (mTransition != null) {
2651            mTransition.addTransitionListener(mLayoutTransitionListener);
2652        }
2653    }
2654
2655    /**
2656     * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
2657     * not null, changes in layout which occur because of children being added to or removed from
2658     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
2659     * object. By default, the transition object is null (so layout changes are not animated).
2660     *
2661     * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
2662     * A value of <code>null</code> means no transition will run on layout changes.
2663     */
2664    public LayoutTransition getLayoutTransition() {
2665        return mTransition;
2666    }
2667
2668    private void removeViewsInternal(int start, int count) {
2669        final OnHierarchyChangeListener onHierarchyChangeListener = mOnHierarchyChangeListener;
2670        final boolean notifyListener = onHierarchyChangeListener != null;
2671        final View focused = mFocused;
2672        final boolean detach = mAttachInfo != null;
2673        View clearChildFocus = null;
2674
2675        final View[] children = mChildren;
2676        final int end = start + count;
2677
2678        for (int i = start; i < end; i++) {
2679            final View view = children[i];
2680
2681            if (mTransition != null) {
2682                mTransition.childRemove(this, view);
2683            }
2684
2685            if (view == focused) {
2686                view.clearFocusForRemoval();
2687                clearChildFocus = view;
2688            }
2689
2690            if (view.getAnimation() != null ||
2691                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
2692                addDisappearingView(view);
2693            } else if (detach) {
2694               view.dispatchDetachedFromWindow();
2695            }
2696
2697            needGlobalAttributesUpdate(false);
2698
2699            if (notifyListener) {
2700                onHierarchyChangeListener.onChildViewRemoved(this, view);
2701            }
2702        }
2703
2704        removeFromArray(start, count);
2705
2706        if (clearChildFocus != null) {
2707            clearChildFocus(clearChildFocus);
2708        }
2709    }
2710
2711    /**
2712     * Call this method to remove all child views from the
2713     * ViewGroup.
2714     */
2715    public void removeAllViews() {
2716        removeAllViewsInLayout();
2717        requestLayout();
2718        invalidate();
2719    }
2720
2721    /**
2722     * Called by a ViewGroup subclass to remove child views from itself,
2723     * when it must first know its size on screen before it can calculate how many
2724     * child views it will render. An example is a Gallery or a ListView, which
2725     * may "have" 50 children, but actually only render the number of children
2726     * that can currently fit inside the object on screen. Do not call
2727     * this method unless you are extending ViewGroup and understand the
2728     * view measuring and layout pipeline.
2729     */
2730    public void removeAllViewsInLayout() {
2731        final int count = mChildrenCount;
2732        if (count <= 0) {
2733            return;
2734        }
2735
2736        final View[] children = mChildren;
2737        mChildrenCount = 0;
2738
2739        final OnHierarchyChangeListener listener = mOnHierarchyChangeListener;
2740        final boolean notify = listener != null;
2741        final View focused = mFocused;
2742        final boolean detach = mAttachInfo != null;
2743        View clearChildFocus = null;
2744
2745        needGlobalAttributesUpdate(false);
2746
2747        for (int i = count - 1; i >= 0; i--) {
2748            final View view = children[i];
2749
2750            if (mTransition != null) {
2751                mTransition.childRemove(this, view);
2752            }
2753
2754            if (view == focused) {
2755                view.clearFocusForRemoval();
2756                clearChildFocus = view;
2757            }
2758
2759            if (view.getAnimation() != null ||
2760                    (mTransitioningViews != null && mTransitioningViews.contains(view))) {
2761                addDisappearingView(view);
2762            } else if (detach) {
2763               view.dispatchDetachedFromWindow();
2764            }
2765
2766            if (notify) {
2767                listener.onChildViewRemoved(this, view);
2768            }
2769
2770            view.mParent = null;
2771            children[i] = null;
2772        }
2773
2774        if (clearChildFocus != null) {
2775            clearChildFocus(clearChildFocus);
2776        }
2777
2778        mGroupFlags &= ~FLAG_CHILD_HAS_OVERLAY;
2779    }
2780
2781    /**
2782     * Finishes the removal of a detached view. This method will dispatch the detached from
2783     * window event and notify the hierarchy change listener.
2784     *
2785     * @param child the child to be definitely removed from the view hierarchy
2786     * @param animate if true and the view has an animation, the view is placed in the
2787     *                disappearing views list, otherwise, it is detached from the window
2788     *
2789     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2790     * @see #detachAllViewsFromParent()
2791     * @see #detachViewFromParent(View)
2792     * @see #detachViewFromParent(int)
2793     */
2794    protected void removeDetachedView(View child, boolean animate) {
2795        if (mTransition != null) {
2796            mTransition.childRemove(this, child);
2797        }
2798
2799        if (child == mFocused) {
2800            child.clearFocus();
2801        }
2802
2803        if ((animate && child.getAnimation() != null) ||
2804                (mTransitioningViews != null && mTransitioningViews.contains(child))) {
2805            addDisappearingView(child);
2806        } else if (child.mAttachInfo != null) {
2807            child.dispatchDetachedFromWindow();
2808        }
2809
2810        if (mOnHierarchyChangeListener != null) {
2811            mOnHierarchyChangeListener.onChildViewRemoved(this, child);
2812        }
2813    }
2814
2815    /**
2816     * Attaches a view to this view group. Attaching a view assigns this group as the parent,
2817     * sets the layout parameters and puts the view in the list of children so it can be retrieved
2818     * by calling {@link #getChildAt(int)}.
2819     *
2820     * This method should be called only for view which were detached from their parent.
2821     *
2822     * @param child the child to attach
2823     * @param index the index at which the child should be attached
2824     * @param params the layout parameters of the child
2825     *
2826     * @see #removeDetachedView(View, boolean)
2827     * @see #detachAllViewsFromParent()
2828     * @see #detachViewFromParent(View)
2829     * @see #detachViewFromParent(int)
2830     */
2831    protected void attachViewToParent(View child, int index, LayoutParams params) {
2832        child.mLayoutParams = params;
2833
2834        if (index < 0) {
2835            index = mChildrenCount;
2836        }
2837
2838        addInArray(child, index);
2839
2840        child.mParent = this;
2841        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) | DRAWN;
2842
2843        if (child.hasFocus()) {
2844            requestChildFocus(child, child.findFocus());
2845        }
2846    }
2847
2848    /**
2849     * Detaches a view from its parent. Detaching a view should be temporary and followed
2850     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2851     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
2852     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2853     *
2854     * @param child the child to detach
2855     *
2856     * @see #detachViewFromParent(int)
2857     * @see #detachViewsFromParent(int, int)
2858     * @see #detachAllViewsFromParent()
2859     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2860     * @see #removeDetachedView(View, boolean)
2861     */
2862    protected void detachViewFromParent(View child) {
2863        removeFromArray(indexOfChild(child));
2864    }
2865
2866    /**
2867     * Detaches a view from its parent. Detaching a view should be temporary and followed
2868     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2869     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
2870     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2871     *
2872     * @param index the index of the child to detach
2873     *
2874     * @see #detachViewFromParent(View)
2875     * @see #detachAllViewsFromParent()
2876     * @see #detachViewsFromParent(int, int)
2877     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2878     * @see #removeDetachedView(View, boolean)
2879     */
2880    protected void detachViewFromParent(int index) {
2881        removeFromArray(index);
2882    }
2883
2884    /**
2885     * Detaches a range of view from their parent. Detaching a view should be temporary and followed
2886     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2887     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its
2888     * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2889     *
2890     * @param start the first index of the childrend range to detach
2891     * @param count the number of children to detach
2892     *
2893     * @see #detachViewFromParent(View)
2894     * @see #detachViewFromParent(int)
2895     * @see #detachAllViewsFromParent()
2896     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2897     * @see #removeDetachedView(View, boolean)
2898     */
2899    protected void detachViewsFromParent(int start, int count) {
2900        removeFromArray(start, count);
2901    }
2902
2903    /**
2904     * Detaches all views from the parent. Detaching a view should be temporary and followed
2905     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2906     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
2907     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2908     *
2909     * @see #detachViewFromParent(View)
2910     * @see #detachViewFromParent(int)
2911     * @see #detachViewsFromParent(int, int)
2912     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2913     * @see #removeDetachedView(View, boolean)
2914     */
2915    protected void detachAllViewsFromParent() {
2916        final int count = mChildrenCount;
2917        if (count <= 0) {
2918            return;
2919        }
2920
2921        final View[] children = mChildren;
2922        mChildrenCount = 0;
2923
2924        for (int i = count - 1; i >= 0; i--) {
2925            children[i].mParent = null;
2926            children[i] = null;
2927        }
2928    }
2929
2930    /**
2931     * Don't call or override this method. It is used for the implementation of
2932     * the view hierarchy.
2933     */
2934    public final void invalidateChild(View child, final Rect dirty) {
2935        if (ViewDebug.TRACE_HIERARCHY) {
2936            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD);
2937        }
2938
2939        ViewParent parent = this;
2940
2941        final AttachInfo attachInfo = mAttachInfo;
2942        if (attachInfo != null) {
2943            final int[] location = attachInfo.mInvalidateChildLocation;
2944            location[CHILD_LEFT_INDEX] = child.mLeft;
2945            location[CHILD_TOP_INDEX] = child.mTop;
2946            Matrix childMatrix = child.getMatrix();
2947            if (!childMatrix.isIdentity()) {
2948                RectF boundingRect = attachInfo.mTmpTransformRect;
2949                boundingRect.set(dirty);
2950                childMatrix.mapRect(boundingRect);
2951                dirty.set((int) boundingRect.left, (int) boundingRect.top,
2952                        (int) (boundingRect.right + 0.5f),
2953                        (int) (boundingRect.bottom + 0.5f));
2954            }
2955
2956            // If the child is drawing an animation, we want to copy this flag onto
2957            // ourselves and the parent to make sure the invalidate request goes
2958            // through
2959            final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;
2960
2961            // Check whether the child that requests the invalidate is fully opaque
2962            final boolean isOpaque = child.isOpaque() && !drawAnimation &&
2963                    child.getAnimation() != null;
2964            // Mark the child as dirty, using the appropriate flag
2965            // Make sure we do not set both flags at the same time
2966            final int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
2967
2968            do {
2969                View view = null;
2970                if (parent instanceof View) {
2971                    view = (View) parent;
2972                }
2973
2974                if (drawAnimation) {
2975                    if (view != null) {
2976                        view.mPrivateFlags |= DRAW_ANIMATION;
2977                    } else if (parent instanceof ViewRoot) {
2978                        ((ViewRoot) parent).mIsAnimating = true;
2979                    }
2980                }
2981
2982                // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
2983                // flag coming from the child that initiated the invalidate
2984                if (view != null && (view.mPrivateFlags & DIRTY_MASK) != DIRTY) {
2985                    view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;
2986                }
2987
2988                parent = parent.invalidateChildInParent(location, dirty);
2989                if (view != null) {
2990                    // Account for transform on current parent
2991                    Matrix m = view.getMatrix();
2992                    if (!m.isIdentity()) {
2993                        RectF boundingRect = attachInfo.mTmpTransformRect;
2994                        boundingRect.set(dirty);
2995                        m.mapRect(boundingRect);
2996                        dirty.set((int) boundingRect.left, (int) boundingRect.top,
2997                                (int) (boundingRect.right + 0.5f),
2998                                (int) (boundingRect.bottom + 0.5f));
2999                    }
3000                }
3001            } while (parent != null);
3002        }
3003    }
3004
3005    /**
3006     * Don't call or override this method. It is used for the implementation of
3007     * the view hierarchy.
3008     *
3009     * This implementation returns null if this ViewGroup does not have a parent,
3010     * if this ViewGroup is already fully invalidated or if the dirty rectangle
3011     * does not intersect with this ViewGroup's bounds.
3012     */
3013    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
3014        if (ViewDebug.TRACE_HIERARCHY) {
3015            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD_IN_PARENT);
3016        }
3017
3018        if ((mPrivateFlags & DRAWN) == DRAWN) {
3019            if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
3020                        FLAG_OPTIMIZE_INVALIDATE) {
3021                dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
3022                        location[CHILD_TOP_INDEX] - mScrollY);
3023
3024                final int left = mLeft;
3025                final int top = mTop;
3026
3027                if ((mGroupFlags & FLAG_CHILD_HAS_OVERLAY) == FLAG_CHILD_HAS_OVERLAY ||
3028                        dirty.intersect(0, 0, mRight - left, mBottom - top) ||
3029                        (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
3030                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
3031
3032                    location[CHILD_LEFT_INDEX] = left;
3033                    location[CHILD_TOP_INDEX] = top;
3034
3035                    return mParent;
3036                }
3037            } else {
3038                mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
3039
3040                location[CHILD_LEFT_INDEX] = mLeft;
3041                location[CHILD_TOP_INDEX] = mTop;
3042
3043                dirty.set(0, 0, mRight - location[CHILD_LEFT_INDEX],
3044                        mBottom - location[CHILD_TOP_INDEX]);
3045
3046                return mParent;
3047            }
3048        }
3049
3050        return null;
3051    }
3052
3053    /**
3054     * Offset a rectangle that is in a descendant's coordinate
3055     * space into our coordinate space.
3056     * @param descendant A descendant of this view
3057     * @param rect A rectangle defined in descendant's coordinate space.
3058     */
3059    public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) {
3060        offsetRectBetweenParentAndChild(descendant, rect, true, false);
3061    }
3062
3063    /**
3064     * Offset a rectangle that is in our coordinate space into an ancestor's
3065     * coordinate space.
3066     * @param descendant A descendant of this view
3067     * @param rect A rectangle defined in descendant's coordinate space.
3068     */
3069    public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) {
3070        offsetRectBetweenParentAndChild(descendant, rect, false, false);
3071    }
3072
3073    /**
3074     * Helper method that offsets a rect either from parent to descendant or
3075     * descendant to parent.
3076     */
3077    void offsetRectBetweenParentAndChild(View descendant, Rect rect,
3078            boolean offsetFromChildToParent, boolean clipToBounds) {
3079
3080        // already in the same coord system :)
3081        if (descendant == this) {
3082            return;
3083        }
3084
3085        ViewParent theParent = descendant.mParent;
3086
3087        // search and offset up to the parent
3088        while ((theParent != null)
3089                && (theParent instanceof View)
3090                && (theParent != this)) {
3091
3092            if (offsetFromChildToParent) {
3093                rect.offset(descendant.mLeft - descendant.mScrollX,
3094                        descendant.mTop - descendant.mScrollY);
3095                if (clipToBounds) {
3096                    View p = (View) theParent;
3097                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
3098                }
3099            } else {
3100                if (clipToBounds) {
3101                    View p = (View) theParent;
3102                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
3103                }
3104                rect.offset(descendant.mScrollX - descendant.mLeft,
3105                        descendant.mScrollY - descendant.mTop);
3106            }
3107
3108            descendant = (View) theParent;
3109            theParent = descendant.mParent;
3110        }
3111
3112        // now that we are up to this view, need to offset one more time
3113        // to get into our coordinate space
3114        if (theParent == this) {
3115            if (offsetFromChildToParent) {
3116                rect.offset(descendant.mLeft - descendant.mScrollX,
3117                        descendant.mTop - descendant.mScrollY);
3118            } else {
3119                rect.offset(descendant.mScrollX - descendant.mLeft,
3120                        descendant.mScrollY - descendant.mTop);
3121            }
3122        } else {
3123            throw new IllegalArgumentException("parameter must be a descendant of this view");
3124        }
3125    }
3126
3127    /**
3128     * Offset the vertical location of all children of this view by the specified number of pixels.
3129     *
3130     * @param offset the number of pixels to offset
3131     *
3132     * @hide
3133     */
3134    public void offsetChildrenTopAndBottom(int offset) {
3135        final int count = mChildrenCount;
3136        final View[] children = mChildren;
3137
3138        for (int i = 0; i < count; i++) {
3139            final View v = children[i];
3140            v.mTop += offset;
3141            v.mBottom += offset;
3142        }
3143    }
3144
3145    /**
3146     * {@inheritDoc}
3147     */
3148    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
3149        int dx = child.mLeft - mScrollX;
3150        int dy = child.mTop - mScrollY;
3151        if (offset != null) {
3152            offset.x += dx;
3153            offset.y += dy;
3154        }
3155        r.offset(dx, dy);
3156        return r.intersect(0, 0, mRight - mLeft, mBottom - mTop) &&
3157               (mParent == null || mParent.getChildVisibleRect(this, r, offset));
3158    }
3159
3160    /**
3161     * {@inheritDoc}
3162     */
3163    @Override
3164    protected abstract void onLayout(boolean changed,
3165            int l, int t, int r, int b);
3166
3167    /**
3168     * Indicates whether the view group has the ability to animate its children
3169     * after the first layout.
3170     *
3171     * @return true if the children can be animated, false otherwise
3172     */
3173    protected boolean canAnimate() {
3174        return mLayoutAnimationController != null;
3175    }
3176
3177    /**
3178     * Runs the layout animation. Calling this method triggers a relayout of
3179     * this view group.
3180     */
3181    public void startLayoutAnimation() {
3182        if (mLayoutAnimationController != null) {
3183            mGroupFlags |= FLAG_RUN_ANIMATION;
3184            requestLayout();
3185        }
3186    }
3187
3188    /**
3189     * Schedules the layout animation to be played after the next layout pass
3190     * of this view group. This can be used to restart the layout animation
3191     * when the content of the view group changes or when the activity is
3192     * paused and resumed.
3193     */
3194    public void scheduleLayoutAnimation() {
3195        mGroupFlags |= FLAG_RUN_ANIMATION;
3196    }
3197
3198    /**
3199     * Sets the layout animation controller used to animate the group's
3200     * children after the first layout.
3201     *
3202     * @param controller the animation controller
3203     */
3204    public void setLayoutAnimation(LayoutAnimationController controller) {
3205        mLayoutAnimationController = controller;
3206        if (mLayoutAnimationController != null) {
3207            mGroupFlags |= FLAG_RUN_ANIMATION;
3208        }
3209    }
3210
3211    /**
3212     * Returns the layout animation controller used to animate the group's
3213     * children.
3214     *
3215     * @return the current animation controller
3216     */
3217    public LayoutAnimationController getLayoutAnimation() {
3218        return mLayoutAnimationController;
3219    }
3220
3221    /**
3222     * Indicates whether the children's drawing cache is used during a layout
3223     * animation. By default, the drawing cache is enabled but this will prevent
3224     * nested layout animations from working. To nest animations, you must disable
3225     * the cache.
3226     *
3227     * @return true if the animation cache is enabled, false otherwise
3228     *
3229     * @see #setAnimationCacheEnabled(boolean)
3230     * @see View#setDrawingCacheEnabled(boolean)
3231     */
3232    @ViewDebug.ExportedProperty
3233    public boolean isAnimationCacheEnabled() {
3234        return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
3235    }
3236
3237    /**
3238     * Enables or disables the children's drawing cache during a layout animation.
3239     * By default, the drawing cache is enabled but this will prevent nested
3240     * layout animations from working. To nest animations, you must disable the
3241     * cache.
3242     *
3243     * @param enabled true to enable the animation cache, false otherwise
3244     *
3245     * @see #isAnimationCacheEnabled()
3246     * @see View#setDrawingCacheEnabled(boolean)
3247     */
3248    public void setAnimationCacheEnabled(boolean enabled) {
3249        setBooleanFlag(FLAG_ANIMATION_CACHE, enabled);
3250    }
3251
3252    /**
3253     * Indicates whether this ViewGroup will always try to draw its children using their
3254     * drawing cache. By default this property is enabled.
3255     *
3256     * @return true if the animation cache is enabled, false otherwise
3257     *
3258     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
3259     * @see #setChildrenDrawnWithCacheEnabled(boolean)
3260     * @see View#setDrawingCacheEnabled(boolean)
3261     */
3262    @ViewDebug.ExportedProperty(category = "drawing")
3263    public boolean isAlwaysDrawnWithCacheEnabled() {
3264        return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE;
3265    }
3266
3267    /**
3268     * Indicates whether this ViewGroup will always try to draw its children using their
3269     * drawing cache. This property can be set to true when the cache rendering is
3270     * slightly different from the children's normal rendering. Renderings can be different,
3271     * for instance, when the cache's quality is set to low.
3272     *
3273     * When this property is disabled, the ViewGroup will use the drawing cache of its
3274     * children only when asked to. It's usually the task of subclasses to tell ViewGroup
3275     * when to start using the drawing cache and when to stop using it.
3276     *
3277     * @param always true to always draw with the drawing cache, false otherwise
3278     *
3279     * @see #isAlwaysDrawnWithCacheEnabled()
3280     * @see #setChildrenDrawnWithCacheEnabled(boolean)
3281     * @see View#setDrawingCacheEnabled(boolean)
3282     * @see View#setDrawingCacheQuality(int)
3283     */
3284    public void setAlwaysDrawnWithCacheEnabled(boolean always) {
3285        setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always);
3286    }
3287
3288    /**
3289     * Indicates whether the ViewGroup is currently drawing its children using
3290     * their drawing cache.
3291     *
3292     * @return true if children should be drawn with their cache, false otherwise
3293     *
3294     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
3295     * @see #setChildrenDrawnWithCacheEnabled(boolean)
3296     */
3297    @ViewDebug.ExportedProperty(category = "drawing")
3298    protected boolean isChildrenDrawnWithCacheEnabled() {
3299        return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE;
3300    }
3301
3302    /**
3303     * Tells the ViewGroup to draw its children using their drawing cache. This property
3304     * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache
3305     * will be used only if it has been enabled.
3306     *
3307     * Subclasses should call this method to start and stop using the drawing cache when
3308     * they perform performance sensitive operations, like scrolling or animating.
3309     *
3310     * @param enabled true if children should be drawn with their cache, false otherwise
3311     *
3312     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
3313     * @see #isChildrenDrawnWithCacheEnabled()
3314     */
3315    protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
3316        setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled);
3317    }
3318
3319    /**
3320     * Indicates whether the ViewGroup is drawing its children in the order defined by
3321     * {@link #getChildDrawingOrder(int, int)}.
3322     *
3323     * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)},
3324     *         false otherwise
3325     *
3326     * @see #setChildrenDrawingOrderEnabled(boolean)
3327     * @see #getChildDrawingOrder(int, int)
3328     */
3329    @ViewDebug.ExportedProperty(category = "drawing")
3330    protected boolean isChildrenDrawingOrderEnabled() {
3331        return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER;
3332    }
3333
3334    /**
3335     * Tells the ViewGroup whether to draw its children in the order defined by the method
3336     * {@link #getChildDrawingOrder(int, int)}.
3337     *
3338     * @param enabled true if the order of the children when drawing is determined by
3339     *        {@link #getChildDrawingOrder(int, int)}, false otherwise
3340     *
3341     * @see #isChildrenDrawingOrderEnabled()
3342     * @see #getChildDrawingOrder(int, int)
3343     */
3344    protected void setChildrenDrawingOrderEnabled(boolean enabled) {
3345        setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled);
3346    }
3347
3348    private void setBooleanFlag(int flag, boolean value) {
3349        if (value) {
3350            mGroupFlags |= flag;
3351        } else {
3352            mGroupFlags &= ~flag;
3353        }
3354    }
3355
3356    /**
3357     * Returns an integer indicating what types of drawing caches are kept in memory.
3358     *
3359     * @see #setPersistentDrawingCache(int)
3360     * @see #setAnimationCacheEnabled(boolean)
3361     *
3362     * @return one or a combination of {@link #PERSISTENT_NO_CACHE},
3363     *         {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
3364     *         and {@link #PERSISTENT_ALL_CACHES}
3365     */
3366    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
3367        @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE,        to = "NONE"),
3368        @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"),
3369        @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"),
3370        @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES,      to = "ALL")
3371    })
3372    public int getPersistentDrawingCache() {
3373        return mPersistentDrawingCache;
3374    }
3375
3376    /**
3377     * Indicates what types of drawing caches should be kept in memory after
3378     * they have been created.
3379     *
3380     * @see #getPersistentDrawingCache()
3381     * @see #setAnimationCacheEnabled(boolean)
3382     *
3383     * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE},
3384     *        {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
3385     *        and {@link #PERSISTENT_ALL_CACHES}
3386     */
3387    public void setPersistentDrawingCache(int drawingCacheToKeep) {
3388        mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES;
3389    }
3390
3391    /**
3392     * Returns a new set of layout parameters based on the supplied attributes set.
3393     *
3394     * @param attrs the attributes to build the layout parameters from
3395     *
3396     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
3397     *         of its descendants
3398     */
3399    public LayoutParams generateLayoutParams(AttributeSet attrs) {
3400        return new LayoutParams(getContext(), attrs);
3401    }
3402
3403    /**
3404     * Returns a safe set of layout parameters based on the supplied layout params.
3405     * When a ViewGroup is passed a View whose layout params do not pass the test of
3406     * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
3407     * is invoked. This method should return a new set of layout params suitable for
3408     * this ViewGroup, possibly by copying the appropriate attributes from the
3409     * specified set of layout params.
3410     *
3411     * @param p The layout parameters to convert into a suitable set of layout parameters
3412     *          for this ViewGroup.
3413     *
3414     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
3415     *         of its descendants
3416     */
3417    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
3418        return p;
3419    }
3420
3421    /**
3422     * Returns a set of default layout parameters. These parameters are requested
3423     * when the View passed to {@link #addView(View)} has no layout parameters
3424     * already set. If null is returned, an exception is thrown from addView.
3425     *
3426     * @return a set of default layout parameters or null
3427     */
3428    protected LayoutParams generateDefaultLayoutParams() {
3429        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
3430    }
3431
3432    /**
3433     * @hide
3434     */
3435    @Override
3436    protected boolean dispatchConsistencyCheck(int consistency) {
3437        boolean result = super.dispatchConsistencyCheck(consistency);
3438
3439        final int count = mChildrenCount;
3440        final View[] children = mChildren;
3441        for (int i = 0; i < count; i++) {
3442            if (!children[i].dispatchConsistencyCheck(consistency)) result = false;
3443        }
3444
3445        return result;
3446    }
3447
3448    /**
3449     * @hide
3450     */
3451    @Override
3452    protected boolean onConsistencyCheck(int consistency) {
3453        boolean result = super.onConsistencyCheck(consistency);
3454
3455        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
3456        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
3457
3458        if (checkLayout) {
3459            final int count = mChildrenCount;
3460            final View[] children = mChildren;
3461            for (int i = 0; i < count; i++) {
3462                if (children[i].getParent() != this) {
3463                    result = false;
3464                    android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
3465                            "View " + children[i] + " has no parent/a parent that is not " + this);
3466                }
3467            }
3468        }
3469
3470        if (checkDrawing) {
3471            // If this group is dirty, check that the parent is dirty as well
3472            if ((mPrivateFlags & DIRTY_MASK) != 0) {
3473                final ViewParent parent = getParent();
3474                if (parent != null && !(parent instanceof ViewRoot)) {
3475                    if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) {
3476                        result = false;
3477                        android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
3478                                "ViewGroup " + this + " is dirty but its parent is not: " + this);
3479                    }
3480                }
3481            }
3482        }
3483
3484        return result;
3485    }
3486
3487    /**
3488     * {@inheritDoc}
3489     */
3490    @Override
3491    protected void debug(int depth) {
3492        super.debug(depth);
3493        String output;
3494
3495        if (mFocused != null) {
3496            output = debugIndent(depth);
3497            output += "mFocused";
3498            Log.d(VIEW_LOG_TAG, output);
3499        }
3500        if (mChildrenCount != 0) {
3501            output = debugIndent(depth);
3502            output += "{";
3503            Log.d(VIEW_LOG_TAG, output);
3504        }
3505        int count = mChildrenCount;
3506        for (int i = 0; i < count; i++) {
3507            View child = mChildren[i];
3508            child.debug(depth + 1);
3509        }
3510
3511        if (mChildrenCount != 0) {
3512            output = debugIndent(depth);
3513            output += "}";
3514            Log.d(VIEW_LOG_TAG, output);
3515        }
3516    }
3517
3518    /**
3519     * Returns the position in the group of the specified child view.
3520     *
3521     * @param child the view for which to get the position
3522     * @return a positive integer representing the position of the view in the
3523     *         group, or -1 if the view does not exist in the group
3524     */
3525    public int indexOfChild(View child) {
3526        final int count = mChildrenCount;
3527        final View[] children = mChildren;
3528        for (int i = 0; i < count; i++) {
3529            if (children[i] == child) {
3530                return i;
3531            }
3532        }
3533        return -1;
3534    }
3535
3536    /**
3537     * Returns the number of children in the group.
3538     *
3539     * @return a positive integer representing the number of children in
3540     *         the group
3541     */
3542    public int getChildCount() {
3543        return mChildrenCount;
3544    }
3545
3546    /**
3547     * Returns the view at the specified position in the group.
3548     *
3549     * @param index the position at which to get the view from
3550     * @return the view at the specified position or null if the position
3551     *         does not exist within the group
3552     */
3553    public View getChildAt(int index) {
3554        try {
3555            return mChildren[index];
3556        } catch (IndexOutOfBoundsException ex) {
3557            return null;
3558        }
3559    }
3560
3561    /**
3562     * Ask all of the children of this view to measure themselves, taking into
3563     * account both the MeasureSpec requirements for this view and its padding.
3564     * We skip children that are in the GONE state The heavy lifting is done in
3565     * getChildMeasureSpec.
3566     *
3567     * @param widthMeasureSpec The width requirements for this view
3568     * @param heightMeasureSpec The height requirements for this view
3569     */
3570    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
3571        final int size = mChildrenCount;
3572        final View[] children = mChildren;
3573        for (int i = 0; i < size; ++i) {
3574            final View child = children[i];
3575            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
3576                measureChild(child, widthMeasureSpec, heightMeasureSpec);
3577            }
3578        }
3579    }
3580
3581    /**
3582     * Ask one of the children of this view to measure itself, taking into
3583     * account both the MeasureSpec requirements for this view and its padding.
3584     * The heavy lifting is done in getChildMeasureSpec.
3585     *
3586     * @param child The child to measure
3587     * @param parentWidthMeasureSpec The width requirements for this view
3588     * @param parentHeightMeasureSpec The height requirements for this view
3589     */
3590    protected void measureChild(View child, int parentWidthMeasureSpec,
3591            int parentHeightMeasureSpec) {
3592        final LayoutParams lp = child.getLayoutParams();
3593
3594        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
3595                mPaddingLeft + mPaddingRight, lp.width);
3596        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
3597                mPaddingTop + mPaddingBottom, lp.height);
3598
3599        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
3600    }
3601
3602    /**
3603     * Ask one of the children of this view to measure itself, taking into
3604     * account both the MeasureSpec requirements for this view and its padding
3605     * and margins. The child must have MarginLayoutParams The heavy lifting is
3606     * done in getChildMeasureSpec.
3607     *
3608     * @param child The child to measure
3609     * @param parentWidthMeasureSpec The width requirements for this view
3610     * @param widthUsed Extra space that has been used up by the parent
3611     *        horizontally (possibly by other children of the parent)
3612     * @param parentHeightMeasureSpec The height requirements for this view
3613     * @param heightUsed Extra space that has been used up by the parent
3614     *        vertically (possibly by other children of the parent)
3615     */
3616    protected void measureChildWithMargins(View child,
3617            int parentWidthMeasureSpec, int widthUsed,
3618            int parentHeightMeasureSpec, int heightUsed) {
3619        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
3620
3621        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
3622                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
3623                        + widthUsed, lp.width);
3624        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
3625                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
3626                        + heightUsed, lp.height);
3627
3628        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
3629    }
3630
3631    /**
3632     * Does the hard part of measureChildren: figuring out the MeasureSpec to
3633     * pass to a particular child. This method figures out the right MeasureSpec
3634     * for one dimension (height or width) of one child view.
3635     *
3636     * The goal is to combine information from our MeasureSpec with the
3637     * LayoutParams of the child to get the best possible results. For example,
3638     * if the this view knows its size (because its MeasureSpec has a mode of
3639     * EXACTLY), and the child has indicated in its LayoutParams that it wants
3640     * to be the same size as the parent, the parent should ask the child to
3641     * layout given an exact size.
3642     *
3643     * @param spec The requirements for this view
3644     * @param padding The padding of this view for the current dimension and
3645     *        margins, if applicable
3646     * @param childDimension How big the child wants to be in the current
3647     *        dimension
3648     * @return a MeasureSpec integer for the child
3649     */
3650    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
3651        int specMode = MeasureSpec.getMode(spec);
3652        int specSize = MeasureSpec.getSize(spec);
3653
3654        int size = Math.max(0, specSize - padding);
3655
3656        int resultSize = 0;
3657        int resultMode = 0;
3658
3659        switch (specMode) {
3660        // Parent has imposed an exact size on us
3661        case MeasureSpec.EXACTLY:
3662            if (childDimension >= 0) {
3663                resultSize = childDimension;
3664                resultMode = MeasureSpec.EXACTLY;
3665            } else if (childDimension == LayoutParams.MATCH_PARENT) {
3666                // Child wants to be our size. So be it.
3667                resultSize = size;
3668                resultMode = MeasureSpec.EXACTLY;
3669            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
3670                // Child wants to determine its own size. It can't be
3671                // bigger than us.
3672                resultSize = size;
3673                resultMode = MeasureSpec.AT_MOST;
3674            }
3675            break;
3676
3677        // Parent has imposed a maximum size on us
3678        case MeasureSpec.AT_MOST:
3679            if (childDimension >= 0) {
3680                // Child wants a specific size... so be it
3681                resultSize = childDimension;
3682                resultMode = MeasureSpec.EXACTLY;
3683            } else if (childDimension == LayoutParams.MATCH_PARENT) {
3684                // Child wants to be our size, but our size is not fixed.
3685                // Constrain child to not be bigger than us.
3686                resultSize = size;
3687                resultMode = MeasureSpec.AT_MOST;
3688            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
3689                // Child wants to determine its own size. It can't be
3690                // bigger than us.
3691                resultSize = size;
3692                resultMode = MeasureSpec.AT_MOST;
3693            }
3694            break;
3695
3696        // Parent asked to see how big we want to be
3697        case MeasureSpec.UNSPECIFIED:
3698            if (childDimension >= 0) {
3699                // Child wants a specific size... let him have it
3700                resultSize = childDimension;
3701                resultMode = MeasureSpec.EXACTLY;
3702            } else if (childDimension == LayoutParams.MATCH_PARENT) {
3703                // Child wants to be our size... find out how big it should
3704                // be
3705                resultSize = 0;
3706                resultMode = MeasureSpec.UNSPECIFIED;
3707            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
3708                // Child wants to determine its own size.... find out how
3709                // big it should be
3710                resultSize = 0;
3711                resultMode = MeasureSpec.UNSPECIFIED;
3712            }
3713            break;
3714        }
3715        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
3716    }
3717
3718
3719    /**
3720     * Removes any pending animations for views that have been removed. Call
3721     * this if you don't want animations for exiting views to stack up.
3722     */
3723    public void clearDisappearingChildren() {
3724        if (mDisappearingChildren != null) {
3725            mDisappearingChildren.clear();
3726        }
3727    }
3728
3729    /**
3730     * Add a view which is removed from mChildren but still needs animation
3731     *
3732     * @param v View to add
3733     */
3734    private void addDisappearingView(View v) {
3735        ArrayList<View> disappearingChildren = mDisappearingChildren;
3736
3737        if (disappearingChildren == null) {
3738            disappearingChildren = mDisappearingChildren = new ArrayList<View>();
3739        }
3740
3741        disappearingChildren.add(v);
3742    }
3743
3744    /**
3745     * Cleanup a view when its animation is done. This may mean removing it from
3746     * the list of disappearing views.
3747     *
3748     * @param view The view whose animation has finished
3749     * @param animation The animation, cannot be null
3750     */
3751    private void finishAnimatingView(final View view, Animation animation) {
3752        final ArrayList<View> disappearingChildren = mDisappearingChildren;
3753        if (disappearingChildren != null) {
3754            if (disappearingChildren.contains(view)) {
3755                disappearingChildren.remove(view);
3756
3757                if (view.mAttachInfo != null) {
3758                    view.dispatchDetachedFromWindow();
3759                }
3760
3761                view.clearAnimation();
3762                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
3763            }
3764        }
3765
3766        if (animation != null && !animation.getFillAfter()) {
3767            view.clearAnimation();
3768        }
3769
3770        if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) {
3771            view.onAnimationEnd();
3772            // Should be performed by onAnimationEnd() but this avoid an infinite loop,
3773            // so we'd rather be safe than sorry
3774            view.mPrivateFlags &= ~ANIMATION_STARTED;
3775            // Draw one more frame after the animation is done
3776            mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
3777        }
3778    }
3779
3780    /**
3781     * This method tells the ViewGroup that the given View object, which should have this
3782     * ViewGroup as its parent,
3783     * should be kept around  (re-displayed when the ViewGroup draws its children) even if it
3784     * is removed from its parent. This allows animations, such as those used by
3785     * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate
3786     * the removal of views. A call to this method should always be accompanied by a later call
3787     * to {@link #endViewTransition(View)}, such as after an animation on the View has finished,
3788     * so that the View finally gets removed.
3789     *
3790     * @param view The View object to be kept visible even if it gets removed from its parent.
3791     */
3792    public void startViewTransition(View view) {
3793        if (view.mParent == this) {
3794            if (mTransitioningViews == null) {
3795                mTransitioningViews = new ArrayList<View>();
3796            }
3797            mTransitioningViews.add(view);
3798        }
3799    }
3800
3801    /**
3802     * This method should always be called following an earlier call to
3803     * {@link #startViewTransition(View)}. The given View is finally removed from its parent
3804     * and will no longer be displayed. Note that this method does not perform the functionality
3805     * of removing a view from its parent; it just discontinues the display of a View that
3806     * has previously been removed.
3807     *
3808     * @return view The View object that has been removed but is being kept around in the visible
3809     * hierarchy by an earlier call to {@link #startViewTransition(View)}.
3810     */
3811    public void endViewTransition(View view) {
3812        if (mTransitioningViews != null) {
3813            mTransitioningViews.remove(view);
3814            final ArrayList<View> disappearingChildren = mDisappearingChildren;
3815            if (disappearingChildren != null && disappearingChildren.contains(view)) {
3816                disappearingChildren.remove(view);
3817                if (view.mAttachInfo != null) {
3818                    view.dispatchDetachedFromWindow();
3819                }
3820                if (view.mParent != null) {
3821                    view.mParent = null;
3822                }
3823                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
3824            }
3825        }
3826    }
3827
3828    private LayoutTransition.TransitionListener mLayoutTransitionListener =
3829            new LayoutTransition.TransitionListener() {
3830        @Override
3831        public void startTransition(LayoutTransition transition, ViewGroup container,
3832                View view, int transitionType) {
3833            // We only care about disappearing items, since we need special logic to keep
3834            // those items visible after they've been 'removed'
3835            if (transitionType == LayoutTransition.DISAPPEARING) {
3836                startViewTransition(view);
3837            }
3838        }
3839
3840        @Override
3841        public void endTransition(LayoutTransition transition, ViewGroup container,
3842                View view, int transitionType) {
3843            if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
3844                endViewTransition(view);
3845            }
3846        }
3847    };
3848
3849    /**
3850     * {@inheritDoc}
3851     */
3852    @Override
3853    public boolean gatherTransparentRegion(Region region) {
3854        // If no transparent regions requested, we are always opaque.
3855        final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0;
3856        if (meOpaque && region == null) {
3857            // The caller doesn't care about the region, so stop now.
3858            return true;
3859        }
3860        super.gatherTransparentRegion(region);
3861        final View[] children = mChildren;
3862        final int count = mChildrenCount;
3863        boolean noneOfTheChildrenAreTransparent = true;
3864        for (int i = 0; i < count; i++) {
3865            final View child = children[i];
3866            if ((child.mViewFlags & VISIBILITY_MASK) != GONE || child.getAnimation() != null) {
3867                if (!child.gatherTransparentRegion(region)) {
3868                    noneOfTheChildrenAreTransparent = false;
3869                }
3870            }
3871        }
3872        return meOpaque || noneOfTheChildrenAreTransparent;
3873    }
3874
3875    /**
3876     * {@inheritDoc}
3877     */
3878    public void requestTransparentRegion(View child) {
3879        if (child != null) {
3880            child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
3881            if (mParent != null) {
3882                mParent.requestTransparentRegion(this);
3883            }
3884        }
3885    }
3886
3887
3888    @Override
3889    protected boolean fitSystemWindows(Rect insets) {
3890        boolean done = super.fitSystemWindows(insets);
3891        if (!done) {
3892            final int count = mChildrenCount;
3893            final View[] children = mChildren;
3894            for (int i = 0; i < count; i++) {
3895                done = children[i].fitSystemWindows(insets);
3896                if (done) {
3897                    break;
3898                }
3899            }
3900        }
3901        return done;
3902    }
3903
3904    /**
3905     * Returns the animation listener to which layout animation events are
3906     * sent.
3907     *
3908     * @return an {@link android.view.animation.Animation.AnimationListener}
3909     */
3910    public Animation.AnimationListener getLayoutAnimationListener() {
3911        return mAnimationListener;
3912    }
3913
3914    @Override
3915    protected void drawableStateChanged() {
3916        super.drawableStateChanged();
3917
3918        if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
3919            if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
3920                throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
3921                        + " child has duplicateParentState set to true");
3922            }
3923
3924            final View[] children = mChildren;
3925            final int count = mChildrenCount;
3926
3927            for (int i = 0; i < count; i++) {
3928                final View child = children[i];
3929                if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
3930                    child.refreshDrawableState();
3931                }
3932            }
3933        }
3934    }
3935
3936    @Override
3937    protected int[] onCreateDrawableState(int extraSpace) {
3938        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) {
3939            return super.onCreateDrawableState(extraSpace);
3940        }
3941
3942        int need = 0;
3943        int n = getChildCount();
3944        for (int i = 0; i < n; i++) {
3945            int[] childState = getChildAt(i).getDrawableState();
3946
3947            if (childState != null) {
3948                need += childState.length;
3949            }
3950        }
3951
3952        int[] state = super.onCreateDrawableState(extraSpace + need);
3953
3954        for (int i = 0; i < n; i++) {
3955            int[] childState = getChildAt(i).getDrawableState();
3956
3957            if (childState != null) {
3958                state = mergeDrawableStates(state, childState);
3959            }
3960        }
3961
3962        return state;
3963    }
3964
3965    /**
3966     * Sets whether this ViewGroup's drawable states also include
3967     * its children's drawable states.  This is used, for example, to
3968     * make a group appear to be focused when its child EditText or button
3969     * is focused.
3970     */
3971    public void setAddStatesFromChildren(boolean addsStates) {
3972        if (addsStates) {
3973            mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN;
3974        } else {
3975            mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN;
3976        }
3977
3978        refreshDrawableState();
3979    }
3980
3981    /**
3982     * Returns whether this ViewGroup's drawable states also include
3983     * its children's drawable states.  This is used, for example, to
3984     * make a group appear to be focused when its child EditText or button
3985     * is focused.
3986     */
3987    public boolean addStatesFromChildren() {
3988        return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0;
3989    }
3990
3991    /**
3992     * If {link #addStatesFromChildren} is true, refreshes this group's
3993     * drawable state (to include the states from its children).
3994     */
3995    public void childDrawableStateChanged(View child) {
3996        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
3997            refreshDrawableState();
3998        }
3999    }
4000
4001    /**
4002     * Specifies the animation listener to which layout animation events must
4003     * be sent. Only
4004     * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)}
4005     * and
4006     * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)}
4007     * are invoked.
4008     *
4009     * @param animationListener the layout animation listener
4010     */
4011    public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
4012        mAnimationListener = animationListener;
4013    }
4014
4015    /**
4016     * Called when a child's overlay state changes between enabled/disabled.
4017     * @param child Child view whose state has changed or null
4018     * @hide
4019     */
4020    public void childOverlayStateChanged(View child) {
4021        boolean childHasOverlay = false;
4022        if (child != null) {
4023            childHasOverlay = child.isOverlayEnabled();
4024        } else {
4025            final int childCount = getChildCount();
4026            for (int i = 0; i < childCount; i++) {
4027                if (childHasOverlay |= getChildAt(i).isOverlayEnabled()) {
4028                    break;
4029                }
4030            }
4031        }
4032
4033        final boolean hasChildWithOverlay = childHasOverlay ||
4034                (mGroupFlags & FLAG_CHILD_HAS_OVERLAY) == FLAG_CHILD_HAS_OVERLAY;
4035
4036        final boolean oldValue = isOverlayEnabled();
4037        mGroupFlags = (mGroupFlags & ~FLAG_CHILD_HAS_OVERLAY) |
4038                (hasChildWithOverlay ? FLAG_CHILD_HAS_OVERLAY : 0);
4039        if (isOverlayEnabled() != oldValue) {
4040            final ViewParent parent = getParent();
4041            if (parent != null) {
4042                try {
4043                    parent.childOverlayStateChanged(this);
4044                } catch (AbstractMethodError e) {
4045                    Log.e("ViewGroup", "Could not propagate hasOverlay state", e);
4046                }
4047            }
4048        }
4049    }
4050
4051    /**
4052     * @hide
4053     */
4054    public boolean isOverlayEnabled() {
4055        return super.isOverlayEnabled() ||
4056                ((mGroupFlags & FLAG_CHILD_HAS_OVERLAY) == FLAG_CHILD_HAS_OVERLAY);
4057    }
4058
4059    /**
4060     * @hide
4061     */
4062    @Override
4063    public void onDrawOverlay(Canvas canvas) {
4064        if ((mGroupFlags & FLAG_CHILD_HAS_OVERLAY) == FLAG_CHILD_HAS_OVERLAY) {
4065            final int childCount = getChildCount();
4066            for (int i = 0; i < childCount; i++) {
4067                final View child = getChildAt(i);
4068                if (child.isOverlayEnabled()) {
4069                    canvas.translate(child.mLeft + child.mScrollX, child.mTop + child.mScrollY);
4070                    child.onDrawOverlay(canvas);
4071                    canvas.translate(-(child.mLeft + child.mScrollX),
4072                            -(child.mTop + child.mScrollY));
4073                }
4074            }
4075        }
4076    }
4077
4078    /**
4079     * LayoutParams are used by views to tell their parents how they want to be
4080     * laid out. See
4081     * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes}
4082     * for a list of all child view attributes that this class supports.
4083     *
4084     * <p>
4085     * The base LayoutParams class just describes how big the view wants to be
4086     * for both width and height. For each dimension, it can specify one of:
4087     * <ul>
4088     * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
4089     * means that the view wants to be as big as its parent (minus padding)
4090     * <li> WRAP_CONTENT, which means that the view wants to be just big enough
4091     * to enclose its content (plus padding)
4092     * <li> an exact number
4093     * </ul>
4094     * There are subclasses of LayoutParams for different subclasses of
4095     * ViewGroup. For example, AbsoluteLayout has its own subclass of
4096     * LayoutParams which adds an X and Y value.
4097     *
4098     * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
4099     * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
4100     */
4101    public static class LayoutParams {
4102        /**
4103         * Special value for the height or width requested by a View.
4104         * FILL_PARENT means that the view wants to be as big as its parent,
4105         * minus the parent's padding, if any. This value is deprecated
4106         * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
4107         */
4108        @SuppressWarnings({"UnusedDeclaration"})
4109        @Deprecated
4110        public static final int FILL_PARENT = -1;
4111
4112        /**
4113         * Special value for the height or width requested by a View.
4114         * MATCH_PARENT means that the view wants to be as big as its parent,
4115         * minus the parent's padding, if any. Introduced in API Level 8.
4116         */
4117        public static final int MATCH_PARENT = -1;
4118
4119        /**
4120         * Special value for the height or width requested by a View.
4121         * WRAP_CONTENT means that the view wants to be just large enough to fit
4122         * its own internal content, taking its own padding into account.
4123         */
4124        public static final int WRAP_CONTENT = -2;
4125
4126        /**
4127         * Information about how wide the view wants to be. Can be one of the
4128         * constants FILL_PARENT (replaced by MATCH_PARENT ,
4129         * in API Level 8) or WRAP_CONTENT. or an exact size.
4130         */
4131        @ViewDebug.ExportedProperty(category = "layout", mapping = {
4132            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
4133            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
4134        })
4135        public int width;
4136
4137        /**
4138         * Information about how tall the view wants to be. Can be one of the
4139         * constants FILL_PARENT (replaced by MATCH_PARENT ,
4140         * in API Level 8) or WRAP_CONTENT. or an exact size.
4141         */
4142        @ViewDebug.ExportedProperty(category = "layout", mapping = {
4143            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
4144            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
4145        })
4146        public int height;
4147
4148        /**
4149         * Used to animate layouts.
4150         */
4151        public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
4152
4153        /**
4154         * Creates a new set of layout parameters. The values are extracted from
4155         * the supplied attributes set and context. The XML attributes mapped
4156         * to this set of layout parameters are:
4157         *
4158         * <ul>
4159         *   <li><code>layout_width</code>: the width, either an exact value,
4160         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
4161         *   {@link #MATCH_PARENT} in API Level 8)</li>
4162         *   <li><code>layout_height</code>: the height, either an exact value,
4163         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
4164         *   {@link #MATCH_PARENT} in API Level 8)</li>
4165         * </ul>
4166         *
4167         * @param c the application environment
4168         * @param attrs the set of attributes from which to extract the layout
4169         *              parameters' values
4170         */
4171        public LayoutParams(Context c, AttributeSet attrs) {
4172            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
4173            setBaseAttributes(a,
4174                    R.styleable.ViewGroup_Layout_layout_width,
4175                    R.styleable.ViewGroup_Layout_layout_height);
4176            a.recycle();
4177        }
4178
4179        /**
4180         * Creates a new set of layout parameters with the specified width
4181         * and height.
4182         *
4183         * @param width the width, either {@link #WRAP_CONTENT},
4184         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
4185         *        API Level 8), or a fixed size in pixels
4186         * @param height the height, either {@link #WRAP_CONTENT},
4187         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
4188         *        API Level 8), or a fixed size in pixels
4189         */
4190        public LayoutParams(int width, int height) {
4191            this.width = width;
4192            this.height = height;
4193        }
4194
4195        /**
4196         * Copy constructor. Clones the width and height values of the source.
4197         *
4198         * @param source The layout params to copy from.
4199         */
4200        public LayoutParams(LayoutParams source) {
4201            this.width = source.width;
4202            this.height = source.height;
4203        }
4204
4205        /**
4206         * Used internally by MarginLayoutParams.
4207         * @hide
4208         */
4209        LayoutParams() {
4210        }
4211
4212        /**
4213         * Extracts the layout parameters from the supplied attributes.
4214         *
4215         * @param a the style attributes to extract the parameters from
4216         * @param widthAttr the identifier of the width attribute
4217         * @param heightAttr the identifier of the height attribute
4218         */
4219        protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
4220            width = a.getLayoutDimension(widthAttr, "layout_width");
4221            height = a.getLayoutDimension(heightAttr, "layout_height");
4222        }
4223
4224        /**
4225         * Returns a String representation of this set of layout parameters.
4226         *
4227         * @param output the String to prepend to the internal representation
4228         * @return a String with the following format: output +
4229         *         "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }"
4230         *
4231         * @hide
4232         */
4233        public String debug(String output) {
4234            return output + "ViewGroup.LayoutParams={ width="
4235                    + sizeToString(width) + ", height=" + sizeToString(height) + " }";
4236        }
4237
4238        /**
4239         * Converts the specified size to a readable String.
4240         *
4241         * @param size the size to convert
4242         * @return a String instance representing the supplied size
4243         *
4244         * @hide
4245         */
4246        protected static String sizeToString(int size) {
4247            if (size == WRAP_CONTENT) {
4248                return "wrap-content";
4249            }
4250            if (size == MATCH_PARENT) {
4251                return "match-parent";
4252            }
4253            return String.valueOf(size);
4254        }
4255    }
4256
4257    /**
4258     * Per-child layout information for layouts that support margins.
4259     * See
4260     * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes}
4261     * for a list of all child view attributes that this class supports.
4262     */
4263    public static class MarginLayoutParams extends ViewGroup.LayoutParams {
4264        /**
4265         * The left margin in pixels of the child.
4266         */
4267        @ViewDebug.ExportedProperty(category = "layout")
4268        public int leftMargin;
4269
4270        /**
4271         * The top margin in pixels of the child.
4272         */
4273        @ViewDebug.ExportedProperty(category = "layout")
4274        public int topMargin;
4275
4276        /**
4277         * The right margin in pixels of the child.
4278         */
4279        @ViewDebug.ExportedProperty(category = "layout")
4280        public int rightMargin;
4281
4282        /**
4283         * The bottom margin in pixels of the child.
4284         */
4285        @ViewDebug.ExportedProperty(category = "layout")
4286        public int bottomMargin;
4287
4288        /**
4289         * Creates a new set of layout parameters. The values are extracted from
4290         * the supplied attributes set and context.
4291         *
4292         * @param c the application environment
4293         * @param attrs the set of attributes from which to extract the layout
4294         *              parameters' values
4295         */
4296        public MarginLayoutParams(Context c, AttributeSet attrs) {
4297            super();
4298
4299            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
4300            setBaseAttributes(a,
4301                    R.styleable.ViewGroup_MarginLayout_layout_width,
4302                    R.styleable.ViewGroup_MarginLayout_layout_height);
4303
4304            int margin = a.getDimensionPixelSize(
4305                    com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
4306            if (margin >= 0) {
4307                leftMargin = margin;
4308                topMargin = margin;
4309                rightMargin= margin;
4310                bottomMargin = margin;
4311            } else {
4312                leftMargin = a.getDimensionPixelSize(
4313                        R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0);
4314                topMargin = a.getDimensionPixelSize(
4315                        R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0);
4316                rightMargin = a.getDimensionPixelSize(
4317                        R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0);
4318                bottomMargin = a.getDimensionPixelSize(
4319                        R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0);
4320            }
4321
4322            a.recycle();
4323        }
4324
4325        /**
4326         * {@inheritDoc}
4327         */
4328        public MarginLayoutParams(int width, int height) {
4329            super(width, height);
4330        }
4331
4332        /**
4333         * Copy constructor. Clones the width, height and margin values of the source.
4334         *
4335         * @param source The layout params to copy from.
4336         */
4337        public MarginLayoutParams(MarginLayoutParams source) {
4338            this.width = source.width;
4339            this.height = source.height;
4340
4341            this.leftMargin = source.leftMargin;
4342            this.topMargin = source.topMargin;
4343            this.rightMargin = source.rightMargin;
4344            this.bottomMargin = source.bottomMargin;
4345        }
4346
4347        /**
4348         * {@inheritDoc}
4349         */
4350        public MarginLayoutParams(LayoutParams source) {
4351            super(source);
4352        }
4353
4354        /**
4355         * Sets the margins, in pixels.
4356         *
4357         * @param left the left margin size
4358         * @param top the top margin size
4359         * @param right the right margin size
4360         * @param bottom the bottom margin size
4361         *
4362         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
4363         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
4364         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
4365         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
4366         */
4367        public void setMargins(int left, int top, int right, int bottom) {
4368            leftMargin = left;
4369            topMargin = top;
4370            rightMargin = right;
4371            bottomMargin = bottom;
4372        }
4373    }
4374
4375    private static class SplitMotionTargets {
4376        private SparseArray<View> mTargets;
4377        private TargetInfo[] mUniqueTargets;
4378        private int mUniqueTargetCount;
4379        private MotionEvent.PointerCoords[] mPointerCoords;
4380        private int[] mPointerIds;
4381
4382        private static final int INITIAL_UNIQUE_MOTION_TARGETS_SIZE = 5;
4383        private static final int INITIAL_BUCKET_SIZE = 5;
4384
4385        public SplitMotionTargets() {
4386            mTargets = new SparseArray<View>();
4387            mUniqueTargets = new TargetInfo[INITIAL_UNIQUE_MOTION_TARGETS_SIZE];
4388            mPointerIds = new int[INITIAL_BUCKET_SIZE];
4389            mPointerCoords = new MotionEvent.PointerCoords[INITIAL_BUCKET_SIZE];
4390            for (int i = 0; i < INITIAL_BUCKET_SIZE; i++) {
4391                mPointerCoords[i] = new MotionEvent.PointerCoords();
4392            }
4393        }
4394
4395        public void clear() {
4396            mTargets.clear();
4397            final int count = mUniqueTargetCount;
4398            for (int i = 0; i < count; i++) {
4399                mUniqueTargets[i].recycle();
4400                mUniqueTargets[i] = null;
4401            }
4402            mUniqueTargetCount = 0;
4403        }
4404
4405        public void add(int pointerId, View target, long downTime) {
4406            mTargets.put(pointerId, target);
4407
4408            final int uniqueCount = mUniqueTargetCount;
4409            boolean addUnique = true;
4410            for (int i = 0; i < uniqueCount; i++) {
4411                if (mUniqueTargets[i].view == target) {
4412                    addUnique = false;
4413                }
4414            }
4415            if (addUnique) {
4416                if (mUniqueTargets.length == uniqueCount) {
4417                    TargetInfo[] newTargets =
4418                        new TargetInfo[uniqueCount + INITIAL_UNIQUE_MOTION_TARGETS_SIZE];
4419                    System.arraycopy(mUniqueTargets, 0, newTargets, 0, uniqueCount);
4420                    mUniqueTargets = newTargets;
4421                }
4422                mUniqueTargets[uniqueCount] = TargetInfo.obtain(target, downTime);
4423                mUniqueTargetCount++;
4424            }
4425        }
4426
4427        public int getIdCount() {
4428            return mTargets.size();
4429        }
4430
4431        public int getUniqueTargetCount() {
4432            return mUniqueTargetCount;
4433        }
4434
4435        public TargetInfo getUniqueTargetAt(int index) {
4436            return mUniqueTargets[index];
4437        }
4438
4439        public View get(int id) {
4440            return mTargets.get(id);
4441        }
4442
4443        public int indexOfTarget(View target) {
4444            return mTargets.indexOfValue(target);
4445        }
4446
4447        public View targetAt(int index) {
4448            return mTargets.valueAt(index);
4449        }
4450
4451        public TargetInfo getPrimaryTarget() {
4452            if (!isEmpty()) {
4453                // Find the longest-lived target
4454                long firstTime = Long.MAX_VALUE;
4455                int firstIndex = 0;
4456                final int uniqueCount = mUniqueTargetCount;
4457                for (int i = 0; i < uniqueCount; i++) {
4458                    TargetInfo info = mUniqueTargets[i];
4459                    if (info.downTime < firstTime) {
4460                        firstTime = info.downTime;
4461                        firstIndex = i;
4462                    }
4463                }
4464                return mUniqueTargets[firstIndex];
4465            }
4466            return null;
4467        }
4468
4469        public boolean isEmpty() {
4470            return mUniqueTargetCount == 0;
4471        }
4472
4473        public void removeById(int id) {
4474            final int index = mTargets.indexOfKey(id);
4475            removeAt(index);
4476        }
4477
4478        public void removeView(View view) {
4479            int i = 0;
4480            while (i < mTargets.size()) {
4481                if (mTargets.valueAt(i) == view) {
4482                    mTargets.removeAt(i);
4483                } else {
4484                    i++;
4485                }
4486            }
4487            removeUnique(view);
4488        }
4489
4490        public void removeAt(int index) {
4491            if (index < 0 || index >= mTargets.size()) {
4492                return;
4493            }
4494
4495            final View removeView = mTargets.valueAt(index);
4496            mTargets.removeAt(index);
4497            if (mTargets.indexOfValue(removeView) < 0) {
4498                removeUnique(removeView);
4499            }
4500        }
4501
4502        private void removeUnique(View removeView) {
4503            TargetInfo[] unique = mUniqueTargets;
4504            int uniqueCount = mUniqueTargetCount;
4505            for (int i = 0; i < uniqueCount; i++) {
4506                if (unique[i].view == removeView) {
4507                    unique[i].recycle();
4508                    unique[i] = unique[--uniqueCount];
4509                    unique[uniqueCount] = null;
4510                    break;
4511                }
4512            }
4513
4514            mUniqueTargetCount = uniqueCount;
4515        }
4516
4517        /**
4518         * Return a new (obtain()ed) MotionEvent containing only data for pointers that should
4519         * be dispatched to child. Don't forget to recycle it!
4520         */
4521        public MotionEvent filterMotionEventForChild(MotionEvent ev, View child, long downTime) {
4522            int action = ev.getAction();
4523            final int maskedAction = action & MotionEvent.ACTION_MASK;
4524
4525            // Only send pointer up events if this child was the target. Drop it otherwise.
4526            if (maskedAction == MotionEvent.ACTION_POINTER_UP &&
4527                    get(ev.getPointerId(ev.getActionIndex())) != child) {
4528                return null;
4529            }
4530
4531            int pointerCount = 0;
4532            final int idCount = getIdCount();
4533            for (int i = 0; i < idCount; i++) {
4534                if (targetAt(i) == child) {
4535                    pointerCount++;
4536                }
4537            }
4538
4539            int actionId = -1;
4540            boolean needsNewIndex = false; // True if we should fill in the action's masked index
4541
4542            // If we have a down event, it wasn't counted above.
4543            if (maskedAction == MotionEvent.ACTION_DOWN) {
4544                pointerCount++;
4545                actionId = ev.getPointerId(0);
4546            } else if (maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
4547                pointerCount++;
4548
4549                actionId = ev.getPointerId(ev.getActionIndex());
4550
4551                if (indexOfTarget(child) < 0) {
4552                    // The new action should be ACTION_DOWN if this child isn't currently getting
4553                    // any events.
4554                    action = MotionEvent.ACTION_DOWN;
4555                } else {
4556                    // Fill in the index portion of the action later.
4557                    needsNewIndex = true;
4558                }
4559            } else if (maskedAction == MotionEvent.ACTION_POINTER_UP) {
4560                actionId = ev.getPointerId(ev.getActionIndex());
4561                if (pointerCount == 1) {
4562                    // The new action should be ACTION_UP if there's only one pointer left for
4563                    // this target.
4564                    action = MotionEvent.ACTION_UP;
4565                } else {
4566                    // Fill in the index portion of the action later.
4567                    needsNewIndex = true;
4568                }
4569            }
4570
4571            if (pointerCount == 0) {
4572                return null;
4573            }
4574
4575            // Fill the buckets with pointer data!
4576            final int eventPointerCount = ev.getPointerCount();
4577            int bucketIndex = 0;
4578            int newActionIndex = -1;
4579            for (int evp = 0; evp < eventPointerCount; evp++) {
4580                final int id = ev.getPointerId(evp);
4581
4582                // Add this pointer to the bucket if it is new or targeted at child
4583                if (id == actionId || get(id) == child) {
4584                    // Expand scratch arrays if needed
4585                    if (mPointerCoords.length <= bucketIndex) {
4586                        int[] pointerIds = new int[pointerCount];
4587                        MotionEvent.PointerCoords[] pointerCoords =
4588                                new MotionEvent.PointerCoords[pointerCount];
4589                        for (int i = mPointerCoords.length; i < pointerCoords.length; i++) {
4590                            pointerCoords[i] = new MotionEvent.PointerCoords();
4591                        }
4592
4593                        System.arraycopy(mPointerCoords, 0,
4594                                pointerCoords, 0, mPointerCoords.length);
4595                        System.arraycopy(mPointerIds, 0, pointerIds, 0, mPointerIds.length);
4596
4597                        mPointerCoords = pointerCoords;
4598                        mPointerIds = pointerIds;
4599                    }
4600
4601                    mPointerIds[bucketIndex] = id;
4602                    ev.getPointerCoords(evp, mPointerCoords[bucketIndex]);
4603
4604                    if (needsNewIndex && id == actionId) {
4605                        newActionIndex = bucketIndex;
4606                    }
4607
4608                    bucketIndex++;
4609                }
4610            }
4611
4612            // Encode the new action index if we have one
4613            if (newActionIndex >= 0) {
4614                action = (action & MotionEvent.ACTION_MASK) |
4615                        (newActionIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT);
4616            }
4617
4618            return MotionEvent.obtain(downTime, ev.getEventTime(),
4619                    action, pointerCount, mPointerIds, mPointerCoords, ev.getMetaState(),
4620                    ev.getXPrecision(), ev.getYPrecision(), ev.getDeviceId(), ev.getEdgeFlags(),
4621                    ev.getSource(), ev.getFlags());
4622        }
4623
4624        static class TargetInfo {
4625            public View view;
4626            public long downTime;
4627
4628            private TargetInfo mNextRecycled;
4629
4630            private static TargetInfo sRecycleBin;
4631            private static int sRecycledCount;
4632
4633            private static int MAX_RECYCLED = 15;
4634
4635            private TargetInfo() {
4636            }
4637
4638            public static TargetInfo obtain(View v, long time) {
4639                TargetInfo info;
4640                if (sRecycleBin == null) {
4641                    info = new TargetInfo();
4642                } else {
4643                    info = sRecycleBin;
4644                    sRecycleBin = info.mNextRecycled;
4645                    sRecycledCount--;
4646                }
4647                info.view = v;
4648                info.downTime = time;
4649                return info;
4650            }
4651
4652            public void recycle() {
4653                if (sRecycledCount >= MAX_RECYCLED) {
4654                    return;
4655                }
4656                mNextRecycled = sRecycleBin;
4657                sRecycleBin = this;
4658                sRecycledCount++;
4659            }
4660        }
4661    }
4662}
4663