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