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