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