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