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