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