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