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