ViewGroup.java revision ea83503e8683531fac2534047e50bc1e5979b6dd
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.Animation;
40import android.view.animation.AnimationUtils;
41import android.view.animation.LayoutAnimationController;
42import android.view.animation.Transformation;
43
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.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
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    protected 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        ViewRootImpl root = getViewRootImpl();
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                event.setSource(InputDevice.SOURCE_TOUCHSCREEN);
1749                syntheticEvent = true;
1750            }
1751
1752            for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
1753                resetCancelNextUpFlag(target.child);
1754                dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits);
1755            }
1756            clearTouchTargets();
1757
1758            if (syntheticEvent) {
1759                event.recycle();
1760            }
1761        }
1762    }
1763
1764    /**
1765     * Gets the touch target for specified child view.
1766     * Returns null if not found.
1767     */
1768    private TouchTarget getTouchTarget(View child) {
1769        for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) {
1770            if (target.child == child) {
1771                return target;
1772            }
1773        }
1774        return null;
1775    }
1776
1777    /**
1778     * Adds a touch target for specified child to the beginning of the list.
1779     * Assumes the target child is not already present.
1780     */
1781    private TouchTarget addTouchTarget(View child, int pointerIdBits) {
1782        TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
1783        target.next = mFirstTouchTarget;
1784        mFirstTouchTarget = target;
1785        return target;
1786    }
1787
1788    /**
1789     * Removes the pointer ids from consideration.
1790     */
1791    private void removePointersFromTouchTargets(int pointerIdBits) {
1792        TouchTarget predecessor = null;
1793        TouchTarget target = mFirstTouchTarget;
1794        while (target != null) {
1795            final TouchTarget next = target.next;
1796            if ((target.pointerIdBits & pointerIdBits) != 0) {
1797                target.pointerIdBits &= ~pointerIdBits;
1798                if (target.pointerIdBits == 0) {
1799                    if (predecessor == null) {
1800                        mFirstTouchTarget = next;
1801                    } else {
1802                        predecessor.next = next;
1803                    }
1804                    target.recycle();
1805                    target = next;
1806                    continue;
1807                }
1808            }
1809            predecessor = target;
1810            target = next;
1811        }
1812    }
1813
1814    /**
1815     * Returns true if a child view can receive pointer events.
1816     * @hide
1817     */
1818    private static boolean canViewReceivePointerEvents(View child) {
1819        return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE
1820                || child.getAnimation() != null;
1821    }
1822
1823    /**
1824     * Returns true if a child view contains the specified point when transformed
1825     * into its coordinate space.
1826     * Child must not be null.
1827     * @hide
1828     */
1829    protected boolean isTransformedTouchPointInView(float x, float y, View child,
1830            PointF outLocalPoint) {
1831        float localX = x + mScrollX - child.mLeft;
1832        float localY = y + mScrollY - child.mTop;
1833        if (! child.hasIdentityMatrix() && mAttachInfo != null) {
1834            final float[] localXY = mAttachInfo.mTmpTransformLocation;
1835            localXY[0] = localX;
1836            localXY[1] = localY;
1837            child.getInverseMatrix().mapPoints(localXY);
1838            localX = localXY[0];
1839            localY = localXY[1];
1840        }
1841        final boolean isInView = child.pointInView(localX, localY);
1842        if (isInView && outLocalPoint != null) {
1843            outLocalPoint.set(localX, localY);
1844        }
1845        return isInView;
1846    }
1847
1848    /**
1849     * Transforms a motion event into the coordinate space of a particular child view,
1850     * filters out irrelevant pointer ids, and overrides its action if necessary.
1851     * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead.
1852     */
1853    private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel,
1854            View child, int desiredPointerIdBits) {
1855        final boolean handled;
1856
1857        // Canceling motions is a special case.  We don't need to perform any transformations
1858        // or filtering.  The important part is the action, not the contents.
1859        final int oldAction = event.getAction();
1860        if (cancel || oldAction == MotionEvent.ACTION_CANCEL) {
1861            event.setAction(MotionEvent.ACTION_CANCEL);
1862            if (child == null) {
1863                handled = super.dispatchTouchEvent(event);
1864            } else {
1865                handled = child.dispatchTouchEvent(event);
1866            }
1867            event.setAction(oldAction);
1868            return handled;
1869        }
1870
1871        // Calculate the number of pointers to deliver.
1872        final int oldPointerIdBits = event.getPointerIdBits();
1873        final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits;
1874
1875        // If for some reason we ended up in an inconsistent state where it looks like we
1876        // might produce a motion event with no pointers in it, then drop the event.
1877        if (newPointerIdBits == 0) {
1878            return false;
1879        }
1880
1881        // If the number of pointers is the same and we don't need to perform any fancy
1882        // irreversible transformations, then we can reuse the motion event for this
1883        // dispatch as long as we are careful to revert any changes we make.
1884        // Otherwise we need to make a copy.
1885        final MotionEvent transformedEvent;
1886        if (newPointerIdBits == oldPointerIdBits) {
1887            if (child == null || child.hasIdentityMatrix()) {
1888                if (child == null) {
1889                    handled = super.dispatchTouchEvent(event);
1890                } else {
1891                    final float offsetX = mScrollX - child.mLeft;
1892                    final float offsetY = mScrollY - child.mTop;
1893                    event.offsetLocation(offsetX, offsetY);
1894
1895                    handled = child.dispatchTouchEvent(event);
1896
1897                    event.offsetLocation(-offsetX, -offsetY);
1898                }
1899                return handled;
1900            }
1901            transformedEvent = MotionEvent.obtain(event);
1902        } else {
1903            transformedEvent = event.split(newPointerIdBits);
1904        }
1905
1906        // Perform any necessary transformations and dispatch.
1907        if (child == null) {
1908            handled = super.dispatchTouchEvent(transformedEvent);
1909        } else {
1910            final float offsetX = mScrollX - child.mLeft;
1911            final float offsetY = mScrollY - child.mTop;
1912            transformedEvent.offsetLocation(offsetX, offsetY);
1913            if (! child.hasIdentityMatrix()) {
1914                transformedEvent.transform(child.getInverseMatrix());
1915            }
1916
1917            handled = child.dispatchTouchEvent(transformedEvent);
1918        }
1919
1920        // Done.
1921        transformedEvent.recycle();
1922        return handled;
1923    }
1924
1925    /**
1926     * Enable or disable the splitting of MotionEvents to multiple children during touch event
1927     * dispatch. This behavior is enabled by default for applications that target an
1928     * SDK version of {@link Build.VERSION_CODES#HONEYCOMB} or newer.
1929     *
1930     * <p>When this option is enabled MotionEvents may be split and dispatched to different child
1931     * views depending on where each pointer initially went down. This allows for user interactions
1932     * such as scrolling two panes of content independently, chording of buttons, and performing
1933     * independent gestures on different pieces of content.
1934     *
1935     * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple
1936     *              child views. <code>false</code> to only allow one child view to be the target of
1937     *              any MotionEvent received by this ViewGroup.
1938     */
1939    public void setMotionEventSplittingEnabled(boolean split) {
1940        // TODO Applications really shouldn't change this setting mid-touch event,
1941        // but perhaps this should handle that case and send ACTION_CANCELs to any child views
1942        // with gestures in progress when this is changed.
1943        if (split) {
1944            mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
1945        } else {
1946            mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
1947        }
1948    }
1949
1950    /**
1951     * Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
1952     * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
1953     */
1954    public boolean isMotionEventSplittingEnabled() {
1955        return (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS;
1956    }
1957
1958    /**
1959     * {@inheritDoc}
1960     */
1961    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
1962
1963        if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
1964            // We're already in this state, assume our ancestors are too
1965            return;
1966        }
1967
1968        if (disallowIntercept) {
1969            mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
1970        } else {
1971            mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
1972        }
1973
1974        // Pass it up to our parent
1975        if (mParent != null) {
1976            mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
1977        }
1978    }
1979
1980    /**
1981     * Implement this method to intercept all touch screen motion events.  This
1982     * allows you to watch events as they are dispatched to your children, and
1983     * take ownership of the current gesture at any point.
1984     *
1985     * <p>Using this function takes some care, as it has a fairly complicated
1986     * interaction with {@link View#onTouchEvent(MotionEvent)
1987     * View.onTouchEvent(MotionEvent)}, and using it requires implementing
1988     * that method as well as this one in the correct way.  Events will be
1989     * received in the following order:
1990     *
1991     * <ol>
1992     * <li> You will receive the down event here.
1993     * <li> The down event will be handled either by a child of this view
1994     * group, or given to your own onTouchEvent() method to handle; this means
1995     * you should implement onTouchEvent() to return true, so you will
1996     * continue to see the rest of the gesture (instead of looking for
1997     * a parent view to handle it).  Also, by returning true from
1998     * onTouchEvent(), you will not receive any following
1999     * events in onInterceptTouchEvent() and all touch processing must
2000     * happen in onTouchEvent() like normal.
2001     * <li> For as long as you return false from this function, each following
2002     * event (up to and including the final up) will be delivered first here
2003     * and then to the target's onTouchEvent().
2004     * <li> If you return true from here, you will not receive any
2005     * following events: the target view will receive the same event but
2006     * with the action {@link MotionEvent#ACTION_CANCEL}, and all further
2007     * events will be delivered to your onTouchEvent() method and no longer
2008     * appear here.
2009     * </ol>
2010     *
2011     * @param ev The motion event being dispatched down the hierarchy.
2012     * @return Return true to steal motion events from the children and have
2013     * them dispatched to this ViewGroup through onTouchEvent().
2014     * The current target will receive an ACTION_CANCEL event, and no further
2015     * messages will be delivered here.
2016     */
2017    public boolean onInterceptTouchEvent(MotionEvent ev) {
2018        return false;
2019    }
2020
2021    /**
2022     * {@inheritDoc}
2023     *
2024     * Looks for a view to give focus to respecting the setting specified by
2025     * {@link #getDescendantFocusability()}.
2026     *
2027     * Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to
2028     * find focus within the children of this group when appropriate.
2029     *
2030     * @see #FOCUS_BEFORE_DESCENDANTS
2031     * @see #FOCUS_AFTER_DESCENDANTS
2032     * @see #FOCUS_BLOCK_DESCENDANTS
2033     * @see #onRequestFocusInDescendants(int, android.graphics.Rect)
2034     */
2035    @Override
2036    public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
2037        if (DBG) {
2038            System.out.println(this + " ViewGroup.requestFocus direction="
2039                    + direction);
2040        }
2041        int descendantFocusability = getDescendantFocusability();
2042
2043        switch (descendantFocusability) {
2044            case FOCUS_BLOCK_DESCENDANTS:
2045                return super.requestFocus(direction, previouslyFocusedRect);
2046            case FOCUS_BEFORE_DESCENDANTS: {
2047                final boolean took = super.requestFocus(direction, previouslyFocusedRect);
2048                return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect);
2049            }
2050            case FOCUS_AFTER_DESCENDANTS: {
2051                final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);
2052                return took ? took : super.requestFocus(direction, previouslyFocusedRect);
2053            }
2054            default:
2055                throw new IllegalStateException("descendant focusability must be "
2056                        + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS "
2057                        + "but is " + descendantFocusability);
2058        }
2059    }
2060
2061    /**
2062     * Look for a descendant to call {@link View#requestFocus} on.
2063     * Called by {@link ViewGroup#requestFocus(int, android.graphics.Rect)}
2064     * when it wants to request focus within its children.  Override this to
2065     * customize how your {@link ViewGroup} requests focus within its children.
2066     * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
2067     * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
2068     *        to give a finer grained hint about where focus is coming from.  May be null
2069     *        if there is no hint.
2070     * @return Whether focus was taken.
2071     */
2072    @SuppressWarnings({"ConstantConditions"})
2073    protected boolean onRequestFocusInDescendants(int direction,
2074            Rect previouslyFocusedRect) {
2075        int index;
2076        int increment;
2077        int end;
2078        int count = mChildrenCount;
2079        if ((direction & FOCUS_FORWARD) != 0) {
2080            index = 0;
2081            increment = 1;
2082            end = count;
2083        } else {
2084            index = count - 1;
2085            increment = -1;
2086            end = -1;
2087        }
2088        final View[] children = mChildren;
2089        for (int i = index; i != end; i += increment) {
2090            View child = children[i];
2091            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2092                if (child.requestFocus(direction, previouslyFocusedRect)) {
2093                    return true;
2094                }
2095            }
2096        }
2097        return false;
2098    }
2099
2100    /**
2101     * {@inheritDoc}
2102     *
2103     * @hide
2104     */
2105    @Override
2106    public void dispatchStartTemporaryDetach() {
2107        super.dispatchStartTemporaryDetach();
2108        final int count = mChildrenCount;
2109        final View[] children = mChildren;
2110        for (int i = 0; i < count; i++) {
2111            children[i].dispatchStartTemporaryDetach();
2112        }
2113    }
2114
2115    /**
2116     * {@inheritDoc}
2117     *
2118     * @hide
2119     */
2120    @Override
2121    public void dispatchFinishTemporaryDetach() {
2122        super.dispatchFinishTemporaryDetach();
2123        final int count = mChildrenCount;
2124        final View[] children = mChildren;
2125        for (int i = 0; i < count; i++) {
2126            children[i].dispatchFinishTemporaryDetach();
2127        }
2128    }
2129
2130    /**
2131     * {@inheritDoc}
2132     */
2133    @Override
2134    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
2135        super.dispatchAttachedToWindow(info, visibility);
2136        visibility |= mViewFlags & VISIBILITY_MASK;
2137        final int count = mChildrenCount;
2138        final View[] children = mChildren;
2139        for (int i = 0; i < count; i++) {
2140            children[i].dispatchAttachedToWindow(info, visibility);
2141        }
2142    }
2143
2144    @Override
2145    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
2146        // We first get a chance to populate the event.
2147        onPopulateAccessibilityEvent(event);
2148        // Let our children have a shot in populating the event.
2149        for (int i = 0, count = getChildCount(); i < count; i++) {
2150            View child = getChildAt(i);
2151            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2152                boolean handled = getChildAt(i).dispatchPopulateAccessibilityEvent(event);
2153                if (handled) {
2154                    return handled;
2155                }
2156            }
2157        }
2158        return false;
2159    }
2160
2161    @Override
2162    public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
2163        super.onInitializeAccessibilityNodeInfo(info);
2164        // If the view is not the topmost one in the view hierarchy and it is
2165        // marked as the logical root of a view hierarchy, do not go any deeper.
2166        if ((!(getParent() instanceof ViewRootImpl)) && (mPrivateFlags & IS_ROOT_NAMESPACE) != 0) {
2167            return;
2168        }
2169        for (int i = 0, count = mChildrenCount; i < count; i++) {
2170            View child = mChildren[i];
2171            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2172                info.addChild(child);
2173            }
2174        }
2175    }
2176
2177    /**
2178     * {@inheritDoc}
2179     */
2180    @Override
2181    void dispatchDetachedFromWindow() {
2182        // If we still have a touch target, we are still in the process of
2183        // dispatching motion events to a child; we need to get rid of that
2184        // child to avoid dispatching events to it after the window is torn
2185        // down. To make sure we keep the child in a consistent state, we
2186        // first send it an ACTION_CANCEL motion event.
2187        cancelAndClearTouchTargets(null);
2188
2189        // In case view is detached while transition is running
2190        mLayoutSuppressed = false;
2191
2192        // Tear down our drag tracking
2193        mDragNotifiedChildren = null;
2194        if (mCurrentDrag != null) {
2195            mCurrentDrag.recycle();
2196            mCurrentDrag = null;
2197        }
2198
2199        final int count = mChildrenCount;
2200        final View[] children = mChildren;
2201        for (int i = 0; i < count; i++) {
2202            children[i].dispatchDetachedFromWindow();
2203        }
2204        super.dispatchDetachedFromWindow();
2205    }
2206
2207    /**
2208     * {@inheritDoc}
2209     */
2210    @Override
2211    public void setPadding(int left, int top, int right, int bottom) {
2212        super.setPadding(left, top, right, bottom);
2213
2214        if ((mPaddingLeft | mPaddingTop | mPaddingRight | mPaddingBottom) != 0) {
2215            mGroupFlags |= FLAG_PADDING_NOT_NULL;
2216        } else {
2217            mGroupFlags &= ~FLAG_PADDING_NOT_NULL;
2218        }
2219    }
2220
2221    /**
2222     * {@inheritDoc}
2223     */
2224    @Override
2225    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
2226        super.dispatchSaveInstanceState(container);
2227        final int count = mChildrenCount;
2228        final View[] children = mChildren;
2229        for (int i = 0; i < count; i++) {
2230            View c = children[i];
2231            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
2232                c.dispatchSaveInstanceState(container);
2233            }
2234        }
2235    }
2236
2237    /**
2238     * Perform dispatching of a {@link #saveHierarchyState(android.util.SparseArray)}  freeze()}
2239     * to only this view, not to its children.  For use when overriding
2240     * {@link #dispatchSaveInstanceState(android.util.SparseArray)}  dispatchFreeze()} to allow
2241     * subclasses to freeze their own state but not the state of their children.
2242     *
2243     * @param container the container
2244     */
2245    protected void dispatchFreezeSelfOnly(SparseArray<Parcelable> container) {
2246        super.dispatchSaveInstanceState(container);
2247    }
2248
2249    /**
2250     * {@inheritDoc}
2251     */
2252    @Override
2253    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
2254        super.dispatchRestoreInstanceState(container);
2255        final int count = mChildrenCount;
2256        final View[] children = mChildren;
2257        for (int i = 0; i < count; i++) {
2258            View c = children[i];
2259            if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
2260                c.dispatchRestoreInstanceState(container);
2261            }
2262        }
2263    }
2264
2265    /**
2266     * Perform dispatching of a {@link #restoreHierarchyState(android.util.SparseArray)}
2267     * to only this view, not to its children.  For use when overriding
2268     * {@link #dispatchRestoreInstanceState(android.util.SparseArray)} to allow
2269     * subclasses to thaw their own state but not the state of their children.
2270     *
2271     * @param container the container
2272     */
2273    protected void dispatchThawSelfOnly(SparseArray<Parcelable> container) {
2274        super.dispatchRestoreInstanceState(container);
2275    }
2276
2277    /**
2278     * Enables or disables the drawing cache for each child of this view group.
2279     *
2280     * @param enabled true to enable the cache, false to dispose of it
2281     */
2282    protected void setChildrenDrawingCacheEnabled(boolean enabled) {
2283        if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) {
2284            final View[] children = mChildren;
2285            final int count = mChildrenCount;
2286            for (int i = 0; i < count; i++) {
2287                children[i].setDrawingCacheEnabled(enabled);
2288            }
2289        }
2290    }
2291
2292    @Override
2293    protected void onAnimationStart() {
2294        super.onAnimationStart();
2295
2296        // When this ViewGroup's animation starts, build the cache for the children
2297        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2298            final int count = mChildrenCount;
2299            final View[] children = mChildren;
2300            final boolean buildCache = !isHardwareAccelerated();
2301
2302            for (int i = 0; i < count; i++) {
2303                final View child = children[i];
2304                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2305                    child.setDrawingCacheEnabled(true);
2306                    if (buildCache) {
2307                        child.buildDrawingCache(true);
2308                    }
2309                }
2310            }
2311
2312            mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
2313        }
2314    }
2315
2316    @Override
2317    protected void onAnimationEnd() {
2318        super.onAnimationEnd();
2319
2320        // When this ViewGroup's animation ends, destroy the cache of the children
2321        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2322            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
2323
2324            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
2325                setChildrenDrawingCacheEnabled(false);
2326            }
2327        }
2328    }
2329
2330    @Override
2331    Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
2332        int count = mChildrenCount;
2333        int[] visibilities = null;
2334
2335        if (skipChildren) {
2336            visibilities = new int[count];
2337            for (int i = 0; i < count; i++) {
2338                View child = getChildAt(i);
2339                visibilities[i] = child.getVisibility();
2340                if (visibilities[i] == View.VISIBLE) {
2341                    child.setVisibility(INVISIBLE);
2342                }
2343            }
2344        }
2345
2346        Bitmap b = super.createSnapshot(quality, backgroundColor, skipChildren);
2347
2348        if (skipChildren) {
2349            for (int i = 0; i < count; i++) {
2350                getChildAt(i).setVisibility(visibilities[i]);
2351            }
2352        }
2353
2354        return b;
2355    }
2356
2357    /**
2358     * {@inheritDoc}
2359     */
2360    @Override
2361    protected void dispatchDraw(Canvas canvas) {
2362        final int count = mChildrenCount;
2363        final View[] children = mChildren;
2364        int flags = mGroupFlags;
2365
2366        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
2367            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
2368
2369            final boolean buildCache = !isHardwareAccelerated();
2370            for (int i = 0; i < count; i++) {
2371                final View child = children[i];
2372                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2373                    final LayoutParams params = child.getLayoutParams();
2374                    attachLayoutAnimationParameters(child, params, i, count);
2375                    bindLayoutAnimation(child);
2376                    if (cache) {
2377                        child.setDrawingCacheEnabled(true);
2378                        if (buildCache) {
2379                            child.buildDrawingCache(true);
2380                        }
2381                    }
2382                }
2383            }
2384
2385            final LayoutAnimationController controller = mLayoutAnimationController;
2386            if (controller.willOverlap()) {
2387                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
2388            }
2389
2390            controller.start();
2391
2392            mGroupFlags &= ~FLAG_RUN_ANIMATION;
2393            mGroupFlags &= ~FLAG_ANIMATION_DONE;
2394
2395            if (cache) {
2396                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
2397            }
2398
2399            if (mAnimationListener != null) {
2400                mAnimationListener.onAnimationStart(controller.getAnimation());
2401            }
2402        }
2403
2404        int saveCount = 0;
2405        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
2406        if (clipToPadding) {
2407            saveCount = canvas.save();
2408            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
2409                    mScrollX + mRight - mLeft - mPaddingRight,
2410                    mScrollY + mBottom - mTop - mPaddingBottom);
2411
2412        }
2413
2414        // We will draw our child's animation, let's reset the flag
2415        mPrivateFlags &= ~DRAW_ANIMATION;
2416        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
2417
2418        boolean more = false;
2419        final long drawingTime = getDrawingTime();
2420
2421        if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {
2422            for (int i = 0; i < count; i++) {
2423                final View child = children[i];
2424                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
2425                    more |= drawChild(canvas, child, drawingTime);
2426                }
2427            }
2428        } else {
2429            for (int i = 0; i < count; i++) {
2430                final View child = children[getChildDrawingOrder(count, i)];
2431                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
2432                    more |= drawChild(canvas, child, drawingTime);
2433                }
2434            }
2435        }
2436
2437        // Draw any disappearing views that have animations
2438        if (mDisappearingChildren != null) {
2439            final ArrayList<View> disappearingChildren = mDisappearingChildren;
2440            final int disappearingCount = disappearingChildren.size() - 1;
2441            // Go backwards -- we may delete as animations finish
2442            for (int i = disappearingCount; i >= 0; i--) {
2443                final View child = disappearingChildren.get(i);
2444                more |= drawChild(canvas, child, drawingTime);
2445            }
2446        }
2447
2448        if (clipToPadding) {
2449            canvas.restoreToCount(saveCount);
2450        }
2451
2452        // mGroupFlags might have been updated by drawChild()
2453        flags = mGroupFlags;
2454
2455        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
2456            invalidate(true);
2457        }
2458
2459        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
2460                mLayoutAnimationController.isDone() && !more) {
2461            // We want to erase the drawing cache and notify the listener after the
2462            // next frame is drawn because one extra invalidate() is caused by
2463            // drawChild() after the animation is over
2464            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
2465            final Runnable end = new Runnable() {
2466               public void run() {
2467                   notifyAnimationListener();
2468               }
2469            };
2470            post(end);
2471        }
2472    }
2473
2474    /**
2475     * Returns the index of the child to draw for this iteration. Override this
2476     * if you want to change the drawing order of children. By default, it
2477     * returns i.
2478     * <p>
2479     * NOTE: In order for this method to be called, you must enable child ordering
2480     * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}.
2481     *
2482     * @param i The current iteration.
2483     * @return The index of the child to draw this iteration.
2484     *
2485     * @see #setChildrenDrawingOrderEnabled(boolean)
2486     * @see #isChildrenDrawingOrderEnabled()
2487     */
2488    protected int getChildDrawingOrder(int childCount, int i) {
2489        return i;
2490    }
2491
2492    private void notifyAnimationListener() {
2493        mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER;
2494        mGroupFlags |= FLAG_ANIMATION_DONE;
2495
2496        if (mAnimationListener != null) {
2497           final Runnable end = new Runnable() {
2498               public void run() {
2499                   mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation());
2500               }
2501           };
2502           post(end);
2503        }
2504
2505        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2506            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
2507            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
2508                setChildrenDrawingCacheEnabled(false);
2509            }
2510        }
2511
2512        invalidate(true);
2513    }
2514
2515    /**
2516     * This method is used to cause children of this ViewGroup to restore or recreate their
2517     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
2518     * to recreate its own display list, which would happen if it went through the normal
2519     * draw/dispatchDraw mechanisms.
2520     *
2521     * @hide
2522     */
2523    @Override
2524    protected void dispatchGetDisplayList() {
2525        final int count = mChildrenCount;
2526        final View[] children = mChildren;
2527        for (int i = 0; i < count; i++) {
2528            final View child = children[i];
2529            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
2530                child.mRecreateDisplayList = (child.mPrivateFlags & INVALIDATED) == INVALIDATED;
2531                child.mPrivateFlags &= ~INVALIDATED;
2532                child.getDisplayList();
2533                child.mRecreateDisplayList = false;
2534            }
2535        }
2536    }
2537
2538    /**
2539     * Draw one child of this View Group. This method is responsible for getting
2540     * the canvas in the right state. This includes clipping, translating so
2541     * that the child's scrolled origin is at 0, 0, and applying any animation
2542     * transformations.
2543     *
2544     * @param canvas The canvas on which to draw the child
2545     * @param child Who to draw
2546     * @param drawingTime The time at which draw is occuring
2547     * @return True if an invalidate() was issued
2548     */
2549    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
2550        boolean more = false;
2551
2552        final int cl = child.mLeft;
2553        final int ct = child.mTop;
2554        final int cr = child.mRight;
2555        final int cb = child.mBottom;
2556
2557        final boolean childHasIdentityMatrix = child.hasIdentityMatrix();
2558
2559        final int flags = mGroupFlags;
2560
2561        if ((flags & FLAG_CLEAR_TRANSFORMATION) == FLAG_CLEAR_TRANSFORMATION) {
2562            mChildTransformation.clear();
2563            mGroupFlags &= ~FLAG_CLEAR_TRANSFORMATION;
2564        }
2565
2566        Transformation transformToApply = null;
2567        Transformation invalidationTransform;
2568        final Animation a = child.getAnimation();
2569        boolean concatMatrix = false;
2570
2571        boolean scalingRequired = false;
2572        boolean caching;
2573        int layerType = mDrawLayers ? child.getLayerType() : LAYER_TYPE_NONE;
2574
2575        final boolean hardwareAccelerated = canvas.isHardwareAccelerated();
2576        if ((flags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE ||
2577                (flags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE) {
2578            caching = true;
2579            if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
2580        } else {
2581            caching = (layerType != LAYER_TYPE_NONE) || hardwareAccelerated;
2582        }
2583
2584        if (a != null) {
2585            final boolean initialized = a.isInitialized();
2586            if (!initialized) {
2587                a.initialize(cr - cl, cb - ct, getWidth(), getHeight());
2588                a.initializeInvalidateRegion(0, 0, cr - cl, cb - ct);
2589                child.onAnimationStart();
2590            }
2591
2592            more = a.getTransformation(drawingTime, mChildTransformation,
2593                    scalingRequired ? mAttachInfo.mApplicationScale : 1f);
2594            if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
2595                if (mInvalidationTransformation == null) {
2596                    mInvalidationTransformation = new Transformation();
2597                }
2598                invalidationTransform = mInvalidationTransformation;
2599                a.getTransformation(drawingTime, invalidationTransform, 1f);
2600            } else {
2601                invalidationTransform = mChildTransformation;
2602            }
2603            transformToApply = mChildTransformation;
2604
2605            concatMatrix = a.willChangeTransformationMatrix();
2606
2607            if (more) {
2608                if (!a.willChangeBounds()) {
2609                    if ((flags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) ==
2610                            FLAG_OPTIMIZE_INVALIDATE) {
2611                        mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
2612                    } else if ((flags & FLAG_INVALIDATE_REQUIRED) == 0) {
2613                        // The child need to draw an animation, potentially offscreen, so
2614                        // make sure we do not cancel invalidate requests
2615                        mPrivateFlags |= DRAW_ANIMATION;
2616                        invalidate(cl, ct, cr, cb);
2617                    }
2618                } else {
2619                    if (mInvalidateRegion == null) {
2620                        mInvalidateRegion = new RectF();
2621                    }
2622                    final RectF region = mInvalidateRegion;
2623                    a.getInvalidateRegion(0, 0, cr - cl, cb - ct, region, invalidationTransform);
2624
2625                    // The child need to draw an animation, potentially offscreen, so
2626                    // make sure we do not cancel invalidate requests
2627                    mPrivateFlags |= DRAW_ANIMATION;
2628
2629                    final int left = cl + (int) region.left;
2630                    final int top = ct + (int) region.top;
2631                    invalidate(left, top, left + (int) region.width(), top + (int) region.height());
2632                }
2633            }
2634        } else if ((flags & FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
2635                FLAG_SUPPORT_STATIC_TRANSFORMATIONS) {
2636            final boolean hasTransform = getChildStaticTransformation(child, mChildTransformation);
2637            if (hasTransform) {
2638                final int transformType = mChildTransformation.getTransformationType();
2639                transformToApply = transformType != Transformation.TYPE_IDENTITY ?
2640                        mChildTransformation : null;
2641                concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
2642            }
2643        }
2644
2645        concatMatrix |= !childHasIdentityMatrix;
2646
2647        // Sets the flag as early as possible to allow draw() implementations
2648        // to call invalidate() successfully when doing animations
2649        child.mPrivateFlags |= DRAWN;
2650
2651        if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW) &&
2652                (child.mPrivateFlags & DRAW_ANIMATION) == 0) {
2653            return more;
2654        }
2655
2656        float alpha = child.getAlpha();
2657        // Bail out early if the view does not need to be drawn
2658        if (alpha <= ViewConfiguration.ALPHA_THRESHOLD && (child.mPrivateFlags & ALPHA_SET) == 0 &&
2659                !(child instanceof SurfaceView)) {
2660            return more;
2661        }
2662
2663        if (hardwareAccelerated) {
2664            // Clear INVALIDATED flag to allow invalidation to occur during rendering, but
2665            // retain the flag's value temporarily in the mRecreateDisplayList flag
2666            child.mRecreateDisplayList = (child.mPrivateFlags & INVALIDATED) == INVALIDATED;
2667            child.mPrivateFlags &= ~INVALIDATED;
2668        }
2669
2670        child.computeScroll();
2671
2672        final int sx = child.mScrollX;
2673        final int sy = child.mScrollY;
2674
2675        DisplayList displayList = null;
2676        Bitmap cache = null;
2677        boolean hasDisplayList = false;
2678        if (caching) {
2679            if (!hardwareAccelerated) {
2680                if (layerType != LAYER_TYPE_NONE) {
2681                    layerType = LAYER_TYPE_SOFTWARE;
2682                    child.buildDrawingCache(true);
2683                }
2684                cache = child.getDrawingCache(true);
2685            } else {
2686                switch (layerType) {
2687                    case LAYER_TYPE_SOFTWARE:
2688                        child.buildDrawingCache(true);
2689                        cache = child.getDrawingCache(true);
2690                        break;
2691                    case LAYER_TYPE_NONE:
2692                        // Delay getting the display list until animation-driven alpha values are
2693                        // set up and possibly passed on to the view
2694                        hasDisplayList = child.canHaveDisplayList();
2695                        break;
2696                }
2697            }
2698        }
2699
2700        final boolean hasNoCache = cache == null || hasDisplayList;
2701        final boolean offsetForScroll = cache == null && !hasDisplayList &&
2702                layerType != LAYER_TYPE_HARDWARE;
2703
2704        final int restoreTo = canvas.save();
2705        if (offsetForScroll) {
2706            canvas.translate(cl - sx, ct - sy);
2707        } else {
2708            canvas.translate(cl, ct);
2709            if (scalingRequired) {
2710                // mAttachInfo cannot be null, otherwise scalingRequired == false
2711                final float scale = 1.0f / mAttachInfo.mApplicationScale;
2712                canvas.scale(scale, scale);
2713            }
2714        }
2715
2716        if (transformToApply != null || alpha < 1.0f || !child.hasIdentityMatrix()) {
2717            if (transformToApply != null || !childHasIdentityMatrix) {
2718                int transX = 0;
2719                int transY = 0;
2720
2721                if (offsetForScroll) {
2722                    transX = -sx;
2723                    transY = -sy;
2724                }
2725
2726                if (transformToApply != null) {
2727                    if (concatMatrix) {
2728                        // Undo the scroll translation, apply the transformation matrix,
2729                        // then redo the scroll translate to get the correct result.
2730                        canvas.translate(-transX, -transY);
2731                        canvas.concat(transformToApply.getMatrix());
2732                        canvas.translate(transX, transY);
2733                        mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
2734                    }
2735
2736                    float transformAlpha = transformToApply.getAlpha();
2737                    if (transformAlpha < 1.0f) {
2738                        alpha *= transformToApply.getAlpha();
2739                        mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
2740                    }
2741                }
2742
2743                if (!childHasIdentityMatrix) {
2744                    canvas.translate(-transX, -transY);
2745                    canvas.concat(child.getMatrix());
2746                    canvas.translate(transX, transY);
2747                }
2748            }
2749
2750            if (alpha < 1.0f) {
2751                mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
2752                if (hasNoCache) {
2753                    final int multipliedAlpha = (int) (255 * alpha);
2754                    if (!child.onSetAlpha(multipliedAlpha)) {
2755                        int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
2756                        if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN ||
2757                                layerType != LAYER_TYPE_NONE) {
2758                            layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
2759                        }
2760                        if (layerType == LAYER_TYPE_NONE) {
2761                            final int scrollX = hasDisplayList ? 0 : sx;
2762                            final int scrollY = hasDisplayList ? 0 : sy;
2763                            canvas.saveLayerAlpha(scrollX, scrollY, scrollX + cr - cl,
2764                                    scrollY + cb - ct, multipliedAlpha, layerFlags);
2765                        }
2766                    } else {
2767                        // Alpha is handled by the child directly, clobber the layer's alpha
2768                        child.mPrivateFlags |= ALPHA_SET;
2769                    }
2770                }
2771            }
2772        } else if ((child.mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
2773            child.onSetAlpha(255);
2774            child.mPrivateFlags &= ~ALPHA_SET;
2775        }
2776
2777        if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
2778            if (offsetForScroll) {
2779                canvas.clipRect(sx, sy, sx + (cr - cl), sy + (cb - ct));
2780            } else {
2781                if (!scalingRequired || cache == null) {
2782                    canvas.clipRect(0, 0, cr - cl, cb - ct);
2783                } else {
2784                    canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
2785                }
2786            }
2787        }
2788
2789        if (hasDisplayList) {
2790            displayList = child.getDisplayList();
2791        }
2792
2793        if (hasNoCache) {
2794            boolean layerRendered = false;
2795            if (layerType == LAYER_TYPE_HARDWARE) {
2796                final HardwareLayer layer = child.getHardwareLayer();
2797                if (layer != null && layer.isValid()) {
2798                    child.mLayerPaint.setAlpha((int) (alpha * 255));
2799                    ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, child.mLayerPaint);
2800                    layerRendered = true;
2801                } else {
2802                    final int scrollX = hasDisplayList ? 0 : sx;
2803                    final int scrollY = hasDisplayList ? 0 : sy;
2804                    canvas.saveLayer(scrollX, scrollY,
2805                            scrollX + cr - cl, scrollY + cb - ct, child.mLayerPaint,
2806                            Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG);
2807                }
2808            }
2809
2810            if (!layerRendered) {
2811                if (!hasDisplayList) {
2812                    // Fast path for layouts with no backgrounds
2813                    if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
2814                        if (ViewDebug.TRACE_HIERARCHY) {
2815                            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
2816                        }
2817                        child.mPrivateFlags &= ~DIRTY_MASK;
2818                        child.dispatchDraw(canvas);
2819                    } else {
2820                        child.draw(canvas);
2821                    }
2822                } else {
2823                    child.mPrivateFlags &= ~DIRTY_MASK;
2824                    ((HardwareCanvas) canvas).drawDisplayList(displayList, cr - cl, cb - ct, null);
2825                }
2826            }
2827        } else if (cache != null) {
2828            child.mPrivateFlags &= ~DIRTY_MASK;
2829            Paint cachePaint;
2830
2831            if (layerType == LAYER_TYPE_NONE) {
2832                cachePaint = mCachePaint;
2833                if (alpha < 1.0f) {
2834                    cachePaint.setAlpha((int) (alpha * 255));
2835                    mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE;
2836                } else if  ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) {
2837                    cachePaint.setAlpha(255);
2838                    mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE;
2839                }
2840            } else {
2841                cachePaint = child.mLayerPaint;
2842                cachePaint.setAlpha((int) (alpha * 255));
2843            }
2844            canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
2845        }
2846
2847        canvas.restoreToCount(restoreTo);
2848
2849        if (a != null && !more) {
2850            if (!hardwareAccelerated && !a.getFillAfter()) {
2851                child.onSetAlpha(255);
2852            }
2853            finishAnimatingView(child, a);
2854        }
2855
2856        if (more && hardwareAccelerated) {
2857            // invalidation is the trigger to recreate display lists, so if we're using
2858            // display lists to render, force an invalidate to allow the animation to
2859            // continue drawing another frame
2860            invalidate(true);
2861            if (a.hasAlpha() && (child.mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
2862                // alpha animations should cause the child to recreate its display list
2863                child.invalidate(true);
2864            }
2865        }
2866
2867        child.mRecreateDisplayList = false;
2868
2869        return more;
2870    }
2871
2872    /**
2873     *
2874     * @param enabled True if children should be drawn with layers, false otherwise.
2875     *
2876     * @hide
2877     */
2878    public void setChildrenLayersEnabled(boolean enabled) {
2879        if (enabled != mDrawLayers) {
2880            mDrawLayers = enabled;
2881            invalidate(true);
2882
2883            // We need to invalidate any child with a layer. For instance,
2884            // if a child is backed by a hardware layer and we disable layers
2885            // the child is marked as not dirty (flags cleared the last time
2886            // the child was drawn inside its layer.) However, that child might
2887            // never have created its own display list or have an obsolete
2888            // display list. By invalidating the child we ensure the display
2889            // list is in sync with the content of the hardware layer.
2890            for (int i = 0; i < mChildrenCount; i++) {
2891                View child = mChildren[i];
2892                if (child.mLayerType != LAYER_TYPE_NONE) {
2893                    child.invalidate(true);
2894                }
2895            }
2896        }
2897    }
2898
2899    /**
2900     * By default, children are clipped to their bounds before drawing. This
2901     * allows view groups to override this behavior for animations, etc.
2902     *
2903     * @param clipChildren true to clip children to their bounds,
2904     *        false otherwise
2905     * @attr ref android.R.styleable#ViewGroup_clipChildren
2906     */
2907    public void setClipChildren(boolean clipChildren) {
2908        setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren);
2909    }
2910
2911    /**
2912     * By default, children are clipped to the padding of the ViewGroup. This
2913     * allows view groups to override this behavior
2914     *
2915     * @param clipToPadding true to clip children to the padding of the
2916     *        group, false otherwise
2917     * @attr ref android.R.styleable#ViewGroup_clipToPadding
2918     */
2919    public void setClipToPadding(boolean clipToPadding) {
2920        setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
2921    }
2922
2923    /**
2924     * {@inheritDoc}
2925     */
2926    @Override
2927    public void dispatchSetSelected(boolean selected) {
2928        final View[] children = mChildren;
2929        final int count = mChildrenCount;
2930        for (int i = 0; i < count; i++) {
2931            children[i].setSelected(selected);
2932        }
2933    }
2934
2935    /**
2936     * {@inheritDoc}
2937     */
2938    @Override
2939    public void dispatchSetActivated(boolean activated) {
2940        final View[] children = mChildren;
2941        final int count = mChildrenCount;
2942        for (int i = 0; i < count; i++) {
2943            children[i].setActivated(activated);
2944        }
2945    }
2946
2947    @Override
2948    protected void dispatchSetPressed(boolean pressed) {
2949        final View[] children = mChildren;
2950        final int count = mChildrenCount;
2951        for (int i = 0; i < count; i++) {
2952            children[i].setPressed(pressed);
2953        }
2954    }
2955
2956    /**
2957     * When this property is set to true, this ViewGroup supports static transformations on
2958     * children; this causes
2959     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
2960     * invoked when a child is drawn.
2961     *
2962     * Any subclass overriding
2963     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
2964     * set this property to true.
2965     *
2966     * @param enabled True to enable static transformations on children, false otherwise.
2967     *
2968     * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS
2969     */
2970    protected void setStaticTransformationsEnabled(boolean enabled) {
2971        setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled);
2972    }
2973
2974    /**
2975     * {@inheritDoc}
2976     *
2977     * @see #setStaticTransformationsEnabled(boolean)
2978     */
2979    protected boolean getChildStaticTransformation(View child, Transformation t) {
2980        return false;
2981    }
2982
2983    /**
2984     * {@hide}
2985     */
2986    @Override
2987    protected View findViewTraversal(int id) {
2988        if (id == mID) {
2989            return this;
2990        }
2991
2992        final View[] where = mChildren;
2993        final int len = mChildrenCount;
2994
2995        for (int i = 0; i < len; i++) {
2996            View v = where[i];
2997
2998            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
2999                v = v.findViewById(id);
3000
3001                if (v != null) {
3002                    return v;
3003                }
3004            }
3005        }
3006
3007        return null;
3008    }
3009
3010    /**
3011     * {@hide}
3012     */
3013    @Override
3014    protected View findViewWithTagTraversal(Object tag) {
3015        if (tag != null && tag.equals(mTag)) {
3016            return this;
3017        }
3018
3019        final View[] where = mChildren;
3020        final int len = mChildrenCount;
3021
3022        for (int i = 0; i < len; i++) {
3023            View v = where[i];
3024
3025            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3026                v = v.findViewWithTag(tag);
3027
3028                if (v != null) {
3029                    return v;
3030                }
3031            }
3032        }
3033
3034        return null;
3035    }
3036
3037    /**
3038     * {@hide}
3039     */
3040    @Override
3041    protected View findViewByPredicateTraversal(Predicate<View> predicate) {
3042        if (predicate.apply(this)) {
3043            return this;
3044        }
3045
3046        final View[] where = mChildren;
3047        final int len = mChildrenCount;
3048
3049        for (int i = 0; i < len; i++) {
3050            View v = where[i];
3051
3052            if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
3053                v = v.findViewByPredicate(predicate);
3054
3055                if (v != null) {
3056                    return v;
3057                }
3058            }
3059        }
3060
3061        return null;
3062    }
3063
3064    /**
3065     * Adds a child view. If no layout parameters are already set on the child, the
3066     * default parameters for this ViewGroup are set on the child.
3067     *
3068     * @param child the child view to add
3069     *
3070     * @see #generateDefaultLayoutParams()
3071     */
3072    public void addView(View child) {
3073        addView(child, -1);
3074    }
3075
3076    /**
3077     * Adds a child view. If no layout parameters are already set on the child, the
3078     * default parameters for this ViewGroup are set on the child.
3079     *
3080     * @param child the child view to add
3081     * @param index the position at which to add the child
3082     *
3083     * @see #generateDefaultLayoutParams()
3084     */
3085    public void addView(View child, int index) {
3086        LayoutParams params = child.getLayoutParams();
3087        if (params == null) {
3088            params = generateDefaultLayoutParams();
3089            if (params == null) {
3090                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
3091            }
3092        }
3093        addView(child, index, params);
3094    }
3095
3096    /**
3097     * Adds a child view with this ViewGroup's default layout parameters and the
3098     * specified width and height.
3099     *
3100     * @param child the child view to add
3101     */
3102    public void addView(View child, int width, int height) {
3103        final LayoutParams params = generateDefaultLayoutParams();
3104        params.width = width;
3105        params.height = height;
3106        addView(child, -1, params);
3107    }
3108
3109    /**
3110     * Adds a child view with the specified layout parameters.
3111     *
3112     * @param child the child view to add
3113     * @param params the layout parameters to set on the child
3114     */
3115    public void addView(View child, LayoutParams params) {
3116        addView(child, -1, params);
3117    }
3118
3119    /**
3120     * Adds a child view with the specified layout parameters.
3121     *
3122     * @param child the child view to add
3123     * @param index the position at which to add the child
3124     * @param params the layout parameters to set on the child
3125     */
3126    public void addView(View child, int index, LayoutParams params) {
3127        if (DBG) {
3128            System.out.println(this + " addView");
3129        }
3130
3131        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
3132        // therefore, we call requestLayout() on ourselves before, so that the child's request
3133        // will be blocked at our level
3134        requestLayout();
3135        invalidate(true);
3136        addViewInner(child, index, params, false);
3137    }
3138
3139    /**
3140     * {@inheritDoc}
3141     */
3142    public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
3143        if (!checkLayoutParams(params)) {
3144            throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this);
3145        }
3146        if (view.mParent != this) {
3147            throw new IllegalArgumentException("Given view not a child of " + this);
3148        }
3149        view.setLayoutParams(params);
3150    }
3151
3152    /**
3153     * {@inheritDoc}
3154     */
3155    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
3156        return  p != null;
3157    }
3158
3159    /**
3160     * Interface definition for a callback to be invoked when the hierarchy
3161     * within this view changed. The hierarchy changes whenever a child is added
3162     * to or removed from this view.
3163     */
3164    public interface OnHierarchyChangeListener {
3165        /**
3166         * Called when a new child is added to a parent view.
3167         *
3168         * @param parent the view in which a child was added
3169         * @param child the new child view added in the hierarchy
3170         */
3171        void onChildViewAdded(View parent, View child);
3172
3173        /**
3174         * Called when a child is removed from a parent view.
3175         *
3176         * @param parent the view from which the child was removed
3177         * @param child the child removed from the hierarchy
3178         */
3179        void onChildViewRemoved(View parent, View child);
3180    }
3181
3182    /**
3183     * Register a callback to be invoked when a child is added to or removed
3184     * from this view.
3185     *
3186     * @param listener the callback to invoke on hierarchy change
3187     */
3188    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
3189        mOnHierarchyChangeListener = listener;
3190    }
3191
3192    /**
3193     * @hide
3194     */
3195    protected void onViewAdded(View child) {
3196        if (mOnHierarchyChangeListener != null) {
3197            mOnHierarchyChangeListener.onChildViewAdded(this, child);
3198        }
3199    }
3200
3201    /**
3202     * @hide
3203     */
3204    protected void onViewRemoved(View child) {
3205        if (mOnHierarchyChangeListener != null) {
3206            mOnHierarchyChangeListener.onChildViewRemoved(this, child);
3207        }
3208    }
3209
3210    /**
3211     * Adds a view during layout. This is useful if in your onLayout() method,
3212     * you need to add more views (as does the list view for example).
3213     *
3214     * If index is negative, it means put it at the end of the list.
3215     *
3216     * @param child the view to add to the group
3217     * @param index the index at which the child must be added
3218     * @param params the layout parameters to associate with the child
3219     * @return true if the child was added, false otherwise
3220     */
3221    protected boolean addViewInLayout(View child, int index, LayoutParams params) {
3222        return addViewInLayout(child, index, params, false);
3223    }
3224
3225    /**
3226     * Adds a view during layout. This is useful if in your onLayout() method,
3227     * you need to add more views (as does the list view for example).
3228     *
3229     * If index is negative, it means put it at the end of the list.
3230     *
3231     * @param child the view to add to the group
3232     * @param index the index at which the child must be added
3233     * @param params the layout parameters to associate with the child
3234     * @param preventRequestLayout if true, calling this method will not trigger a
3235     *        layout request on child
3236     * @return true if the child was added, false otherwise
3237     */
3238    protected boolean addViewInLayout(View child, int index, LayoutParams params,
3239            boolean preventRequestLayout) {
3240        child.mParent = null;
3241        addViewInner(child, index, params, preventRequestLayout);
3242        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN;
3243        return true;
3244    }
3245
3246    /**
3247     * Prevents the specified child to be laid out during the next layout pass.
3248     *
3249     * @param child the child on which to perform the cleanup
3250     */
3251    protected void cleanupLayoutState(View child) {
3252        child.mPrivateFlags &= ~View.FORCE_LAYOUT;
3253    }
3254
3255    private void addViewInner(View child, int index, LayoutParams params,
3256            boolean preventRequestLayout) {
3257
3258        if (mTransition != null) {
3259            // Don't prevent other add transitions from completing, but cancel remove
3260            // transitions to let them complete the process before we add to the container
3261            mTransition.cancel(LayoutTransition.DISAPPEARING);
3262        }
3263
3264        if (child.getParent() != null) {
3265            throw new IllegalStateException("The specified child already has a parent. " +
3266                    "You must call removeView() on the child's parent first.");
3267        }
3268
3269        if (mTransition != null) {
3270            mTransition.addChild(this, child);
3271        }
3272
3273        if (!checkLayoutParams(params)) {
3274            params = generateLayoutParams(params);
3275        }
3276
3277        if (preventRequestLayout) {
3278            child.mLayoutParams = params;
3279        } else {
3280            child.setLayoutParams(params);
3281        }
3282
3283        if (index < 0) {
3284            index = mChildrenCount;
3285        }
3286
3287        addInArray(child, index);
3288
3289        // tell our children
3290        if (preventRequestLayout) {
3291            child.assignParent(this);
3292        } else {
3293            child.mParent = this;
3294        }
3295
3296        if (child.hasFocus()) {
3297            requestChildFocus(child, child.findFocus());
3298        }
3299
3300        AttachInfo ai = mAttachInfo;
3301        if (ai != null) {
3302            boolean lastKeepOn = ai.mKeepScreenOn;
3303            ai.mKeepScreenOn = false;
3304            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
3305            if (ai.mKeepScreenOn) {
3306                needGlobalAttributesUpdate(true);
3307            }
3308            ai.mKeepScreenOn = lastKeepOn;
3309        }
3310
3311        onViewAdded(child);
3312
3313        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
3314            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
3315        }
3316    }
3317
3318    private void addInArray(View child, int index) {
3319        View[] children = mChildren;
3320        final int count = mChildrenCount;
3321        final int size = children.length;
3322        if (index == count) {
3323            if (size == count) {
3324                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3325                System.arraycopy(children, 0, mChildren, 0, size);
3326                children = mChildren;
3327            }
3328            children[mChildrenCount++] = child;
3329        } else if (index < count) {
3330            if (size == count) {
3331                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3332                System.arraycopy(children, 0, mChildren, 0, index);
3333                System.arraycopy(children, index, mChildren, index + 1, count - index);
3334                children = mChildren;
3335            } else {
3336                System.arraycopy(children, index, children, index + 1, count - index);
3337            }
3338            children[index] = child;
3339            mChildrenCount++;
3340            if (mLastTouchDownIndex >= index) {
3341                mLastTouchDownIndex++;
3342            }
3343        } else {
3344            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
3345        }
3346    }
3347
3348    // This method also sets the child's mParent to null
3349    private void removeFromArray(int index) {
3350        final View[] children = mChildren;
3351        if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
3352            children[index].mParent = null;
3353        }
3354        final int count = mChildrenCount;
3355        if (index == count - 1) {
3356            children[--mChildrenCount] = null;
3357        } else if (index >= 0 && index < count) {
3358            System.arraycopy(children, index + 1, children, index, count - index - 1);
3359            children[--mChildrenCount] = null;
3360        } else {
3361            throw new IndexOutOfBoundsException();
3362        }
3363        if (mLastTouchDownIndex == index) {
3364            mLastTouchDownTime = 0;
3365            mLastTouchDownIndex = -1;
3366        } else if (mLastTouchDownIndex > index) {
3367            mLastTouchDownIndex--;
3368        }
3369    }
3370
3371    // This method also sets the children's mParent to null
3372    private void removeFromArray(int start, int count) {
3373        final View[] children = mChildren;
3374        final int childrenCount = mChildrenCount;
3375
3376        start = Math.max(0, start);
3377        final int end = Math.min(childrenCount, start + count);
3378
3379        if (start == end) {
3380            return;
3381        }
3382
3383        if (end == childrenCount) {
3384            for (int i = start; i < end; i++) {
3385                children[i].mParent = null;
3386                children[i] = null;
3387            }
3388        } else {
3389            for (int i = start; i < end; i++) {
3390                children[i].mParent = null;
3391            }
3392
3393            // Since we're looping above, we might as well do the copy, but is arraycopy()
3394            // faster than the extra 2 bounds checks we would do in the loop?
3395            System.arraycopy(children, end, children, start, childrenCount - end);
3396
3397            for (int i = childrenCount - (end - start); i < childrenCount; i++) {
3398                children[i] = null;
3399            }
3400        }
3401
3402        mChildrenCount -= (end - start);
3403    }
3404
3405    private void bindLayoutAnimation(View child) {
3406        Animation a = mLayoutAnimationController.getAnimationForView(child);
3407        child.setAnimation(a);
3408    }
3409
3410    /**
3411     * Subclasses should override this method to set layout animation
3412     * parameters on the supplied child.
3413     *
3414     * @param child the child to associate with animation parameters
3415     * @param params the child's layout parameters which hold the animation
3416     *        parameters
3417     * @param index the index of the child in the view group
3418     * @param count the number of children in the view group
3419     */
3420    protected void attachLayoutAnimationParameters(View child,
3421            LayoutParams params, int index, int count) {
3422        LayoutAnimationController.AnimationParameters animationParams =
3423                    params.layoutAnimationParameters;
3424        if (animationParams == null) {
3425            animationParams = new LayoutAnimationController.AnimationParameters();
3426            params.layoutAnimationParameters = animationParams;
3427        }
3428
3429        animationParams.count = count;
3430        animationParams.index = index;
3431    }
3432
3433    /**
3434     * {@inheritDoc}
3435     */
3436    public void removeView(View view) {
3437        removeViewInternal(view);
3438        requestLayout();
3439        invalidate(true);
3440    }
3441
3442    /**
3443     * Removes a view during layout. This is useful if in your onLayout() method,
3444     * you need to remove more views.
3445     *
3446     * @param view the view to remove from the group
3447     */
3448    public void removeViewInLayout(View view) {
3449        removeViewInternal(view);
3450    }
3451
3452    /**
3453     * Removes a range of views during layout. This is useful if in your onLayout() method,
3454     * you need to remove more views.
3455     *
3456     * @param start the index of the first view to remove from the group
3457     * @param count the number of views to remove from the group
3458     */
3459    public void removeViewsInLayout(int start, int count) {
3460        removeViewsInternal(start, count);
3461    }
3462
3463    /**
3464     * Removes the view at the specified position in the group.
3465     *
3466     * @param index the position in the group of the view to remove
3467     */
3468    public void removeViewAt(int index) {
3469        removeViewInternal(index, getChildAt(index));
3470        requestLayout();
3471        invalidate(true);
3472    }
3473
3474    /**
3475     * Removes the specified range of views from the group.
3476     *
3477     * @param start the first position in the group of the range of views to remove
3478     * @param count the number of views to remove
3479     */
3480    public void removeViews(int start, int count) {
3481        removeViewsInternal(start, count);
3482        requestLayout();
3483        invalidate(true);
3484    }
3485
3486    private void removeViewInternal(View view) {
3487        final int index = indexOfChild(view);
3488        if (index >= 0) {
3489            removeViewInternal(index, view);
3490        }
3491    }
3492
3493    private void removeViewInternal(int index, View view) {
3494
3495        if (mTransition != null) {
3496            mTransition.removeChild(this, view);
3497        }
3498
3499        boolean clearChildFocus = false;
3500        if (view == mFocused) {
3501            view.clearFocusForRemoval();
3502            clearChildFocus = true;
3503        }
3504
3505        if (view.getAnimation() != null ||
3506                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3507            addDisappearingView(view);
3508        } else if (view.mAttachInfo != null) {
3509           view.dispatchDetachedFromWindow();
3510        }
3511
3512        onViewRemoved(view);
3513
3514        needGlobalAttributesUpdate(false);
3515
3516        removeFromArray(index);
3517
3518        if (clearChildFocus) {
3519            clearChildFocus(view);
3520        }
3521    }
3522
3523    /**
3524     * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3525     * not null, changes in layout which occur because of children being added to or removed from
3526     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3527     * object. By default, the transition object is null (so layout changes are not animated).
3528     *
3529     * @param transition The LayoutTransition object that will animated changes in layout. A value
3530     * of <code>null</code> means no transition will run on layout changes.
3531     * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
3532     */
3533    public void setLayoutTransition(LayoutTransition transition) {
3534        if (mTransition != null) {
3535            mTransition.removeTransitionListener(mLayoutTransitionListener);
3536        }
3537        mTransition = transition;
3538        if (mTransition != null) {
3539            mTransition.addTransitionListener(mLayoutTransitionListener);
3540        }
3541    }
3542
3543    /**
3544     * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3545     * not null, changes in layout which occur because of children being added to or removed from
3546     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3547     * object. By default, the transition object is null (so layout changes are not animated).
3548     *
3549     * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
3550     * A value of <code>null</code> means no transition will run on layout changes.
3551     */
3552    public LayoutTransition getLayoutTransition() {
3553        return mTransition;
3554    }
3555
3556    private void removeViewsInternal(int start, int count) {
3557        final View focused = mFocused;
3558        final boolean detach = mAttachInfo != null;
3559        View clearChildFocus = null;
3560
3561        final View[] children = mChildren;
3562        final int end = start + count;
3563
3564        for (int i = start; i < end; i++) {
3565            final View view = children[i];
3566
3567            if (mTransition != null) {
3568                mTransition.removeChild(this, view);
3569            }
3570
3571            if (view == focused) {
3572                view.clearFocusForRemoval();
3573                clearChildFocus = view;
3574            }
3575
3576            if (view.getAnimation() != null ||
3577                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3578                addDisappearingView(view);
3579            } else if (detach) {
3580               view.dispatchDetachedFromWindow();
3581            }
3582
3583            needGlobalAttributesUpdate(false);
3584
3585            onViewRemoved(view);
3586        }
3587
3588        removeFromArray(start, count);
3589
3590        if (clearChildFocus != null) {
3591            clearChildFocus(clearChildFocus);
3592        }
3593    }
3594
3595    /**
3596     * Call this method to remove all child views from the
3597     * ViewGroup.
3598     */
3599    public void removeAllViews() {
3600        removeAllViewsInLayout();
3601        requestLayout();
3602        invalidate(true);
3603    }
3604
3605    /**
3606     * Called by a ViewGroup subclass to remove child views from itself,
3607     * when it must first know its size on screen before it can calculate how many
3608     * child views it will render. An example is a Gallery or a ListView, which
3609     * may "have" 50 children, but actually only render the number of children
3610     * that can currently fit inside the object on screen. Do not call
3611     * this method unless you are extending ViewGroup and understand the
3612     * view measuring and layout pipeline.
3613     */
3614    public void removeAllViewsInLayout() {
3615        final int count = mChildrenCount;
3616        if (count <= 0) {
3617            return;
3618        }
3619
3620        final View[] children = mChildren;
3621        mChildrenCount = 0;
3622
3623        final View focused = mFocused;
3624        final boolean detach = mAttachInfo != null;
3625        View clearChildFocus = null;
3626
3627        needGlobalAttributesUpdate(false);
3628
3629        for (int i = count - 1; i >= 0; i--) {
3630            final View view = children[i];
3631
3632            if (mTransition != null) {
3633                mTransition.removeChild(this, view);
3634            }
3635
3636            if (view == focused) {
3637                view.clearFocusForRemoval();
3638                clearChildFocus = view;
3639            }
3640
3641            if (view.getAnimation() != null ||
3642                    (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3643                addDisappearingView(view);
3644            } else if (detach) {
3645               view.dispatchDetachedFromWindow();
3646            }
3647
3648            onViewRemoved(view);
3649
3650            view.mParent = null;
3651            children[i] = null;
3652        }
3653
3654        if (clearChildFocus != null) {
3655            clearChildFocus(clearChildFocus);
3656        }
3657    }
3658
3659    /**
3660     * Finishes the removal of a detached view. This method will dispatch the detached from
3661     * window event and notify the hierarchy change listener.
3662     *
3663     * @param child the child to be definitely removed from the view hierarchy
3664     * @param animate if true and the view has an animation, the view is placed in the
3665     *                disappearing views list, otherwise, it is detached from the window
3666     *
3667     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3668     * @see #detachAllViewsFromParent()
3669     * @see #detachViewFromParent(View)
3670     * @see #detachViewFromParent(int)
3671     */
3672    protected void removeDetachedView(View child, boolean animate) {
3673        if (mTransition != null) {
3674            mTransition.removeChild(this, child);
3675        }
3676
3677        if (child == mFocused) {
3678            child.clearFocus();
3679        }
3680
3681        if ((animate && child.getAnimation() != null) ||
3682                (mTransitioningViews != null && mTransitioningViews.contains(child))) {
3683            addDisappearingView(child);
3684        } else if (child.mAttachInfo != null) {
3685            child.dispatchDetachedFromWindow();
3686        }
3687
3688        onViewRemoved(child);
3689    }
3690
3691    /**
3692     * Attaches a view to this view group. Attaching a view assigns this group as the parent,
3693     * sets the layout parameters and puts the view in the list of children so it can be retrieved
3694     * by calling {@link #getChildAt(int)}.
3695     *
3696     * This method should be called only for view which were detached from their parent.
3697     *
3698     * @param child the child to attach
3699     * @param index the index at which the child should be attached
3700     * @param params the layout parameters of the child
3701     *
3702     * @see #removeDetachedView(View, boolean)
3703     * @see #detachAllViewsFromParent()
3704     * @see #detachViewFromParent(View)
3705     * @see #detachViewFromParent(int)
3706     */
3707    protected void attachViewToParent(View child, int index, LayoutParams params) {
3708        child.mLayoutParams = params;
3709
3710        if (index < 0) {
3711            index = mChildrenCount;
3712        }
3713
3714        addInArray(child, index);
3715
3716        child.mParent = this;
3717        child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) |
3718                DRAWN | INVALIDATED;
3719        this.mPrivateFlags |= INVALIDATED;
3720
3721        if (child.hasFocus()) {
3722            requestChildFocus(child, child.findFocus());
3723        }
3724    }
3725
3726    /**
3727     * Detaches a view from its parent. Detaching a view should be temporary and followed
3728     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3729     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3730     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3731     *
3732     * @param child the child to detach
3733     *
3734     * @see #detachViewFromParent(int)
3735     * @see #detachViewsFromParent(int, int)
3736     * @see #detachAllViewsFromParent()
3737     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3738     * @see #removeDetachedView(View, boolean)
3739     */
3740    protected void detachViewFromParent(View child) {
3741        removeFromArray(indexOfChild(child));
3742    }
3743
3744    /**
3745     * Detaches a view from its parent. Detaching a view should be temporary and followed
3746     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3747     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3748     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3749     *
3750     * @param index the index of the child to detach
3751     *
3752     * @see #detachViewFromParent(View)
3753     * @see #detachAllViewsFromParent()
3754     * @see #detachViewsFromParent(int, int)
3755     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3756     * @see #removeDetachedView(View, boolean)
3757     */
3758    protected void detachViewFromParent(int index) {
3759        removeFromArray(index);
3760    }
3761
3762    /**
3763     * Detaches a range of view from their parent. Detaching a view should be temporary and followed
3764     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3765     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its
3766     * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3767     *
3768     * @param start the first index of the childrend range to detach
3769     * @param count the number of children to detach
3770     *
3771     * @see #detachViewFromParent(View)
3772     * @see #detachViewFromParent(int)
3773     * @see #detachAllViewsFromParent()
3774     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3775     * @see #removeDetachedView(View, boolean)
3776     */
3777    protected void detachViewsFromParent(int start, int count) {
3778        removeFromArray(start, count);
3779    }
3780
3781    /**
3782     * Detaches all views from the parent. Detaching a view should be temporary and followed
3783     * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3784     * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
3785     * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
3786     *
3787     * @see #detachViewFromParent(View)
3788     * @see #detachViewFromParent(int)
3789     * @see #detachViewsFromParent(int, int)
3790     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3791     * @see #removeDetachedView(View, boolean)
3792     */
3793    protected void detachAllViewsFromParent() {
3794        final int count = mChildrenCount;
3795        if (count <= 0) {
3796            return;
3797        }
3798
3799        final View[] children = mChildren;
3800        mChildrenCount = 0;
3801
3802        for (int i = count - 1; i >= 0; i--) {
3803            children[i].mParent = null;
3804            children[i] = null;
3805        }
3806    }
3807
3808    /**
3809     * Don't call or override this method. It is used for the implementation of
3810     * the view hierarchy.
3811     */
3812    public final void invalidateChild(View child, final Rect dirty) {
3813        if (ViewDebug.TRACE_HIERARCHY) {
3814            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD);
3815        }
3816
3817        ViewParent parent = this;
3818
3819        final AttachInfo attachInfo = mAttachInfo;
3820        if (attachInfo != null) {
3821            // If the child is drawing an animation, we want to copy this flag onto
3822            // ourselves and the parent to make sure the invalidate request goes
3823            // through
3824            final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;
3825
3826            if (dirty == null) {
3827                if (child.mLayerType != LAYER_TYPE_NONE) {
3828                    mPrivateFlags |= INVALIDATED;
3829                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
3830                    child.mLocalDirtyRect.setEmpty();
3831                }
3832                do {
3833                    View view = null;
3834                    if (parent instanceof View) {
3835                        view = (View) parent;
3836                        if (view.mLayerType != LAYER_TYPE_NONE) {
3837                            view.mLocalDirtyRect.setEmpty();
3838                            if (view.getParent() instanceof View) {
3839                                final View grandParent = (View) view.getParent();
3840                                grandParent.mPrivateFlags |= INVALIDATED;
3841                                grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID;
3842                            }
3843                        }
3844                        if ((view.mPrivateFlags & DIRTY_MASK) != 0) {
3845                            // already marked dirty - we're done
3846                            break;
3847                        }
3848                    }
3849
3850                    if (drawAnimation) {
3851                        if (view != null) {
3852                            view.mPrivateFlags |= DRAW_ANIMATION;
3853                        } else if (parent instanceof ViewRootImpl) {
3854                            ((ViewRootImpl) parent).mIsAnimating = true;
3855                        }
3856                    }
3857
3858                    if (parent instanceof ViewRootImpl) {
3859                        ((ViewRootImpl) parent).invalidate();
3860                        parent = null;
3861                    } else if (view != null) {
3862                        if ((view.mPrivateFlags & DRAWN) == DRAWN ||
3863                                (view.mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
3864                            view.mPrivateFlags &= ~DRAWING_CACHE_VALID;
3865                            view.mPrivateFlags |= DIRTY;
3866                            parent = view.mParent;
3867                        } else {
3868                            parent = null;
3869                        }
3870                    }
3871                } while (parent != null);
3872            } else {
3873                // Check whether the child that requests the invalidate is fully opaque
3874                final boolean isOpaque = child.isOpaque() && !drawAnimation &&
3875                        child.getAnimation() == null;
3876                // Mark the child as dirty, using the appropriate flag
3877                // Make sure we do not set both flags at the same time
3878                int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
3879
3880                if (child.mLayerType != LAYER_TYPE_NONE) {
3881                    mPrivateFlags |= INVALIDATED;
3882                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
3883                    child.mLocalDirtyRect.union(dirty);
3884                }
3885
3886                final int[] location = attachInfo.mInvalidateChildLocation;
3887                location[CHILD_LEFT_INDEX] = child.mLeft;
3888                location[CHILD_TOP_INDEX] = child.mTop;
3889                Matrix childMatrix = child.getMatrix();
3890                if (!childMatrix.isIdentity()) {
3891                    RectF boundingRect = attachInfo.mTmpTransformRect;
3892                    boundingRect.set(dirty);
3893                    //boundingRect.inset(-0.5f, -0.5f);
3894                    childMatrix.mapRect(boundingRect);
3895                    dirty.set((int) (boundingRect.left - 0.5f),
3896                            (int) (boundingRect.top - 0.5f),
3897                            (int) (boundingRect.right + 0.5f),
3898                            (int) (boundingRect.bottom + 0.5f));
3899                }
3900
3901                do {
3902                    View view = null;
3903                    if (parent instanceof View) {
3904                        view = (View) parent;
3905                        if (view.mLayerType != LAYER_TYPE_NONE &&
3906                                view.getParent() instanceof View) {
3907                            final View grandParent = (View) view.getParent();
3908                            grandParent.mPrivateFlags |= INVALIDATED;
3909                            grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID;
3910                        }
3911                    }
3912
3913                    if (drawAnimation) {
3914                        if (view != null) {
3915                            view.mPrivateFlags |= DRAW_ANIMATION;
3916                        } else if (parent instanceof ViewRootImpl) {
3917                            ((ViewRootImpl) parent).mIsAnimating = true;
3918                        }
3919                    }
3920
3921                    // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
3922                    // flag coming from the child that initiated the invalidate
3923                    if (view != null) {
3924                        if ((view.mViewFlags & FADING_EDGE_MASK) != 0 &&
3925                                view.getSolidColor() == 0) {
3926                            opaqueFlag = DIRTY;
3927                        }
3928                        if ((view.mPrivateFlags & DIRTY_MASK) != DIRTY) {
3929                            view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;
3930                        }
3931                    }
3932
3933                    parent = parent.invalidateChildInParent(location, dirty);
3934                    if (view != null) {
3935                        // Account for transform on current parent
3936                        Matrix m = view.getMatrix();
3937                        if (!m.isIdentity()) {
3938                            RectF boundingRect = attachInfo.mTmpTransformRect;
3939                            boundingRect.set(dirty);
3940                            m.mapRect(boundingRect);
3941                            dirty.set((int) boundingRect.left, (int) boundingRect.top,
3942                                    (int) (boundingRect.right + 0.5f),
3943                                    (int) (boundingRect.bottom + 0.5f));
3944                        }
3945                    }
3946                } while (parent != null);
3947            }
3948        }
3949    }
3950
3951    /**
3952     * Don't call or override this method. It is used for the implementation of
3953     * the view hierarchy.
3954     *
3955     * This implementation returns null if this ViewGroup does not have a parent,
3956     * if this ViewGroup is already fully invalidated or if the dirty rectangle
3957     * does not intersect with this ViewGroup's bounds.
3958     */
3959    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
3960        if (ViewDebug.TRACE_HIERARCHY) {
3961            ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD_IN_PARENT);
3962        }
3963
3964        if ((mPrivateFlags & DRAWN) == DRAWN ||
3965                (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) {
3966            if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
3967                        FLAG_OPTIMIZE_INVALIDATE) {
3968                dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
3969                        location[CHILD_TOP_INDEX] - mScrollY);
3970
3971                final int left = mLeft;
3972                final int top = mTop;
3973
3974                if ((mGroupFlags & FLAG_CLIP_CHILDREN) != FLAG_CLIP_CHILDREN ||
3975                        dirty.intersect(0, 0, mRight - left, mBottom - top) ||
3976                        (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
3977                    mPrivateFlags &= ~DRAWING_CACHE_VALID;
3978
3979                    location[CHILD_LEFT_INDEX] = left;
3980                    location[CHILD_TOP_INDEX] = top;
3981
3982                    if (mLayerType != LAYER_TYPE_NONE) {
3983                        mLocalDirtyRect.union(dirty);
3984                    }
3985
3986                    return mParent;
3987                }
3988            } else {
3989                mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
3990
3991                location[CHILD_LEFT_INDEX] = mLeft;
3992                location[CHILD_TOP_INDEX] = mTop;
3993                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
3994                    dirty.set(0, 0, mRight - mLeft, mBottom - mTop);
3995                } else {
3996                    // in case the dirty rect extends outside the bounds of this container
3997                    dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
3998                }
3999
4000                if (mLayerType != LAYER_TYPE_NONE) {
4001                    mLocalDirtyRect.union(dirty);
4002                }
4003
4004                return mParent;
4005            }
4006        }
4007
4008        return null;
4009    }
4010
4011    /**
4012     * Offset a rectangle that is in a descendant's coordinate
4013     * space into our coordinate space.
4014     * @param descendant A descendant of this view
4015     * @param rect A rectangle defined in descendant's coordinate space.
4016     */
4017    public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) {
4018        offsetRectBetweenParentAndChild(descendant, rect, true, false);
4019    }
4020
4021    /**
4022     * Offset a rectangle that is in our coordinate space into an ancestor's
4023     * coordinate space.
4024     * @param descendant A descendant of this view
4025     * @param rect A rectangle defined in descendant's coordinate space.
4026     */
4027    public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) {
4028        offsetRectBetweenParentAndChild(descendant, rect, false, false);
4029    }
4030
4031    /**
4032     * Helper method that offsets a rect either from parent to descendant or
4033     * descendant to parent.
4034     */
4035    void offsetRectBetweenParentAndChild(View descendant, Rect rect,
4036            boolean offsetFromChildToParent, boolean clipToBounds) {
4037
4038        // already in the same coord system :)
4039        if (descendant == this) {
4040            return;
4041        }
4042
4043        ViewParent theParent = descendant.mParent;
4044
4045        // search and offset up to the parent
4046        while ((theParent != null)
4047                && (theParent instanceof View)
4048                && (theParent != this)) {
4049
4050            if (offsetFromChildToParent) {
4051                rect.offset(descendant.mLeft - descendant.mScrollX,
4052                        descendant.mTop - descendant.mScrollY);
4053                if (clipToBounds) {
4054                    View p = (View) theParent;
4055                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4056                }
4057            } else {
4058                if (clipToBounds) {
4059                    View p = (View) theParent;
4060                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4061                }
4062                rect.offset(descendant.mScrollX - descendant.mLeft,
4063                        descendant.mScrollY - descendant.mTop);
4064            }
4065
4066            descendant = (View) theParent;
4067            theParent = descendant.mParent;
4068        }
4069
4070        // now that we are up to this view, need to offset one more time
4071        // to get into our coordinate space
4072        if (theParent == this) {
4073            if (offsetFromChildToParent) {
4074                rect.offset(descendant.mLeft - descendant.mScrollX,
4075                        descendant.mTop - descendant.mScrollY);
4076            } else {
4077                rect.offset(descendant.mScrollX - descendant.mLeft,
4078                        descendant.mScrollY - descendant.mTop);
4079            }
4080        } else {
4081            throw new IllegalArgumentException("parameter must be a descendant of this view");
4082        }
4083    }
4084
4085    /**
4086     * Offset the vertical location of all children of this view by the specified number of pixels.
4087     *
4088     * @param offset the number of pixels to offset
4089     *
4090     * @hide
4091     */
4092    public void offsetChildrenTopAndBottom(int offset) {
4093        final int count = mChildrenCount;
4094        final View[] children = mChildren;
4095
4096        for (int i = 0; i < count; i++) {
4097            final View v = children[i];
4098            v.mTop += offset;
4099            v.mBottom += offset;
4100        }
4101    }
4102
4103    /**
4104     * {@inheritDoc}
4105     */
4106    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
4107        int dx = child.mLeft - mScrollX;
4108        int dy = child.mTop - mScrollY;
4109        if (offset != null) {
4110            offset.x += dx;
4111            offset.y += dy;
4112        }
4113        r.offset(dx, dy);
4114        return r.intersect(0, 0, mRight - mLeft, mBottom - mTop) &&
4115               (mParent == null || mParent.getChildVisibleRect(this, r, offset));
4116    }
4117
4118    /**
4119     * {@inheritDoc}
4120     */
4121    @Override
4122    public final void layout(int l, int t, int r, int b) {
4123        if (mTransition == null || !mTransition.isChangingLayout()) {
4124            super.layout(l, t, r, b);
4125        } else {
4126            // record the fact that we noop'd it; request layout when transition finishes
4127            mLayoutSuppressed = true;
4128        }
4129    }
4130
4131    /**
4132     * {@inheritDoc}
4133     */
4134    @Override
4135    protected abstract void onLayout(boolean changed,
4136            int l, int t, int r, int b);
4137
4138    /**
4139     * Indicates whether the view group has the ability to animate its children
4140     * after the first layout.
4141     *
4142     * @return true if the children can be animated, false otherwise
4143     */
4144    protected boolean canAnimate() {
4145        return mLayoutAnimationController != null;
4146    }
4147
4148    /**
4149     * Runs the layout animation. Calling this method triggers a relayout of
4150     * this view group.
4151     */
4152    public void startLayoutAnimation() {
4153        if (mLayoutAnimationController != null) {
4154            mGroupFlags |= FLAG_RUN_ANIMATION;
4155            requestLayout();
4156        }
4157    }
4158
4159    /**
4160     * Schedules the layout animation to be played after the next layout pass
4161     * of this view group. This can be used to restart the layout animation
4162     * when the content of the view group changes or when the activity is
4163     * paused and resumed.
4164     */
4165    public void scheduleLayoutAnimation() {
4166        mGroupFlags |= FLAG_RUN_ANIMATION;
4167    }
4168
4169    /**
4170     * Sets the layout animation controller used to animate the group's
4171     * children after the first layout.
4172     *
4173     * @param controller the animation controller
4174     */
4175    public void setLayoutAnimation(LayoutAnimationController controller) {
4176        mLayoutAnimationController = controller;
4177        if (mLayoutAnimationController != null) {
4178            mGroupFlags |= FLAG_RUN_ANIMATION;
4179        }
4180    }
4181
4182    /**
4183     * Returns the layout animation controller used to animate the group's
4184     * children.
4185     *
4186     * @return the current animation controller
4187     */
4188    public LayoutAnimationController getLayoutAnimation() {
4189        return mLayoutAnimationController;
4190    }
4191
4192    /**
4193     * Indicates whether the children's drawing cache is used during a layout
4194     * animation. By default, the drawing cache is enabled but this will prevent
4195     * nested layout animations from working. To nest animations, you must disable
4196     * the cache.
4197     *
4198     * @return true if the animation cache is enabled, false otherwise
4199     *
4200     * @see #setAnimationCacheEnabled(boolean)
4201     * @see View#setDrawingCacheEnabled(boolean)
4202     */
4203    @ViewDebug.ExportedProperty
4204    public boolean isAnimationCacheEnabled() {
4205        return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
4206    }
4207
4208    /**
4209     * Enables or disables the children's drawing cache during a layout animation.
4210     * By default, the drawing cache is enabled but this will prevent nested
4211     * layout animations from working. To nest animations, you must disable the
4212     * cache.
4213     *
4214     * @param enabled true to enable the animation cache, false otherwise
4215     *
4216     * @see #isAnimationCacheEnabled()
4217     * @see View#setDrawingCacheEnabled(boolean)
4218     */
4219    public void setAnimationCacheEnabled(boolean enabled) {
4220        setBooleanFlag(FLAG_ANIMATION_CACHE, enabled);
4221    }
4222
4223    /**
4224     * Indicates whether this ViewGroup will always try to draw its children using their
4225     * drawing cache. By default this property is enabled.
4226     *
4227     * @return true if the animation cache is enabled, false otherwise
4228     *
4229     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4230     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4231     * @see View#setDrawingCacheEnabled(boolean)
4232     */
4233    @ViewDebug.ExportedProperty(category = "drawing")
4234    public boolean isAlwaysDrawnWithCacheEnabled() {
4235        return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE;
4236    }
4237
4238    /**
4239     * Indicates whether this ViewGroup will always try to draw its children using their
4240     * drawing cache. This property can be set to true when the cache rendering is
4241     * slightly different from the children's normal rendering. Renderings can be different,
4242     * for instance, when the cache's quality is set to low.
4243     *
4244     * When this property is disabled, the ViewGroup will use the drawing cache of its
4245     * children only when asked to. It's usually the task of subclasses to tell ViewGroup
4246     * when to start using the drawing cache and when to stop using it.
4247     *
4248     * @param always true to always draw with the drawing cache, false otherwise
4249     *
4250     * @see #isAlwaysDrawnWithCacheEnabled()
4251     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4252     * @see View#setDrawingCacheEnabled(boolean)
4253     * @see View#setDrawingCacheQuality(int)
4254     */
4255    public void setAlwaysDrawnWithCacheEnabled(boolean always) {
4256        setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always);
4257    }
4258
4259    /**
4260     * Indicates whether the ViewGroup is currently drawing its children using
4261     * their drawing cache.
4262     *
4263     * @return true if children should be drawn with their cache, false otherwise
4264     *
4265     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4266     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4267     */
4268    @ViewDebug.ExportedProperty(category = "drawing")
4269    protected boolean isChildrenDrawnWithCacheEnabled() {
4270        return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE;
4271    }
4272
4273    /**
4274     * Tells the ViewGroup to draw its children using their drawing cache. This property
4275     * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache
4276     * will be used only if it has been enabled.
4277     *
4278     * Subclasses should call this method to start and stop using the drawing cache when
4279     * they perform performance sensitive operations, like scrolling or animating.
4280     *
4281     * @param enabled true if children should be drawn with their cache, false otherwise
4282     *
4283     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4284     * @see #isChildrenDrawnWithCacheEnabled()
4285     */
4286    protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
4287        setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled);
4288    }
4289
4290    /**
4291     * Indicates whether the ViewGroup is drawing its children in the order defined by
4292     * {@link #getChildDrawingOrder(int, int)}.
4293     *
4294     * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)},
4295     *         false otherwise
4296     *
4297     * @see #setChildrenDrawingOrderEnabled(boolean)
4298     * @see #getChildDrawingOrder(int, int)
4299     */
4300    @ViewDebug.ExportedProperty(category = "drawing")
4301    protected boolean isChildrenDrawingOrderEnabled() {
4302        return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER;
4303    }
4304
4305    /**
4306     * Tells the ViewGroup whether to draw its children in the order defined by the method
4307     * {@link #getChildDrawingOrder(int, int)}.
4308     *
4309     * @param enabled true if the order of the children when drawing is determined by
4310     *        {@link #getChildDrawingOrder(int, int)}, false otherwise
4311     *
4312     * @see #isChildrenDrawingOrderEnabled()
4313     * @see #getChildDrawingOrder(int, int)
4314     */
4315    protected void setChildrenDrawingOrderEnabled(boolean enabled) {
4316        setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled);
4317    }
4318
4319    private void setBooleanFlag(int flag, boolean value) {
4320        if (value) {
4321            mGroupFlags |= flag;
4322        } else {
4323            mGroupFlags &= ~flag;
4324        }
4325    }
4326
4327    /**
4328     * Returns an integer indicating what types of drawing caches are kept in memory.
4329     *
4330     * @see #setPersistentDrawingCache(int)
4331     * @see #setAnimationCacheEnabled(boolean)
4332     *
4333     * @return one or a combination of {@link #PERSISTENT_NO_CACHE},
4334     *         {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4335     *         and {@link #PERSISTENT_ALL_CACHES}
4336     */
4337    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4338        @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE,        to = "NONE"),
4339        @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"),
4340        @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"),
4341        @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES,      to = "ALL")
4342    })
4343    public int getPersistentDrawingCache() {
4344        return mPersistentDrawingCache;
4345    }
4346
4347    /**
4348     * Indicates what types of drawing caches should be kept in memory after
4349     * they have been created.
4350     *
4351     * @see #getPersistentDrawingCache()
4352     * @see #setAnimationCacheEnabled(boolean)
4353     *
4354     * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE},
4355     *        {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4356     *        and {@link #PERSISTENT_ALL_CACHES}
4357     */
4358    public void setPersistentDrawingCache(int drawingCacheToKeep) {
4359        mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES;
4360    }
4361
4362    /**
4363     * Returns a new set of layout parameters based on the supplied attributes set.
4364     *
4365     * @param attrs the attributes to build the layout parameters from
4366     *
4367     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4368     *         of its descendants
4369     */
4370    public LayoutParams generateLayoutParams(AttributeSet attrs) {
4371        return new LayoutParams(getContext(), attrs);
4372    }
4373
4374    /**
4375     * Returns a safe set of layout parameters based on the supplied layout params.
4376     * When a ViewGroup is passed a View whose layout params do not pass the test of
4377     * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
4378     * is invoked. This method should return a new set of layout params suitable for
4379     * this ViewGroup, possibly by copying the appropriate attributes from the
4380     * specified set of layout params.
4381     *
4382     * @param p The layout parameters to convert into a suitable set of layout parameters
4383     *          for this ViewGroup.
4384     *
4385     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4386     *         of its descendants
4387     */
4388    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
4389        return p;
4390    }
4391
4392    /**
4393     * Returns a set of default layout parameters. These parameters are requested
4394     * when the View passed to {@link #addView(View)} has no layout parameters
4395     * already set. If null is returned, an exception is thrown from addView.
4396     *
4397     * @return a set of default layout parameters or null
4398     */
4399    protected LayoutParams generateDefaultLayoutParams() {
4400        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
4401    }
4402
4403    /**
4404     * @hide
4405     */
4406    @Override
4407    protected boolean dispatchConsistencyCheck(int consistency) {
4408        boolean result = super.dispatchConsistencyCheck(consistency);
4409
4410        final int count = mChildrenCount;
4411        final View[] children = mChildren;
4412        for (int i = 0; i < count; i++) {
4413            if (!children[i].dispatchConsistencyCheck(consistency)) result = false;
4414        }
4415
4416        return result;
4417    }
4418
4419    /**
4420     * @hide
4421     */
4422    @Override
4423    protected boolean onConsistencyCheck(int consistency) {
4424        boolean result = super.onConsistencyCheck(consistency);
4425
4426        final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
4427        final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
4428
4429        if (checkLayout) {
4430            final int count = mChildrenCount;
4431            final View[] children = mChildren;
4432            for (int i = 0; i < count; i++) {
4433                if (children[i].getParent() != this) {
4434                    result = false;
4435                    android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
4436                            "View " + children[i] + " has no parent/a parent that is not " + this);
4437                }
4438            }
4439        }
4440
4441        if (checkDrawing) {
4442            // If this group is dirty, check that the parent is dirty as well
4443            if ((mPrivateFlags & DIRTY_MASK) != 0) {
4444                final ViewParent parent = getParent();
4445                if (parent != null && !(parent instanceof ViewRootImpl)) {
4446                    if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) {
4447                        result = false;
4448                        android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
4449                                "ViewGroup " + this + " is dirty but its parent is not: " + this);
4450                    }
4451                }
4452            }
4453        }
4454
4455        return result;
4456    }
4457
4458    /**
4459     * {@inheritDoc}
4460     */
4461    @Override
4462    protected void debug(int depth) {
4463        super.debug(depth);
4464        String output;
4465
4466        if (mFocused != null) {
4467            output = debugIndent(depth);
4468            output += "mFocused";
4469            Log.d(VIEW_LOG_TAG, output);
4470        }
4471        if (mChildrenCount != 0) {
4472            output = debugIndent(depth);
4473            output += "{";
4474            Log.d(VIEW_LOG_TAG, output);
4475        }
4476        int count = mChildrenCount;
4477        for (int i = 0; i < count; i++) {
4478            View child = mChildren[i];
4479            child.debug(depth + 1);
4480        }
4481
4482        if (mChildrenCount != 0) {
4483            output = debugIndent(depth);
4484            output += "}";
4485            Log.d(VIEW_LOG_TAG, output);
4486        }
4487    }
4488
4489    /**
4490     * Returns the position in the group of the specified child view.
4491     *
4492     * @param child the view for which to get the position
4493     * @return a positive integer representing the position of the view in the
4494     *         group, or -1 if the view does not exist in the group
4495     */
4496    public int indexOfChild(View child) {
4497        final int count = mChildrenCount;
4498        final View[] children = mChildren;
4499        for (int i = 0; i < count; i++) {
4500            if (children[i] == child) {
4501                return i;
4502            }
4503        }
4504        return -1;
4505    }
4506
4507    /**
4508     * Returns the number of children in the group.
4509     *
4510     * @return a positive integer representing the number of children in
4511     *         the group
4512     */
4513    public int getChildCount() {
4514        return mChildrenCount;
4515    }
4516
4517    /**
4518     * Returns the view at the specified position in the group.
4519     *
4520     * @param index the position at which to get the view from
4521     * @return the view at the specified position or null if the position
4522     *         does not exist within the group
4523     */
4524    public View getChildAt(int index) {
4525        if (index < 0 || index >= mChildrenCount) {
4526            return null;
4527        }
4528        return mChildren[index];
4529    }
4530
4531    /**
4532     * Ask all of the children of this view to measure themselves, taking into
4533     * account both the MeasureSpec requirements for this view and its padding.
4534     * We skip children that are in the GONE state The heavy lifting is done in
4535     * getChildMeasureSpec.
4536     *
4537     * @param widthMeasureSpec The width requirements for this view
4538     * @param heightMeasureSpec The height requirements for this view
4539     */
4540    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
4541        final int size = mChildrenCount;
4542        final View[] children = mChildren;
4543        for (int i = 0; i < size; ++i) {
4544            final View child = children[i];
4545            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
4546                measureChild(child, widthMeasureSpec, heightMeasureSpec);
4547            }
4548        }
4549    }
4550
4551    /**
4552     * Ask one of the children of this view to measure itself, taking into
4553     * account both the MeasureSpec requirements for this view and its padding.
4554     * The heavy lifting is done in getChildMeasureSpec.
4555     *
4556     * @param child The child to measure
4557     * @param parentWidthMeasureSpec The width requirements for this view
4558     * @param parentHeightMeasureSpec The height requirements for this view
4559     */
4560    protected void measureChild(View child, int parentWidthMeasureSpec,
4561            int parentHeightMeasureSpec) {
4562        final LayoutParams lp = child.getLayoutParams();
4563
4564        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4565                mPaddingLeft + mPaddingRight, lp.width);
4566        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4567                mPaddingTop + mPaddingBottom, lp.height);
4568
4569        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4570    }
4571
4572    /**
4573     * Ask one of the children of this view to measure itself, taking into
4574     * account both the MeasureSpec requirements for this view and its padding
4575     * and margins. The child must have MarginLayoutParams The heavy lifting is
4576     * done in getChildMeasureSpec.
4577     *
4578     * @param child The child to measure
4579     * @param parentWidthMeasureSpec The width requirements for this view
4580     * @param widthUsed Extra space that has been used up by the parent
4581     *        horizontally (possibly by other children of the parent)
4582     * @param parentHeightMeasureSpec The height requirements for this view
4583     * @param heightUsed Extra space that has been used up by the parent
4584     *        vertically (possibly by other children of the parent)
4585     */
4586    protected void measureChildWithMargins(View child,
4587            int parentWidthMeasureSpec, int widthUsed,
4588            int parentHeightMeasureSpec, int heightUsed) {
4589        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
4590
4591        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4592                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
4593                        + widthUsed, lp.width);
4594        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4595                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
4596                        + heightUsed, lp.height);
4597
4598        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4599    }
4600
4601    /**
4602     * Does the hard part of measureChildren: figuring out the MeasureSpec to
4603     * pass to a particular child. This method figures out the right MeasureSpec
4604     * for one dimension (height or width) of one child view.
4605     *
4606     * The goal is to combine information from our MeasureSpec with the
4607     * LayoutParams of the child to get the best possible results. For example,
4608     * if the this view knows its size (because its MeasureSpec has a mode of
4609     * EXACTLY), and the child has indicated in its LayoutParams that it wants
4610     * to be the same size as the parent, the parent should ask the child to
4611     * layout given an exact size.
4612     *
4613     * @param spec The requirements for this view
4614     * @param padding The padding of this view for the current dimension and
4615     *        margins, if applicable
4616     * @param childDimension How big the child wants to be in the current
4617     *        dimension
4618     * @return a MeasureSpec integer for the child
4619     */
4620    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
4621        int specMode = MeasureSpec.getMode(spec);
4622        int specSize = MeasureSpec.getSize(spec);
4623
4624        int size = Math.max(0, specSize - padding);
4625
4626        int resultSize = 0;
4627        int resultMode = 0;
4628
4629        switch (specMode) {
4630        // Parent has imposed an exact size on us
4631        case MeasureSpec.EXACTLY:
4632            if (childDimension >= 0) {
4633                resultSize = childDimension;
4634                resultMode = MeasureSpec.EXACTLY;
4635            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4636                // Child wants to be our size. So be it.
4637                resultSize = size;
4638                resultMode = MeasureSpec.EXACTLY;
4639            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4640                // Child wants to determine its own size. It can't be
4641                // bigger than us.
4642                resultSize = size;
4643                resultMode = MeasureSpec.AT_MOST;
4644            }
4645            break;
4646
4647        // Parent has imposed a maximum size on us
4648        case MeasureSpec.AT_MOST:
4649            if (childDimension >= 0) {
4650                // Child wants a specific size... so be it
4651                resultSize = childDimension;
4652                resultMode = MeasureSpec.EXACTLY;
4653            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4654                // Child wants to be our size, but our size is not fixed.
4655                // Constrain child to not be bigger than us.
4656                resultSize = size;
4657                resultMode = MeasureSpec.AT_MOST;
4658            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4659                // Child wants to determine its own size. It can't be
4660                // bigger than us.
4661                resultSize = size;
4662                resultMode = MeasureSpec.AT_MOST;
4663            }
4664            break;
4665
4666        // Parent asked to see how big we want to be
4667        case MeasureSpec.UNSPECIFIED:
4668            if (childDimension >= 0) {
4669                // Child wants a specific size... let him have it
4670                resultSize = childDimension;
4671                resultMode = MeasureSpec.EXACTLY;
4672            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4673                // Child wants to be our size... find out how big it should
4674                // be
4675                resultSize = 0;
4676                resultMode = MeasureSpec.UNSPECIFIED;
4677            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4678                // Child wants to determine its own size.... find out how
4679                // big it should be
4680                resultSize = 0;
4681                resultMode = MeasureSpec.UNSPECIFIED;
4682            }
4683            break;
4684        }
4685        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
4686    }
4687
4688
4689    /**
4690     * Removes any pending animations for views that have been removed. Call
4691     * this if you don't want animations for exiting views to stack up.
4692     */
4693    public void clearDisappearingChildren() {
4694        if (mDisappearingChildren != null) {
4695            mDisappearingChildren.clear();
4696        }
4697    }
4698
4699    /**
4700     * Add a view which is removed from mChildren but still needs animation
4701     *
4702     * @param v View to add
4703     */
4704    private void addDisappearingView(View v) {
4705        ArrayList<View> disappearingChildren = mDisappearingChildren;
4706
4707        if (disappearingChildren == null) {
4708            disappearingChildren = mDisappearingChildren = new ArrayList<View>();
4709        }
4710
4711        disappearingChildren.add(v);
4712    }
4713
4714    /**
4715     * Cleanup a view when its animation is done. This may mean removing it from
4716     * the list of disappearing views.
4717     *
4718     * @param view The view whose animation has finished
4719     * @param animation The animation, cannot be null
4720     */
4721    private void finishAnimatingView(final View view, Animation animation) {
4722        final ArrayList<View> disappearingChildren = mDisappearingChildren;
4723        if (disappearingChildren != null) {
4724            if (disappearingChildren.contains(view)) {
4725                disappearingChildren.remove(view);
4726
4727                if (view.mAttachInfo != null) {
4728                    view.dispatchDetachedFromWindow();
4729                }
4730
4731                view.clearAnimation();
4732                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
4733            }
4734        }
4735
4736        if (animation != null && !animation.getFillAfter()) {
4737            view.clearAnimation();
4738        }
4739
4740        if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) {
4741            view.onAnimationEnd();
4742            // Should be performed by onAnimationEnd() but this avoid an infinite loop,
4743            // so we'd rather be safe than sorry
4744            view.mPrivateFlags &= ~ANIMATION_STARTED;
4745            // Draw one more frame after the animation is done
4746            mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
4747        }
4748    }
4749
4750    /**
4751     * This method tells the ViewGroup that the given View object, which should have this
4752     * ViewGroup as its parent,
4753     * should be kept around  (re-displayed when the ViewGroup draws its children) even if it
4754     * is removed from its parent. This allows animations, such as those used by
4755     * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate
4756     * the removal of views. A call to this method should always be accompanied by a later call
4757     * to {@link #endViewTransition(View)}, such as after an animation on the View has finished,
4758     * so that the View finally gets removed.
4759     *
4760     * @param view The View object to be kept visible even if it gets removed from its parent.
4761     */
4762    public void startViewTransition(View view) {
4763        if (view.mParent == this) {
4764            if (mTransitioningViews == null) {
4765                mTransitioningViews = new ArrayList<View>();
4766            }
4767            mTransitioningViews.add(view);
4768        }
4769    }
4770
4771    /**
4772     * This method should always be called following an earlier call to
4773     * {@link #startViewTransition(View)}. The given View is finally removed from its parent
4774     * and will no longer be displayed. Note that this method does not perform the functionality
4775     * of removing a view from its parent; it just discontinues the display of a View that
4776     * has previously been removed.
4777     *
4778     * @return view The View object that has been removed but is being kept around in the visible
4779     * hierarchy by an earlier call to {@link #startViewTransition(View)}.
4780     */
4781    public void endViewTransition(View view) {
4782        if (mTransitioningViews != null) {
4783            mTransitioningViews.remove(view);
4784            final ArrayList<View> disappearingChildren = mDisappearingChildren;
4785            if (disappearingChildren != null && disappearingChildren.contains(view)) {
4786                disappearingChildren.remove(view);
4787                if (mVisibilityChangingChildren != null &&
4788                        mVisibilityChangingChildren.contains(view)) {
4789                    mVisibilityChangingChildren.remove(view);
4790                } else {
4791                    if (view.mAttachInfo != null) {
4792                        view.dispatchDetachedFromWindow();
4793                    }
4794                    if (view.mParent != null) {
4795                        view.mParent = null;
4796                    }
4797                }
4798                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
4799            }
4800        }
4801    }
4802
4803    private LayoutTransition.TransitionListener mLayoutTransitionListener =
4804            new LayoutTransition.TransitionListener() {
4805        @Override
4806        public void startTransition(LayoutTransition transition, ViewGroup container,
4807                View view, int transitionType) {
4808            // We only care about disappearing items, since we need special logic to keep
4809            // those items visible after they've been 'removed'
4810            if (transitionType == LayoutTransition.DISAPPEARING) {
4811                startViewTransition(view);
4812            }
4813        }
4814
4815        @Override
4816        public void endTransition(LayoutTransition transition, ViewGroup container,
4817                View view, int transitionType) {
4818            if (mLayoutSuppressed && !transition.isChangingLayout()) {
4819                requestLayout();
4820                mLayoutSuppressed = false;
4821            }
4822            if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
4823                endViewTransition(view);
4824            }
4825        }
4826    };
4827
4828    /**
4829     * {@inheritDoc}
4830     */
4831    @Override
4832    public boolean gatherTransparentRegion(Region region) {
4833        // If no transparent regions requested, we are always opaque.
4834        final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0;
4835        if (meOpaque && region == null) {
4836            // The caller doesn't care about the region, so stop now.
4837            return true;
4838        }
4839        super.gatherTransparentRegion(region);
4840        final View[] children = mChildren;
4841        final int count = mChildrenCount;
4842        boolean noneOfTheChildrenAreTransparent = true;
4843        for (int i = 0; i < count; i++) {
4844            final View child = children[i];
4845            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
4846                if (!child.gatherTransparentRegion(region)) {
4847                    noneOfTheChildrenAreTransparent = false;
4848                }
4849            }
4850        }
4851        return meOpaque || noneOfTheChildrenAreTransparent;
4852    }
4853
4854    /**
4855     * {@inheritDoc}
4856     */
4857    public void requestTransparentRegion(View child) {
4858        if (child != null) {
4859            child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
4860            if (mParent != null) {
4861                mParent.requestTransparentRegion(this);
4862            }
4863        }
4864    }
4865
4866
4867    @Override
4868    protected boolean fitSystemWindows(Rect insets) {
4869        boolean done = super.fitSystemWindows(insets);
4870        if (!done) {
4871            final int count = mChildrenCount;
4872            final View[] children = mChildren;
4873            for (int i = 0; i < count; i++) {
4874                done = children[i].fitSystemWindows(insets);
4875                if (done) {
4876                    break;
4877                }
4878            }
4879        }
4880        return done;
4881    }
4882
4883    /**
4884     * Returns the animation listener to which layout animation events are
4885     * sent.
4886     *
4887     * @return an {@link android.view.animation.Animation.AnimationListener}
4888     */
4889    public Animation.AnimationListener getLayoutAnimationListener() {
4890        return mAnimationListener;
4891    }
4892
4893    @Override
4894    protected void drawableStateChanged() {
4895        super.drawableStateChanged();
4896
4897        if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
4898            if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
4899                throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
4900                        + " child has duplicateParentState set to true");
4901            }
4902
4903            final View[] children = mChildren;
4904            final int count = mChildrenCount;
4905
4906            for (int i = 0; i < count; i++) {
4907                final View child = children[i];
4908                if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
4909                    child.refreshDrawableState();
4910                }
4911            }
4912        }
4913    }
4914
4915    @Override
4916    public void jumpDrawablesToCurrentState() {
4917        super.jumpDrawablesToCurrentState();
4918        final View[] children = mChildren;
4919        final int count = mChildrenCount;
4920        for (int i = 0; i < count; i++) {
4921            children[i].jumpDrawablesToCurrentState();
4922        }
4923    }
4924
4925    @Override
4926    protected int[] onCreateDrawableState(int extraSpace) {
4927        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) {
4928            return super.onCreateDrawableState(extraSpace);
4929        }
4930
4931        int need = 0;
4932        int n = getChildCount();
4933        for (int i = 0; i < n; i++) {
4934            int[] childState = getChildAt(i).getDrawableState();
4935
4936            if (childState != null) {
4937                need += childState.length;
4938            }
4939        }
4940
4941        int[] state = super.onCreateDrawableState(extraSpace + need);
4942
4943        for (int i = 0; i < n; i++) {
4944            int[] childState = getChildAt(i).getDrawableState();
4945
4946            if (childState != null) {
4947                state = mergeDrawableStates(state, childState);
4948            }
4949        }
4950
4951        return state;
4952    }
4953
4954    /**
4955     * Sets whether this ViewGroup's drawable states also include
4956     * its children's drawable states.  This is used, for example, to
4957     * make a group appear to be focused when its child EditText or button
4958     * is focused.
4959     */
4960    public void setAddStatesFromChildren(boolean addsStates) {
4961        if (addsStates) {
4962            mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN;
4963        } else {
4964            mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN;
4965        }
4966
4967        refreshDrawableState();
4968    }
4969
4970    /**
4971     * Returns whether this ViewGroup's drawable states also include
4972     * its children's drawable states.  This is used, for example, to
4973     * make a group appear to be focused when its child EditText or button
4974     * is focused.
4975     */
4976    public boolean addStatesFromChildren() {
4977        return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0;
4978    }
4979
4980    /**
4981     * If {link #addStatesFromChildren} is true, refreshes this group's
4982     * drawable state (to include the states from its children).
4983     */
4984    public void childDrawableStateChanged(View child) {
4985        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
4986            refreshDrawableState();
4987        }
4988    }
4989
4990    /**
4991     * Specifies the animation listener to which layout animation events must
4992     * be sent. Only
4993     * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)}
4994     * and
4995     * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)}
4996     * are invoked.
4997     *
4998     * @param animationListener the layout animation listener
4999     */
5000    public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
5001        mAnimationListener = animationListener;
5002    }
5003
5004    /**
5005     * This method is called by LayoutTransition when there are 'changing' animations that need
5006     * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who
5007     * starts all pending transitions prior to the drawing phase in the current traversal.
5008     *
5009     * @param transition The LayoutTransition to be started on the next traversal.
5010     *
5011     * @hide
5012     */
5013    public void requestTransitionStart(LayoutTransition transition) {
5014        ViewRootImpl viewAncestor = getViewRootImpl();
5015        viewAncestor.requestTransitionStart(transition);
5016    }
5017
5018    @Override
5019    protected void resetResolvedLayoutDirection() {
5020        super.resetResolvedLayoutDirection();
5021
5022        // Take care of resetting the children resolution too
5023        final int count = getChildCount();
5024        for (int i = 0; i < count; i++) {
5025            final View child = getChildAt(i);
5026            if (child.getLayoutDirection() == LAYOUT_DIRECTION_INHERIT) {
5027                child.resetResolvedLayoutDirection();
5028            }
5029        }
5030    }
5031
5032    @Override
5033    protected void resetResolvedTextDirection() {
5034        super.resetResolvedTextDirection();
5035
5036        // Take care of resetting the children resolution too
5037        final int count = getChildCount();
5038        for (int i = 0; i < count; i++) {
5039            final View child = getChildAt(i);
5040            if (child.getTextDirection() == TEXT_DIRECTION_INHERIT) {
5041                child.resetResolvedTextDirection();
5042            }
5043        }
5044    }
5045
5046    /**
5047     * Return true if the pressed state should be delayed for children or descendants of this
5048     * ViewGroup. Generally, this should be done for containers that can scroll, such as a List.
5049     * This prevents the pressed state from appearing when the user is actually trying to scroll
5050     * the content.
5051     *
5052     * The default implementation returns true for compatibility reasons. Subclasses that do
5053     * not scroll should generally override this method and return false.
5054     */
5055    public boolean shouldDelayChildPressedState() {
5056        return true;
5057    }
5058
5059    /**
5060     * LayoutParams are used by views to tell their parents how they want to be
5061     * laid out. See
5062     * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes}
5063     * for a list of all child view attributes that this class supports.
5064     *
5065     * <p>
5066     * The base LayoutParams class just describes how big the view wants to be
5067     * for both width and height. For each dimension, it can specify one of:
5068     * <ul>
5069     * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
5070     * means that the view wants to be as big as its parent (minus padding)
5071     * <li> WRAP_CONTENT, which means that the view wants to be just big enough
5072     * to enclose its content (plus padding)
5073     * <li> an exact number
5074     * </ul>
5075     * There are subclasses of LayoutParams for different subclasses of
5076     * ViewGroup. For example, AbsoluteLayout has its own subclass of
5077     * LayoutParams which adds an X and Y value.
5078     *
5079     * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
5080     * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
5081     */
5082    public static class LayoutParams {
5083        /**
5084         * Special value for the height or width requested by a View.
5085         * FILL_PARENT means that the view wants to be as big as its parent,
5086         * minus the parent's padding, if any. This value is deprecated
5087         * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
5088         */
5089        @SuppressWarnings({"UnusedDeclaration"})
5090        @Deprecated
5091        public static final int FILL_PARENT = -1;
5092
5093        /**
5094         * Special value for the height or width requested by a View.
5095         * MATCH_PARENT means that the view wants to be as big as its parent,
5096         * minus the parent's padding, if any. Introduced in API Level 8.
5097         */
5098        public static final int MATCH_PARENT = -1;
5099
5100        /**
5101         * Special value for the height or width requested by a View.
5102         * WRAP_CONTENT means that the view wants to be just large enough to fit
5103         * its own internal content, taking its own padding into account.
5104         */
5105        public static final int WRAP_CONTENT = -2;
5106
5107        /**
5108         * Information about how wide the view wants to be. Can be one of the
5109         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5110         * in API Level 8) or WRAP_CONTENT. or an exact size.
5111         */
5112        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5113            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5114            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5115        })
5116        public int width;
5117
5118        /**
5119         * Information about how tall the view wants to be. Can be one of the
5120         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5121         * in API Level 8) or WRAP_CONTENT. or an exact size.
5122         */
5123        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5124            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5125            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5126        })
5127        public int height;
5128
5129        /**
5130         * Used to animate layouts.
5131         */
5132        public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
5133
5134        /**
5135         * Creates a new set of layout parameters. The values are extracted from
5136         * the supplied attributes set and context. The XML attributes mapped
5137         * to this set of layout parameters are:
5138         *
5139         * <ul>
5140         *   <li><code>layout_width</code>: the width, either an exact value,
5141         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5142         *   {@link #MATCH_PARENT} in API Level 8)</li>
5143         *   <li><code>layout_height</code>: the height, either an exact value,
5144         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5145         *   {@link #MATCH_PARENT} in API Level 8)</li>
5146         * </ul>
5147         *
5148         * @param c the application environment
5149         * @param attrs the set of attributes from which to extract the layout
5150         *              parameters' values
5151         */
5152        public LayoutParams(Context c, AttributeSet attrs) {
5153            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
5154            setBaseAttributes(a,
5155                    R.styleable.ViewGroup_Layout_layout_width,
5156                    R.styleable.ViewGroup_Layout_layout_height);
5157            a.recycle();
5158        }
5159
5160        /**
5161         * Creates a new set of layout parameters with the specified width
5162         * and height.
5163         *
5164         * @param width the width, either {@link #WRAP_CONTENT},
5165         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5166         *        API Level 8), or a fixed size in pixels
5167         * @param height the height, either {@link #WRAP_CONTENT},
5168         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5169         *        API Level 8), or a fixed size in pixels
5170         */
5171        public LayoutParams(int width, int height) {
5172            this.width = width;
5173            this.height = height;
5174        }
5175
5176        /**
5177         * Copy constructor. Clones the width and height values of the source.
5178         *
5179         * @param source The layout params to copy from.
5180         */
5181        public LayoutParams(LayoutParams source) {
5182            this.width = source.width;
5183            this.height = source.height;
5184        }
5185
5186        /**
5187         * Used internally by MarginLayoutParams.
5188         * @hide
5189         */
5190        LayoutParams() {
5191        }
5192
5193        /**
5194         * Extracts the layout parameters from the supplied attributes.
5195         *
5196         * @param a the style attributes to extract the parameters from
5197         * @param widthAttr the identifier of the width attribute
5198         * @param heightAttr the identifier of the height attribute
5199         */
5200        protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
5201            width = a.getLayoutDimension(widthAttr, "layout_width");
5202            height = a.getLayoutDimension(heightAttr, "layout_height");
5203        }
5204
5205        /**
5206         * Resolve layout parameters depending on the layout direction. Subclasses that care about
5207         * layoutDirection changes should override this method. The default implementation does
5208         * nothing.
5209         *
5210         * @param layoutDirection the direction of the layout
5211         *
5212         * {@link View#LAYOUT_DIRECTION_LTR}
5213         * {@link View#LAYOUT_DIRECTION_RTL}
5214         *
5215         * @hide
5216         */
5217        protected void resolveWithDirection(int layoutDirection) {
5218        }
5219
5220        /**
5221         * Returns a String representation of this set of layout parameters.
5222         *
5223         * @param output the String to prepend to the internal representation
5224         * @return a String with the following format: output +
5225         *         "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }"
5226         *
5227         * @hide
5228         */
5229        public String debug(String output) {
5230            return output + "ViewGroup.LayoutParams={ width="
5231                    + sizeToString(width) + ", height=" + sizeToString(height) + " }";
5232        }
5233
5234        /**
5235         * Converts the specified size to a readable String.
5236         *
5237         * @param size the size to convert
5238         * @return a String instance representing the supplied size
5239         *
5240         * @hide
5241         */
5242        protected static String sizeToString(int size) {
5243            if (size == WRAP_CONTENT) {
5244                return "wrap-content";
5245            }
5246            if (size == MATCH_PARENT) {
5247                return "match-parent";
5248            }
5249            return String.valueOf(size);
5250        }
5251    }
5252
5253    /**
5254     * Per-child layout information for layouts that support margins.
5255     * See
5256     * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes}
5257     * for a list of all child view attributes that this class supports.
5258     */
5259    public static class MarginLayoutParams extends ViewGroup.LayoutParams {
5260        /**
5261         * The left margin in pixels of the child. Whenever this value is changed, a call to
5262         * {@link android.view.View#requestLayout()} needs to be done.
5263         */
5264        @ViewDebug.ExportedProperty(category = "layout")
5265        public int leftMargin;
5266
5267        /**
5268         * The top margin in pixels of the child. Whenever this value is changed, a call to
5269         * {@link android.view.View#requestLayout()} needs to be done.
5270         */
5271        @ViewDebug.ExportedProperty(category = "layout")
5272        public int topMargin;
5273
5274        /**
5275         * The right margin in pixels of the child. Whenever this value is changed, a call to
5276         * {@link android.view.View#requestLayout()} needs to be done.
5277         */
5278        @ViewDebug.ExportedProperty(category = "layout")
5279        public int rightMargin;
5280
5281        /**
5282         * The bottom margin in pixels of the child. Whenever this value is changed, a call to
5283         * {@link android.view.View#requestLayout()} needs to be done.
5284         */
5285        @ViewDebug.ExportedProperty(category = "layout")
5286        public int bottomMargin;
5287
5288        /**
5289         * The start margin in pixels of the child.
5290         *
5291         * @hide
5292         *
5293         */
5294        @ViewDebug.ExportedProperty(category = "layout")
5295        protected int startMargin = DEFAULT_RELATIVE;
5296
5297        /**
5298         * The end margin in pixels of the child.
5299         *
5300         * @hide
5301         */
5302        @ViewDebug.ExportedProperty(category = "layout")
5303        protected int endMargin = DEFAULT_RELATIVE;
5304
5305        /**
5306         * The default start and end margin.
5307         */
5308        static private final int DEFAULT_RELATIVE = Integer.MIN_VALUE;
5309
5310        /**
5311         * Creates a new set of layout parameters. The values are extracted from
5312         * the supplied attributes set and context.
5313         *
5314         * @param c the application environment
5315         * @param attrs the set of attributes from which to extract the layout
5316         *              parameters' values
5317         */
5318        public MarginLayoutParams(Context c, AttributeSet attrs) {
5319            super();
5320
5321            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
5322            setBaseAttributes(a,
5323                    R.styleable.ViewGroup_MarginLayout_layout_width,
5324                    R.styleable.ViewGroup_MarginLayout_layout_height);
5325
5326            int margin = a.getDimensionPixelSize(
5327                    com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
5328            if (margin >= 0) {
5329                leftMargin = margin;
5330                topMargin = margin;
5331                rightMargin= margin;
5332                bottomMargin = margin;
5333            } else {
5334                leftMargin = a.getDimensionPixelSize(
5335                        R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0);
5336                topMargin = a.getDimensionPixelSize(
5337                        R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0);
5338                rightMargin = a.getDimensionPixelSize(
5339                        R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0);
5340                bottomMargin = a.getDimensionPixelSize(
5341                        R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0);
5342                startMargin = a.getDimensionPixelSize(
5343                        R.styleable.ViewGroup_MarginLayout_layout_marginStart, DEFAULT_RELATIVE);
5344                endMargin = a.getDimensionPixelSize(
5345                        R.styleable.ViewGroup_MarginLayout_layout_marginEnd, DEFAULT_RELATIVE);
5346            }
5347
5348            a.recycle();
5349        }
5350
5351        /**
5352         * {@inheritDoc}
5353         */
5354        public MarginLayoutParams(int width, int height) {
5355            super(width, height);
5356        }
5357
5358        /**
5359         * Copy constructor. Clones the width, height and margin values of the source.
5360         *
5361         * @param source The layout params to copy from.
5362         */
5363        public MarginLayoutParams(MarginLayoutParams source) {
5364            this.width = source.width;
5365            this.height = source.height;
5366
5367            this.leftMargin = source.leftMargin;
5368            this.topMargin = source.topMargin;
5369            this.rightMargin = source.rightMargin;
5370            this.bottomMargin = source.bottomMargin;
5371            this.startMargin = source.startMargin;
5372            this.endMargin = source.endMargin;
5373        }
5374
5375        /**
5376         * {@inheritDoc}
5377         */
5378        public MarginLayoutParams(LayoutParams source) {
5379            super(source);
5380        }
5381
5382        /**
5383         * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs
5384         * to be done so that the new margins are taken into account. Left and right margins may be
5385         * overriden by {@link android.view.View#requestLayout()} depending on layout direction.
5386         *
5387         * @param left the left margin size
5388         * @param top the top margin size
5389         * @param right the right margin size
5390         * @param bottom the bottom margin size
5391         *
5392         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
5393         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5394         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
5395         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5396         */
5397        public void setMargins(int left, int top, int right, int bottom) {
5398            leftMargin = left;
5399            topMargin = top;
5400            rightMargin = right;
5401            bottomMargin = bottom;
5402        }
5403
5404        /**
5405         * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()}
5406         * needs to be done so that the new relative margins are taken into account. Left and right
5407         * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout
5408         * direction.
5409         *
5410         * @param start the start margin size
5411         * @param top the top margin size
5412         * @param end the right margin size
5413         * @param bottom the bottom margin size
5414         *
5415         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5416         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5417         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5418         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5419         *
5420         * @hide
5421         */
5422        public void setMarginsRelative(int start, int top, int end, int bottom) {
5423            startMargin = start;
5424            topMargin = top;
5425            endMargin = end;
5426            bottomMargin = bottom;
5427        }
5428
5429        /**
5430         * Returns the start margin in pixels.
5431         *
5432         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5433         *
5434         * @return the start margin in pixels.
5435         *
5436         * @hide
5437         */
5438        public int getMarginStart() {
5439            return startMargin;
5440        }
5441
5442        /**
5443         * Returns the end margin in pixels.
5444         *
5445         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5446         *
5447         * @return the end margin in pixels.
5448         *
5449         * @hide
5450         */
5451        public int getMarginEnd() {
5452            return endMargin;
5453        }
5454
5455        /**
5456         * Check if margins are relative.
5457         *
5458         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5459         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5460         *
5461         * @return true if either marginStart or marginEnd has been set
5462         *
5463         * @hide
5464         */
5465        public boolean isMarginRelative() {
5466            return (startMargin != DEFAULT_RELATIVE) || (endMargin != DEFAULT_RELATIVE);
5467        }
5468
5469        /**
5470         * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins
5471         * maybe overriden depending on layout direction.
5472         *
5473         * @hide
5474         */
5475        @Override
5476        protected void resolveWithDirection(int layoutDirection) {
5477            switch(layoutDirection) {
5478                case View.LAYOUT_DIRECTION_RTL:
5479                    leftMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : leftMargin;
5480                    rightMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : rightMargin;
5481                    break;
5482                case View.LAYOUT_DIRECTION_LTR:
5483                default:
5484                    leftMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : leftMargin;
5485                    rightMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : rightMargin;
5486                    break;
5487            }
5488        }
5489    }
5490
5491    /* Describes a touched view and the ids of the pointers that it has captured.
5492     *
5493     * This code assumes that pointer ids are always in the range 0..31 such that
5494     * it can use a bitfield to track which pointer ids are present.
5495     * As it happens, the lower layers of the input dispatch pipeline also use the
5496     * same trick so the assumption should be safe here...
5497     */
5498    private static final class TouchTarget {
5499        private static final int MAX_RECYCLED = 32;
5500        private static final Object sRecycleLock = new Object();
5501        private static TouchTarget sRecycleBin;
5502        private static int sRecycledCount;
5503
5504        public static final int ALL_POINTER_IDS = -1; // all ones
5505
5506        // The touched child view.
5507        public View child;
5508
5509        // The combined bit mask of pointer ids for all pointers captured by the target.
5510        public int pointerIdBits;
5511
5512        // The next target in the target list.
5513        public TouchTarget next;
5514
5515        private TouchTarget() {
5516        }
5517
5518        public static TouchTarget obtain(View child, int pointerIdBits) {
5519            final TouchTarget target;
5520            synchronized (sRecycleLock) {
5521                if (sRecycleBin == null) {
5522                    target = new TouchTarget();
5523                } else {
5524                    target = sRecycleBin;
5525                    sRecycleBin = target.next;
5526                     sRecycledCount--;
5527                    target.next = null;
5528                }
5529            }
5530            target.child = child;
5531            target.pointerIdBits = pointerIdBits;
5532            return target;
5533        }
5534
5535        public void recycle() {
5536            synchronized (sRecycleLock) {
5537                if (sRecycledCount < MAX_RECYCLED) {
5538                    next = sRecycleBin;
5539                    sRecycleBin = this;
5540                    sRecycledCount += 1;
5541                } else {
5542                    next = null;
5543                }
5544                child = null;
5545            }
5546        }
5547    }
5548
5549    /* Describes a hovered view. */
5550    private static final class HoverTarget {
5551        private static final int MAX_RECYCLED = 32;
5552        private static final Object sRecycleLock = new Object();
5553        private static HoverTarget sRecycleBin;
5554        private static int sRecycledCount;
5555
5556        // The hovered child view.
5557        public View child;
5558
5559        // The next target in the target list.
5560        public HoverTarget next;
5561
5562        private HoverTarget() {
5563        }
5564
5565        public static HoverTarget obtain(View child) {
5566            final HoverTarget target;
5567            synchronized (sRecycleLock) {
5568                if (sRecycleBin == null) {
5569                    target = new HoverTarget();
5570                } else {
5571                    target = sRecycleBin;
5572                    sRecycleBin = target.next;
5573                     sRecycledCount--;
5574                    target.next = null;
5575                }
5576            }
5577            target.child = child;
5578            return target;
5579        }
5580
5581        public void recycle() {
5582            synchronized (sRecycleLock) {
5583                if (sRecycledCount < MAX_RECYCLED) {
5584                    next = sRecycleBin;
5585                    sRecycleBin = this;
5586                    sRecycledCount += 1;
5587                } else {
5588                    next = null;
5589                }
5590                child = null;
5591            }
5592        }
5593    }
5594}
5595