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