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