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