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