ViewGroup.java revision 5c555f39fb9bb1a47c081ae62658454e92792f44
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            child.resolveRtlPropertiesIfNeeded();
3482        }
3483
3484        onViewAdded(child);
3485
3486        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
3487            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
3488        }
3489
3490        if (child.hasTransientState()) {
3491            childHasTransientStateChanged(child, true);
3492        }
3493    }
3494
3495    private void addInArray(View child, int index) {
3496        View[] children = mChildren;
3497        final int count = mChildrenCount;
3498        final int size = children.length;
3499        if (index == count) {
3500            if (size == count) {
3501                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3502                System.arraycopy(children, 0, mChildren, 0, size);
3503                children = mChildren;
3504            }
3505            children[mChildrenCount++] = child;
3506        } else if (index < count) {
3507            if (size == count) {
3508                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3509                System.arraycopy(children, 0, mChildren, 0, index);
3510                System.arraycopy(children, index, mChildren, index + 1, count - index);
3511                children = mChildren;
3512            } else {
3513                System.arraycopy(children, index, children, index + 1, count - index);
3514            }
3515            children[index] = child;
3516            mChildrenCount++;
3517            if (mLastTouchDownIndex >= index) {
3518                mLastTouchDownIndex++;
3519            }
3520        } else {
3521            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
3522        }
3523    }
3524
3525    // This method also sets the child's mParent to null
3526    private void removeFromArray(int index) {
3527        final View[] children = mChildren;
3528        if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
3529            children[index].mParent = null;
3530        }
3531        final int count = mChildrenCount;
3532        if (index == count - 1) {
3533            children[--mChildrenCount] = null;
3534        } else if (index >= 0 && index < count) {
3535            System.arraycopy(children, index + 1, children, index, count - index - 1);
3536            children[--mChildrenCount] = null;
3537        } else {
3538            throw new IndexOutOfBoundsException();
3539        }
3540        if (mLastTouchDownIndex == index) {
3541            mLastTouchDownTime = 0;
3542            mLastTouchDownIndex = -1;
3543        } else if (mLastTouchDownIndex > index) {
3544            mLastTouchDownIndex--;
3545        }
3546    }
3547
3548    // This method also sets the children's mParent to null
3549    private void removeFromArray(int start, int count) {
3550        final View[] children = mChildren;
3551        final int childrenCount = mChildrenCount;
3552
3553        start = Math.max(0, start);
3554        final int end = Math.min(childrenCount, start + count);
3555
3556        if (start == end) {
3557            return;
3558        }
3559
3560        if (end == childrenCount) {
3561            for (int i = start; i < end; i++) {
3562                children[i].mParent = null;
3563                children[i] = null;
3564            }
3565        } else {
3566            for (int i = start; i < end; i++) {
3567                children[i].mParent = null;
3568            }
3569
3570            // Since we're looping above, we might as well do the copy, but is arraycopy()
3571            // faster than the extra 2 bounds checks we would do in the loop?
3572            System.arraycopy(children, end, children, start, childrenCount - end);
3573
3574            for (int i = childrenCount - (end - start); i < childrenCount; i++) {
3575                children[i] = null;
3576            }
3577        }
3578
3579        mChildrenCount -= (end - start);
3580    }
3581
3582    private void bindLayoutAnimation(View child) {
3583        Animation a = mLayoutAnimationController.getAnimationForView(child);
3584        child.setAnimation(a);
3585    }
3586
3587    /**
3588     * Subclasses should override this method to set layout animation
3589     * parameters on the supplied child.
3590     *
3591     * @param child the child to associate with animation parameters
3592     * @param params the child's layout parameters which hold the animation
3593     *        parameters
3594     * @param index the index of the child in the view group
3595     * @param count the number of children in the view group
3596     */
3597    protected void attachLayoutAnimationParameters(View child,
3598            LayoutParams params, int index, int count) {
3599        LayoutAnimationController.AnimationParameters animationParams =
3600                    params.layoutAnimationParameters;
3601        if (animationParams == null) {
3602            animationParams = new LayoutAnimationController.AnimationParameters();
3603            params.layoutAnimationParameters = animationParams;
3604        }
3605
3606        animationParams.count = count;
3607        animationParams.index = index;
3608    }
3609
3610    /**
3611     * {@inheritDoc}
3612     *
3613     * <p><strong>Note:</strong> do not invoke this method from
3614     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3615     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3616     */
3617    public void removeView(View view) {
3618        removeViewInternal(view);
3619        requestLayout();
3620        invalidate(true);
3621    }
3622
3623    /**
3624     * Removes a view during layout. This is useful if in your onLayout() method,
3625     * you need to remove more views.
3626     *
3627     * <p><strong>Note:</strong> do not invoke this method from
3628     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3629     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3630     *
3631     * @param view the view to remove from the group
3632     */
3633    public void removeViewInLayout(View view) {
3634        removeViewInternal(view);
3635    }
3636
3637    /**
3638     * Removes a range of views during layout. This is useful if in your onLayout() method,
3639     * you need to remove more views.
3640     *
3641     * <p><strong>Note:</strong> do not invoke this method from
3642     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3643     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3644     *
3645     * @param start the index of the first view to remove from the group
3646     * @param count the number of views to remove from the group
3647     */
3648    public void removeViewsInLayout(int start, int count) {
3649        removeViewsInternal(start, count);
3650    }
3651
3652    /**
3653     * Removes the view at the specified position in the group.
3654     *
3655     * <p><strong>Note:</strong> do not invoke this method from
3656     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3657     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3658     *
3659     * @param index the position in the group of the view to remove
3660     */
3661    public void removeViewAt(int index) {
3662        removeViewInternal(index, getChildAt(index));
3663        requestLayout();
3664        invalidate(true);
3665    }
3666
3667    /**
3668     * Removes the specified range of views from the group.
3669     *
3670     * <p><strong>Note:</strong> do not invoke this method from
3671     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3672     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3673     *
3674     * @param start the first position in the group of the range of views to remove
3675     * @param count the number of views to remove
3676     */
3677    public void removeViews(int start, int count) {
3678        removeViewsInternal(start, count);
3679        requestLayout();
3680        invalidate(true);
3681    }
3682
3683    private void removeViewInternal(View view) {
3684        final int index = indexOfChild(view);
3685        if (index >= 0) {
3686            removeViewInternal(index, view);
3687        }
3688    }
3689
3690    private void removeViewInternal(int index, View view) {
3691
3692        if (mTransition != null) {
3693            mTransition.removeChild(this, view);
3694        }
3695
3696        boolean clearChildFocus = false;
3697        if (view == mFocused) {
3698            view.unFocus();
3699            clearChildFocus = true;
3700        }
3701
3702        view.clearAccessibilityFocus();
3703
3704        cancelTouchTarget(view);
3705        cancelHoverTarget(view);
3706
3707        if (view.getAnimation() != null ||
3708                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3709            addDisappearingView(view);
3710        } else if (view.mAttachInfo != null) {
3711           view.dispatchDetachedFromWindow();
3712        }
3713
3714        if (view.hasTransientState()) {
3715            childHasTransientStateChanged(view, false);
3716        }
3717
3718        view.resetRtlProperties();
3719
3720        onViewRemoved(view);
3721
3722        needGlobalAttributesUpdate(false);
3723
3724        removeFromArray(index);
3725
3726        if (clearChildFocus) {
3727            clearChildFocus(view);
3728            ensureInputFocusOnFirstFocusable();
3729        }
3730
3731        if (view.isAccessibilityFocused()) {
3732            view.clearAccessibilityFocus();
3733        }
3734    }
3735
3736    /**
3737     * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3738     * not null, changes in layout which occur because of children being added to or removed from
3739     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3740     * object. By default, the transition object is null (so layout changes are not animated).
3741     *
3742     * @param transition The LayoutTransition object that will animated changes in layout. A value
3743     * of <code>null</code> means no transition will run on layout changes.
3744     * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
3745     */
3746    public void setLayoutTransition(LayoutTransition transition) {
3747        if (mTransition != null) {
3748            mTransition.removeTransitionListener(mLayoutTransitionListener);
3749        }
3750        mTransition = transition;
3751        if (mTransition != null) {
3752            mTransition.addTransitionListener(mLayoutTransitionListener);
3753        }
3754    }
3755
3756    /**
3757     * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3758     * not null, changes in layout which occur because of children being added to or removed from
3759     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3760     * object. By default, the transition object is null (so layout changes are not animated).
3761     *
3762     * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
3763     * A value of <code>null</code> means no transition will run on layout changes.
3764     */
3765    public LayoutTransition getLayoutTransition() {
3766        return mTransition;
3767    }
3768
3769    private void removeViewsInternal(int start, int count) {
3770        final View focused = mFocused;
3771        final boolean detach = mAttachInfo != null;
3772        View clearChildFocus = null;
3773
3774        final View[] children = mChildren;
3775        final int end = start + count;
3776
3777        for (int i = start; i < end; i++) {
3778            final View view = children[i];
3779
3780            if (mTransition != null) {
3781                mTransition.removeChild(this, view);
3782            }
3783
3784            if (view == focused) {
3785                view.unFocus();
3786                clearChildFocus = view;
3787            }
3788
3789            view.clearAccessibilityFocus();
3790
3791            cancelTouchTarget(view);
3792            cancelHoverTarget(view);
3793
3794            if (view.getAnimation() != null ||
3795                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3796                addDisappearingView(view);
3797            } else if (detach) {
3798               view.dispatchDetachedFromWindow();
3799            }
3800
3801            if (view.hasTransientState()) {
3802                childHasTransientStateChanged(view, false);
3803            }
3804
3805            needGlobalAttributesUpdate(false);
3806
3807            onViewRemoved(view);
3808        }
3809
3810        removeFromArray(start, count);
3811
3812        if (clearChildFocus != null) {
3813            clearChildFocus(clearChildFocus);
3814            ensureInputFocusOnFirstFocusable();
3815        }
3816    }
3817
3818    /**
3819     * Call this method to remove all child views from the
3820     * ViewGroup.
3821     *
3822     * <p><strong>Note:</strong> do not invoke this method from
3823     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3824     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3825     */
3826    public void removeAllViews() {
3827        removeAllViewsInLayout();
3828        requestLayout();
3829        invalidate(true);
3830    }
3831
3832    /**
3833     * Called by a ViewGroup subclass to remove child views from itself,
3834     * when it must first know its size on screen before it can calculate how many
3835     * child views it will render. An example is a Gallery or a ListView, which
3836     * may "have" 50 children, but actually only render the number of children
3837     * that can currently fit inside the object on screen. Do not call
3838     * this method unless you are extending ViewGroup and understand the
3839     * view measuring and layout pipeline.
3840     *
3841     * <p><strong>Note:</strong> do not invoke this method from
3842     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3843     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3844     */
3845    public void removeAllViewsInLayout() {
3846        final int count = mChildrenCount;
3847        if (count <= 0) {
3848            return;
3849        }
3850
3851        final View[] children = mChildren;
3852        mChildrenCount = 0;
3853
3854        final View focused = mFocused;
3855        final boolean detach = mAttachInfo != null;
3856        View clearChildFocus = null;
3857
3858        needGlobalAttributesUpdate(false);
3859
3860        for (int i = count - 1; i >= 0; i--) {
3861            final View view = children[i];
3862
3863            if (mTransition != null) {
3864                mTransition.removeChild(this, view);
3865            }
3866
3867            if (view == focused) {
3868                view.unFocus();
3869                clearChildFocus = view;
3870            }
3871
3872            view.clearAccessibilityFocus();
3873
3874            cancelTouchTarget(view);
3875            cancelHoverTarget(view);
3876
3877            if (view.getAnimation() != null ||
3878                    (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3879                addDisappearingView(view);
3880            } else if (detach) {
3881               view.dispatchDetachedFromWindow();
3882            }
3883
3884            if (view.hasTransientState()) {
3885                childHasTransientStateChanged(view, false);
3886            }
3887
3888            onViewRemoved(view);
3889
3890            view.mParent = null;
3891            children[i] = null;
3892        }
3893
3894        if (clearChildFocus != null) {
3895            clearChildFocus(clearChildFocus);
3896            ensureInputFocusOnFirstFocusable();
3897        }
3898    }
3899
3900    /**
3901     * Finishes the removal of a detached view. This method will dispatch the detached from
3902     * window event and notify the hierarchy change listener.
3903     * <p>
3904     * This method is intended to be lightweight and makes no assumptions about whether the
3905     * parent or child should be redrawn. Proper use of this method will include also making
3906     * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls.
3907     * For example, callers can {@link #post(Runnable) post} a {@link Runnable}
3908     * which performs a {@link #requestLayout()} on the next frame, after all detach/remove
3909     * calls are finished, causing layout to be run prior to redrawing the view hierarchy.
3910     *
3911     * @param child the child to be definitely removed from the view hierarchy
3912     * @param animate if true and the view has an animation, the view is placed in the
3913     *                disappearing views list, otherwise, it is detached from the window
3914     *
3915     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3916     * @see #detachAllViewsFromParent()
3917     * @see #detachViewFromParent(View)
3918     * @see #detachViewFromParent(int)
3919     */
3920    protected void removeDetachedView(View child, boolean animate) {
3921        if (mTransition != null) {
3922            mTransition.removeChild(this, child);
3923        }
3924
3925        if (child == mFocused) {
3926            child.clearFocus();
3927        }
3928
3929        child.clearAccessibilityFocus();
3930
3931        cancelTouchTarget(child);
3932        cancelHoverTarget(child);
3933
3934        if ((animate && child.getAnimation() != null) ||
3935                (mTransitioningViews != null && mTransitioningViews.contains(child))) {
3936            addDisappearingView(child);
3937        } else if (child.mAttachInfo != null) {
3938            child.dispatchDetachedFromWindow();
3939        }
3940
3941        if (child.hasTransientState()) {
3942            childHasTransientStateChanged(child, false);
3943        }
3944
3945        onViewRemoved(child);
3946    }
3947
3948    /**
3949     * Attaches a view to this view group. Attaching a view assigns this group as the parent,
3950     * sets the layout parameters and puts the view in the list of children so that
3951     * it can be retrieved by calling {@link #getChildAt(int)}.
3952     * <p>
3953     * This method is intended to be lightweight and makes no assumptions about whether the
3954     * parent or child should be redrawn. Proper use of this method will include also making
3955     * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls.
3956     * For example, callers can {@link #post(Runnable) post} a {@link Runnable}
3957     * which performs a {@link #requestLayout()} on the next frame, after all detach/attach
3958     * calls are finished, causing layout to be run prior to redrawing the view hierarchy.
3959     * <p>
3960     * This method should be called only for views which were detached from their parent.
3961     *
3962     * @param child the child to attach
3963     * @param index the index at which the child should be attached
3964     * @param params the layout parameters of the child
3965     *
3966     * @see #removeDetachedView(View, boolean)
3967     * @see #detachAllViewsFromParent()
3968     * @see #detachViewFromParent(View)
3969     * @see #detachViewFromParent(int)
3970     */
3971    protected void attachViewToParent(View child, int index, LayoutParams params) {
3972        child.mLayoutParams = params;
3973
3974        if (index < 0) {
3975            index = mChildrenCount;
3976        }
3977
3978        addInArray(child, index);
3979
3980        child.mParent = this;
3981        child.mPrivateFlags = (child.mPrivateFlags & ~PFLAG_DIRTY_MASK
3982                        & ~PFLAG_DRAWING_CACHE_VALID)
3983                | PFLAG_DRAWN | PFLAG_INVALIDATED;
3984        this.mPrivateFlags |= PFLAG_INVALIDATED;
3985
3986        if (child.hasFocus()) {
3987            requestChildFocus(child, child.findFocus());
3988        }
3989    }
3990
3991    /**
3992     * Detaches a view from its parent. Detaching a view should be followed
3993     * either by a call to
3994     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3995     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
3996     * temporary; reattachment or removal should happen within the same drawing cycle as
3997     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
3998     * call to {@link #getChildAt(int)}.
3999     *
4000     * @param child the child to detach
4001     *
4002     * @see #detachViewFromParent(int)
4003     * @see #detachViewsFromParent(int, int)
4004     * @see #detachAllViewsFromParent()
4005     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4006     * @see #removeDetachedView(View, boolean)
4007     */
4008    protected void detachViewFromParent(View child) {
4009        removeFromArray(indexOfChild(child));
4010    }
4011
4012    /**
4013     * Detaches a view from its parent. Detaching a view should be followed
4014     * either by a call to
4015     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4016     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4017     * temporary; reattachment or removal should happen within the same drawing cycle as
4018     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4019     * call to {@link #getChildAt(int)}.
4020     *
4021     * @param index the index of the child to detach
4022     *
4023     * @see #detachViewFromParent(View)
4024     * @see #detachAllViewsFromParent()
4025     * @see #detachViewsFromParent(int, int)
4026     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4027     * @see #removeDetachedView(View, boolean)
4028     */
4029    protected void detachViewFromParent(int index) {
4030        removeFromArray(index);
4031    }
4032
4033    /**
4034     * Detaches a range of views from their parents. Detaching a view should be followed
4035     * either by a call to
4036     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4037     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4038     * temporary; reattachment or removal should happen within the same drawing cycle as
4039     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4040     * call to {@link #getChildAt(int)}.
4041     *
4042     * @param start the first index of the childrend range to detach
4043     * @param count the number of children to detach
4044     *
4045     * @see #detachViewFromParent(View)
4046     * @see #detachViewFromParent(int)
4047     * @see #detachAllViewsFromParent()
4048     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4049     * @see #removeDetachedView(View, boolean)
4050     */
4051    protected void detachViewsFromParent(int start, int count) {
4052        removeFromArray(start, count);
4053    }
4054
4055    /**
4056     * Detaches all views from the parent. Detaching a view should be followed
4057     * either by a call to
4058     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4059     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4060     * temporary; reattachment or removal should happen within the same drawing cycle as
4061     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4062     * call to {@link #getChildAt(int)}.
4063     *
4064     * @see #detachViewFromParent(View)
4065     * @see #detachViewFromParent(int)
4066     * @see #detachViewsFromParent(int, int)
4067     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4068     * @see #removeDetachedView(View, boolean)
4069     */
4070    protected void detachAllViewsFromParent() {
4071        final int count = mChildrenCount;
4072        if (count <= 0) {
4073            return;
4074        }
4075
4076        final View[] children = mChildren;
4077        mChildrenCount = 0;
4078
4079        for (int i = count - 1; i >= 0; i--) {
4080            children[i].mParent = null;
4081            children[i] = null;
4082        }
4083    }
4084
4085    /**
4086     * Don't call or override this method. It is used for the implementation of
4087     * the view hierarchy.
4088     */
4089    public final void invalidateChild(View child, final Rect dirty) {
4090        ViewParent parent = this;
4091
4092        final AttachInfo attachInfo = mAttachInfo;
4093        if (attachInfo != null) {
4094            // If the child is drawing an animation, we want to copy this flag onto
4095            // ourselves and the parent to make sure the invalidate request goes
4096            // through
4097            final boolean drawAnimation = (child.mPrivateFlags & PFLAG_DRAW_ANIMATION)
4098                    == PFLAG_DRAW_ANIMATION;
4099
4100            // Check whether the child that requests the invalidate is fully opaque
4101            // Views being animated or transformed are not considered opaque because we may
4102            // be invalidating their old position and need the parent to paint behind them.
4103            Matrix childMatrix = child.getMatrix();
4104            final boolean isOpaque = child.isOpaque() && !drawAnimation &&
4105                    child.getAnimation() == null && childMatrix.isIdentity();
4106            // Mark the child as dirty, using the appropriate flag
4107            // Make sure we do not set both flags at the same time
4108            int opaqueFlag = isOpaque ? PFLAG_DIRTY_OPAQUE : PFLAG_DIRTY;
4109
4110            if (child.mLayerType != LAYER_TYPE_NONE) {
4111                mPrivateFlags |= PFLAG_INVALIDATED;
4112                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
4113                child.mLocalDirtyRect.union(dirty);
4114            }
4115
4116            final int[] location = attachInfo.mInvalidateChildLocation;
4117            location[CHILD_LEFT_INDEX] = child.mLeft;
4118            location[CHILD_TOP_INDEX] = child.mTop;
4119            if (!childMatrix.isIdentity() ||
4120                    (mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
4121                RectF boundingRect = attachInfo.mTmpTransformRect;
4122                boundingRect.set(dirty);
4123                Matrix transformMatrix;
4124                if ((mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
4125                    Transformation t = attachInfo.mTmpTransformation;
4126                    boolean transformed = getChildStaticTransformation(child, t);
4127                    if (transformed) {
4128                        transformMatrix = attachInfo.mTmpMatrix;
4129                        transformMatrix.set(t.getMatrix());
4130                        if (!childMatrix.isIdentity()) {
4131                            transformMatrix.preConcat(childMatrix);
4132                        }
4133                    } else {
4134                        transformMatrix = childMatrix;
4135                    }
4136                } else {
4137                    transformMatrix = childMatrix;
4138                }
4139                transformMatrix.mapRect(boundingRect);
4140                dirty.set((int) (boundingRect.left - 0.5f),
4141                        (int) (boundingRect.top - 0.5f),
4142                        (int) (boundingRect.right + 0.5f),
4143                        (int) (boundingRect.bottom + 0.5f));
4144            }
4145
4146            do {
4147                View view = null;
4148                if (parent instanceof View) {
4149                    view = (View) parent;
4150                }
4151
4152                if (drawAnimation) {
4153                    if (view != null) {
4154                        view.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
4155                    } else if (parent instanceof ViewRootImpl) {
4156                        ((ViewRootImpl) parent).mIsAnimating = true;
4157                    }
4158                }
4159
4160                // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
4161                // flag coming from the child that initiated the invalidate
4162                if (view != null) {
4163                    if ((view.mViewFlags & FADING_EDGE_MASK) != 0 &&
4164                            view.getSolidColor() == 0) {
4165                        opaqueFlag = PFLAG_DIRTY;
4166                    }
4167                    if ((view.mPrivateFlags & PFLAG_DIRTY_MASK) != PFLAG_DIRTY) {
4168                        view.mPrivateFlags = (view.mPrivateFlags & ~PFLAG_DIRTY_MASK) | opaqueFlag;
4169                    }
4170                }
4171
4172                parent = parent.invalidateChildInParent(location, dirty);
4173                if (view != null) {
4174                    // Account for transform on current parent
4175                    Matrix m = view.getMatrix();
4176                    if (!m.isIdentity()) {
4177                        RectF boundingRect = attachInfo.mTmpTransformRect;
4178                        boundingRect.set(dirty);
4179                        m.mapRect(boundingRect);
4180                        dirty.set((int) (boundingRect.left - 0.5f),
4181                                (int) (boundingRect.top - 0.5f),
4182                                (int) (boundingRect.right + 0.5f),
4183                                (int) (boundingRect.bottom + 0.5f));
4184                    }
4185                }
4186            } while (parent != null);
4187        }
4188    }
4189
4190    /**
4191     * Don't call or override this method. It is used for the implementation of
4192     * the view hierarchy.
4193     *
4194     * This implementation returns null if this ViewGroup does not have a parent,
4195     * if this ViewGroup is already fully invalidated or if the dirty rectangle
4196     * does not intersect with this ViewGroup's bounds.
4197     */
4198    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
4199        if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN ||
4200                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) {
4201            if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
4202                        FLAG_OPTIMIZE_INVALIDATE) {
4203                dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
4204                        location[CHILD_TOP_INDEX] - mScrollY);
4205
4206                final int left = mLeft;
4207                final int top = mTop;
4208
4209                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
4210                    if (!dirty.intersect(0, 0, mRight - left, mBottom - top)) {
4211                        dirty.setEmpty();
4212                    }
4213                }
4214                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
4215
4216                location[CHILD_LEFT_INDEX] = left;
4217                location[CHILD_TOP_INDEX] = top;
4218
4219                if (mLayerType != LAYER_TYPE_NONE) {
4220                    mPrivateFlags |= PFLAG_INVALIDATED;
4221                    mLocalDirtyRect.union(dirty);
4222                }
4223
4224                return mParent;
4225
4226            } else {
4227                mPrivateFlags &= ~PFLAG_DRAWN & ~PFLAG_DRAWING_CACHE_VALID;
4228
4229                location[CHILD_LEFT_INDEX] = mLeft;
4230                location[CHILD_TOP_INDEX] = mTop;
4231                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
4232                    dirty.set(0, 0, mRight - mLeft, mBottom - mTop);
4233                } else {
4234                    // in case the dirty rect extends outside the bounds of this container
4235                    dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
4236                }
4237
4238                if (mLayerType != LAYER_TYPE_NONE) {
4239                    mPrivateFlags |= PFLAG_INVALIDATED;
4240                    mLocalDirtyRect.union(dirty);
4241                }
4242
4243                return mParent;
4244            }
4245        }
4246
4247        return null;
4248    }
4249
4250    /**
4251     * Quick invalidation method called by View.invalidateViewProperty. This doesn't set the
4252     * DRAWN flags and doesn't handle the Animation logic that the default invalidation methods
4253     * do; all we want to do here is schedule a traversal with the appropriate dirty rect.
4254     *
4255     * @hide
4256     */
4257    public void invalidateChildFast(View child, final Rect dirty) {
4258        ViewParent parent = this;
4259
4260        final AttachInfo attachInfo = mAttachInfo;
4261        if (attachInfo != null) {
4262            if (child.mLayerType != LAYER_TYPE_NONE) {
4263                child.mLocalDirtyRect.union(dirty);
4264            }
4265
4266            int left = child.mLeft;
4267            int top = child.mTop;
4268            if (!child.getMatrix().isIdentity()) {
4269                child.transformRect(dirty);
4270            }
4271
4272            do {
4273                if (parent instanceof ViewGroup) {
4274                    ViewGroup parentVG = (ViewGroup) parent;
4275                    if (parentVG.mLayerType != LAYER_TYPE_NONE) {
4276                        // Layered parents should be recreated, not just re-issued
4277                        parentVG.invalidate();
4278                        parent = null;
4279                    } else {
4280                        parent = parentVG.invalidateChildInParentFast(left, top, dirty);
4281                        left = parentVG.mLeft;
4282                        top = parentVG.mTop;
4283                    }
4284                } else {
4285                    // Reached the top; this calls into the usual invalidate method in
4286                    // ViewRootImpl, which schedules a traversal
4287                    final int[] location = attachInfo.mInvalidateChildLocation;
4288                    location[0] = left;
4289                    location[1] = top;
4290                    parent = parent.invalidateChildInParent(location, dirty);
4291                }
4292            } while (parent != null);
4293        }
4294    }
4295
4296    /**
4297     * Quick invalidation method that simply transforms the dirty rect into the parent's
4298     * coordinate system, pruning the invalidation if the parent has already been invalidated.
4299     */
4300    private ViewParent invalidateChildInParentFast(int left, int top, final Rect dirty) {
4301        if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN ||
4302                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) {
4303            dirty.offset(left - mScrollX, top - mScrollY);
4304
4305            if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0 ||
4306                    dirty.intersect(0, 0, mRight - mLeft, mBottom - mTop)) {
4307
4308                if (mLayerType != LAYER_TYPE_NONE) {
4309                    mLocalDirtyRect.union(dirty);
4310                }
4311                if (!getMatrix().isIdentity()) {
4312                    transformRect(dirty);
4313                }
4314
4315                return mParent;
4316            }
4317        }
4318
4319        return null;
4320    }
4321
4322    /**
4323     * Offset a rectangle that is in a descendant's coordinate
4324     * space into our coordinate space.
4325     * @param descendant A descendant of this view
4326     * @param rect A rectangle defined in descendant's coordinate space.
4327     */
4328    public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) {
4329        offsetRectBetweenParentAndChild(descendant, rect, true, false);
4330    }
4331
4332    /**
4333     * Offset a rectangle that is in our coordinate space into an ancestor's
4334     * coordinate space.
4335     * @param descendant A descendant of this view
4336     * @param rect A rectangle defined in descendant's coordinate space.
4337     */
4338    public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) {
4339        offsetRectBetweenParentAndChild(descendant, rect, false, false);
4340    }
4341
4342    /**
4343     * Helper method that offsets a rect either from parent to descendant or
4344     * descendant to parent.
4345     */
4346    void offsetRectBetweenParentAndChild(View descendant, Rect rect,
4347            boolean offsetFromChildToParent, boolean clipToBounds) {
4348
4349        // already in the same coord system :)
4350        if (descendant == this) {
4351            return;
4352        }
4353
4354        ViewParent theParent = descendant.mParent;
4355
4356        // search and offset up to the parent
4357        while ((theParent != null)
4358                && (theParent instanceof View)
4359                && (theParent != this)) {
4360
4361            if (offsetFromChildToParent) {
4362                rect.offset(descendant.mLeft - descendant.mScrollX,
4363                        descendant.mTop - descendant.mScrollY);
4364                if (clipToBounds) {
4365                    View p = (View) theParent;
4366                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4367                }
4368            } else {
4369                if (clipToBounds) {
4370                    View p = (View) theParent;
4371                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4372                }
4373                rect.offset(descendant.mScrollX - descendant.mLeft,
4374                        descendant.mScrollY - descendant.mTop);
4375            }
4376
4377            descendant = (View) theParent;
4378            theParent = descendant.mParent;
4379        }
4380
4381        // now that we are up to this view, need to offset one more time
4382        // to get into our coordinate space
4383        if (theParent == this) {
4384            if (offsetFromChildToParent) {
4385                rect.offset(descendant.mLeft - descendant.mScrollX,
4386                        descendant.mTop - descendant.mScrollY);
4387            } else {
4388                rect.offset(descendant.mScrollX - descendant.mLeft,
4389                        descendant.mScrollY - descendant.mTop);
4390            }
4391        } else {
4392            throw new IllegalArgumentException("parameter must be a descendant of this view");
4393        }
4394    }
4395
4396    /**
4397     * Offset the vertical location of all children of this view by the specified number of pixels.
4398     *
4399     * @param offset the number of pixels to offset
4400     *
4401     * @hide
4402     */
4403    public void offsetChildrenTopAndBottom(int offset) {
4404        final int count = mChildrenCount;
4405        final View[] children = mChildren;
4406
4407        for (int i = 0; i < count; i++) {
4408            final View v = children[i];
4409            v.mTop += offset;
4410            v.mBottom += offset;
4411            if (v.mDisplayList != null) {
4412                v.mDisplayList.offsetTopBottom(offset);
4413                invalidateViewProperty(false, false);
4414            }
4415        }
4416    }
4417
4418    /**
4419     * {@inheritDoc}
4420     */
4421    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
4422        // It doesn't make a whole lot of sense to call this on a view that isn't attached,
4423        // but for some simple tests it can be useful. If we don't have attach info this
4424        // will allocate memory.
4425        final RectF rect = mAttachInfo != null ? mAttachInfo.mTmpTransformRect : new RectF();
4426        rect.set(r);
4427
4428        if (!child.hasIdentityMatrix()) {
4429           child.getMatrix().mapRect(rect);
4430        }
4431
4432        int dx = child.mLeft - mScrollX;
4433        int dy = child.mTop - mScrollY;
4434
4435        rect.offset(dx, dy);
4436
4437        if (offset != null) {
4438            if (!child.hasIdentityMatrix()) {
4439                float[] position = mAttachInfo != null ? mAttachInfo.mTmpTransformLocation
4440                        : new float[2];
4441                position[0] = offset.x;
4442                position[1] = offset.y;
4443                child.getMatrix().mapPoints(position);
4444                offset.x = (int) (position[0] + 0.5f);
4445                offset.y = (int) (position[1] + 0.5f);
4446            }
4447            offset.x += dx;
4448            offset.y += dy;
4449        }
4450
4451        if (rect.intersect(0, 0, mRight - mLeft, mBottom - mTop)) {
4452            if (mParent == null) return true;
4453            r.set((int) (rect.left + 0.5f), (int) (rect.top + 0.5f),
4454                    (int) (rect.right + 0.5f), (int) (rect.bottom + 0.5f));
4455            return mParent.getChildVisibleRect(this, r, offset);
4456        }
4457
4458        return false;
4459    }
4460
4461    /**
4462     * {@inheritDoc}
4463     */
4464    @Override
4465    public final void layout(int l, int t, int r, int b) {
4466        if (mTransition == null || !mTransition.isChangingLayout()) {
4467            if (mTransition != null) {
4468                mTransition.layoutChange(this);
4469            }
4470            super.layout(l, t, r, b);
4471        } else {
4472            // record the fact that we noop'd it; request layout when transition finishes
4473            mLayoutSuppressed = true;
4474        }
4475    }
4476
4477    /**
4478     * {@inheritDoc}
4479     */
4480    @Override
4481    protected abstract void onLayout(boolean changed,
4482            int l, int t, int r, int b);
4483
4484    /**
4485     * Indicates whether the view group has the ability to animate its children
4486     * after the first layout.
4487     *
4488     * @return true if the children can be animated, false otherwise
4489     */
4490    protected boolean canAnimate() {
4491        return mLayoutAnimationController != null;
4492    }
4493
4494    /**
4495     * Runs the layout animation. Calling this method triggers a relayout of
4496     * this view group.
4497     */
4498    public void startLayoutAnimation() {
4499        if (mLayoutAnimationController != null) {
4500            mGroupFlags |= FLAG_RUN_ANIMATION;
4501            requestLayout();
4502        }
4503    }
4504
4505    /**
4506     * Schedules the layout animation to be played after the next layout pass
4507     * of this view group. This can be used to restart the layout animation
4508     * when the content of the view group changes or when the activity is
4509     * paused and resumed.
4510     */
4511    public void scheduleLayoutAnimation() {
4512        mGroupFlags |= FLAG_RUN_ANIMATION;
4513    }
4514
4515    /**
4516     * Sets the layout animation controller used to animate the group's
4517     * children after the first layout.
4518     *
4519     * @param controller the animation controller
4520     */
4521    public void setLayoutAnimation(LayoutAnimationController controller) {
4522        mLayoutAnimationController = controller;
4523        if (mLayoutAnimationController != null) {
4524            mGroupFlags |= FLAG_RUN_ANIMATION;
4525        }
4526    }
4527
4528    /**
4529     * Returns the layout animation controller used to animate the group's
4530     * children.
4531     *
4532     * @return the current animation controller
4533     */
4534    public LayoutAnimationController getLayoutAnimation() {
4535        return mLayoutAnimationController;
4536    }
4537
4538    /**
4539     * Indicates whether the children's drawing cache is used during a layout
4540     * animation. By default, the drawing cache is enabled but this will prevent
4541     * nested layout animations from working. To nest animations, you must disable
4542     * the cache.
4543     *
4544     * @return true if the animation cache is enabled, false otherwise
4545     *
4546     * @see #setAnimationCacheEnabled(boolean)
4547     * @see View#setDrawingCacheEnabled(boolean)
4548     */
4549    @ViewDebug.ExportedProperty
4550    public boolean isAnimationCacheEnabled() {
4551        return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
4552    }
4553
4554    /**
4555     * Enables or disables the children's drawing cache during a layout animation.
4556     * By default, the drawing cache is enabled but this will prevent nested
4557     * layout animations from working. To nest animations, you must disable the
4558     * cache.
4559     *
4560     * @param enabled true to enable the animation cache, false otherwise
4561     *
4562     * @see #isAnimationCacheEnabled()
4563     * @see View#setDrawingCacheEnabled(boolean)
4564     */
4565    public void setAnimationCacheEnabled(boolean enabled) {
4566        setBooleanFlag(FLAG_ANIMATION_CACHE, enabled);
4567    }
4568
4569    /**
4570     * Indicates whether this ViewGroup will always try to draw its children using their
4571     * drawing cache. By default this property is enabled.
4572     *
4573     * @return true if the animation cache is enabled, false otherwise
4574     *
4575     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4576     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4577     * @see View#setDrawingCacheEnabled(boolean)
4578     */
4579    @ViewDebug.ExportedProperty(category = "drawing")
4580    public boolean isAlwaysDrawnWithCacheEnabled() {
4581        return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE;
4582    }
4583
4584    /**
4585     * Indicates whether this ViewGroup will always try to draw its children using their
4586     * drawing cache. This property can be set to true when the cache rendering is
4587     * slightly different from the children's normal rendering. Renderings can be different,
4588     * for instance, when the cache's quality is set to low.
4589     *
4590     * When this property is disabled, the ViewGroup will use the drawing cache of its
4591     * children only when asked to. It's usually the task of subclasses to tell ViewGroup
4592     * when to start using the drawing cache and when to stop using it.
4593     *
4594     * @param always true to always draw with the drawing cache, false otherwise
4595     *
4596     * @see #isAlwaysDrawnWithCacheEnabled()
4597     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4598     * @see View#setDrawingCacheEnabled(boolean)
4599     * @see View#setDrawingCacheQuality(int)
4600     */
4601    public void setAlwaysDrawnWithCacheEnabled(boolean always) {
4602        setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always);
4603    }
4604
4605    /**
4606     * Indicates whether the ViewGroup is currently drawing its children using
4607     * their drawing cache.
4608     *
4609     * @return true if children should be drawn with their cache, false otherwise
4610     *
4611     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4612     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4613     */
4614    @ViewDebug.ExportedProperty(category = "drawing")
4615    protected boolean isChildrenDrawnWithCacheEnabled() {
4616        return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE;
4617    }
4618
4619    /**
4620     * Tells the ViewGroup to draw its children using their drawing cache. This property
4621     * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache
4622     * will be used only if it has been enabled.
4623     *
4624     * Subclasses should call this method to start and stop using the drawing cache when
4625     * they perform performance sensitive operations, like scrolling or animating.
4626     *
4627     * @param enabled true if children should be drawn with their cache, false otherwise
4628     *
4629     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4630     * @see #isChildrenDrawnWithCacheEnabled()
4631     */
4632    protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
4633        setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled);
4634    }
4635
4636    /**
4637     * Indicates whether the ViewGroup is drawing its children in the order defined by
4638     * {@link #getChildDrawingOrder(int, int)}.
4639     *
4640     * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)},
4641     *         false otherwise
4642     *
4643     * @see #setChildrenDrawingOrderEnabled(boolean)
4644     * @see #getChildDrawingOrder(int, int)
4645     */
4646    @ViewDebug.ExportedProperty(category = "drawing")
4647    protected boolean isChildrenDrawingOrderEnabled() {
4648        return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER;
4649    }
4650
4651    /**
4652     * Tells the ViewGroup whether to draw its children in the order defined by the method
4653     * {@link #getChildDrawingOrder(int, int)}.
4654     *
4655     * @param enabled true if the order of the children when drawing is determined by
4656     *        {@link #getChildDrawingOrder(int, int)}, false otherwise
4657     *
4658     * @see #isChildrenDrawingOrderEnabled()
4659     * @see #getChildDrawingOrder(int, int)
4660     */
4661    protected void setChildrenDrawingOrderEnabled(boolean enabled) {
4662        setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled);
4663    }
4664
4665    private void setBooleanFlag(int flag, boolean value) {
4666        if (value) {
4667            mGroupFlags |= flag;
4668        } else {
4669            mGroupFlags &= ~flag;
4670        }
4671    }
4672
4673    /**
4674     * Returns an integer indicating what types of drawing caches are kept in memory.
4675     *
4676     * @see #setPersistentDrawingCache(int)
4677     * @see #setAnimationCacheEnabled(boolean)
4678     *
4679     * @return one or a combination of {@link #PERSISTENT_NO_CACHE},
4680     *         {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4681     *         and {@link #PERSISTENT_ALL_CACHES}
4682     */
4683    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4684        @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE,        to = "NONE"),
4685        @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"),
4686        @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"),
4687        @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES,      to = "ALL")
4688    })
4689    public int getPersistentDrawingCache() {
4690        return mPersistentDrawingCache;
4691    }
4692
4693    /**
4694     * Indicates what types of drawing caches should be kept in memory after
4695     * they have been created.
4696     *
4697     * @see #getPersistentDrawingCache()
4698     * @see #setAnimationCacheEnabled(boolean)
4699     *
4700     * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE},
4701     *        {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4702     *        and {@link #PERSISTENT_ALL_CACHES}
4703     */
4704    public void setPersistentDrawingCache(int drawingCacheToKeep) {
4705        mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES;
4706    }
4707
4708    /**
4709     * Returns the basis of alignment during layout operations on this view group:
4710     * either {@link #LAYOUT_MODE_CLIP_BOUNDS} or {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
4711     *
4712     * @return the layout mode to use during layout operations
4713     *
4714     * @see #setLayoutMode(int)
4715     */
4716    public int getLayoutMode() {
4717        return mLayoutMode;
4718    }
4719
4720    /**
4721     * Sets the basis of alignment during the layout of this view group.
4722     * Valid values are either {@link #LAYOUT_MODE_CLIP_BOUNDS} or
4723     * {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
4724     * <p>
4725     * The default is {@link #LAYOUT_MODE_CLIP_BOUNDS}.
4726     *
4727     * @param layoutMode the layout mode to use during layout operations
4728     *
4729     * @see #getLayoutMode()
4730     */
4731    public void setLayoutMode(int layoutMode) {
4732        if (mLayoutMode != layoutMode) {
4733            mLayoutMode = layoutMode;
4734            requestLayout();
4735        }
4736    }
4737
4738    /**
4739     * Returns a new set of layout parameters based on the supplied attributes set.
4740     *
4741     * @param attrs the attributes to build the layout parameters from
4742     *
4743     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4744     *         of its descendants
4745     */
4746    public LayoutParams generateLayoutParams(AttributeSet attrs) {
4747        return new LayoutParams(getContext(), attrs);
4748    }
4749
4750    /**
4751     * Returns a safe set of layout parameters based on the supplied layout params.
4752     * When a ViewGroup is passed a View whose layout params do not pass the test of
4753     * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
4754     * is invoked. This method should return a new set of layout params suitable for
4755     * this ViewGroup, possibly by copying the appropriate attributes from the
4756     * specified set of layout params.
4757     *
4758     * @param p The layout parameters to convert into a suitable set of layout parameters
4759     *          for this ViewGroup.
4760     *
4761     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4762     *         of its descendants
4763     */
4764    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
4765        return p;
4766    }
4767
4768    /**
4769     * Returns a set of default layout parameters. These parameters are requested
4770     * when the View passed to {@link #addView(View)} has no layout parameters
4771     * already set. If null is returned, an exception is thrown from addView.
4772     *
4773     * @return a set of default layout parameters or null
4774     */
4775    protected LayoutParams generateDefaultLayoutParams() {
4776        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
4777    }
4778
4779    /**
4780     * {@inheritDoc}
4781     */
4782    @Override
4783    protected void debug(int depth) {
4784        super.debug(depth);
4785        String output;
4786
4787        if (mFocused != null) {
4788            output = debugIndent(depth);
4789            output += "mFocused";
4790            Log.d(VIEW_LOG_TAG, output);
4791        }
4792        if (mChildrenCount != 0) {
4793            output = debugIndent(depth);
4794            output += "{";
4795            Log.d(VIEW_LOG_TAG, output);
4796        }
4797        int count = mChildrenCount;
4798        for (int i = 0; i < count; i++) {
4799            View child = mChildren[i];
4800            child.debug(depth + 1);
4801        }
4802
4803        if (mChildrenCount != 0) {
4804            output = debugIndent(depth);
4805            output += "}";
4806            Log.d(VIEW_LOG_TAG, output);
4807        }
4808    }
4809
4810    /**
4811     * Returns the position in the group of the specified child view.
4812     *
4813     * @param child the view for which to get the position
4814     * @return a positive integer representing the position of the view in the
4815     *         group, or -1 if the view does not exist in the group
4816     */
4817    public int indexOfChild(View child) {
4818        final int count = mChildrenCount;
4819        final View[] children = mChildren;
4820        for (int i = 0; i < count; i++) {
4821            if (children[i] == child) {
4822                return i;
4823            }
4824        }
4825        return -1;
4826    }
4827
4828    /**
4829     * Returns the number of children in the group.
4830     *
4831     * @return a positive integer representing the number of children in
4832     *         the group
4833     */
4834    public int getChildCount() {
4835        return mChildrenCount;
4836    }
4837
4838    /**
4839     * Returns the view at the specified position in the group.
4840     *
4841     * @param index the position at which to get the view from
4842     * @return the view at the specified position or null if the position
4843     *         does not exist within the group
4844     */
4845    public View getChildAt(int index) {
4846        if (index < 0 || index >= mChildrenCount) {
4847            return null;
4848        }
4849        return mChildren[index];
4850    }
4851
4852    /**
4853     * Ask all of the children of this view to measure themselves, taking into
4854     * account both the MeasureSpec requirements for this view and its padding.
4855     * We skip children that are in the GONE state The heavy lifting is done in
4856     * getChildMeasureSpec.
4857     *
4858     * @param widthMeasureSpec The width requirements for this view
4859     * @param heightMeasureSpec The height requirements for this view
4860     */
4861    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
4862        final int size = mChildrenCount;
4863        final View[] children = mChildren;
4864        for (int i = 0; i < size; ++i) {
4865            final View child = children[i];
4866            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
4867                measureChild(child, widthMeasureSpec, heightMeasureSpec);
4868            }
4869        }
4870    }
4871
4872    /**
4873     * Ask one of the children of this view to measure itself, taking into
4874     * account both the MeasureSpec requirements for this view and its padding.
4875     * The heavy lifting is done in getChildMeasureSpec.
4876     *
4877     * @param child The child to measure
4878     * @param parentWidthMeasureSpec The width requirements for this view
4879     * @param parentHeightMeasureSpec The height requirements for this view
4880     */
4881    protected void measureChild(View child, int parentWidthMeasureSpec,
4882            int parentHeightMeasureSpec) {
4883        final LayoutParams lp = child.getLayoutParams();
4884
4885        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4886                mPaddingLeft + mPaddingRight, lp.width);
4887        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4888                mPaddingTop + mPaddingBottom, lp.height);
4889
4890        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4891    }
4892
4893    /**
4894     * Ask one of the children of this view to measure itself, taking into
4895     * account both the MeasureSpec requirements for this view and its padding
4896     * and margins. The child must have MarginLayoutParams The heavy lifting is
4897     * done in getChildMeasureSpec.
4898     *
4899     * @param child The child to measure
4900     * @param parentWidthMeasureSpec The width requirements for this view
4901     * @param widthUsed Extra space that has been used up by the parent
4902     *        horizontally (possibly by other children of the parent)
4903     * @param parentHeightMeasureSpec The height requirements for this view
4904     * @param heightUsed Extra space that has been used up by the parent
4905     *        vertically (possibly by other children of the parent)
4906     */
4907    protected void measureChildWithMargins(View child,
4908            int parentWidthMeasureSpec, int widthUsed,
4909            int parentHeightMeasureSpec, int heightUsed) {
4910        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
4911        final int layoutDirection = getLayoutDirection();
4912        lp.resolveLayoutDirection(layoutDirection);
4913
4914        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4915                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
4916                        + widthUsed, lp.width);
4917        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4918                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
4919                        + heightUsed, lp.height);
4920
4921        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4922    }
4923
4924    /**
4925     * Does the hard part of measureChildren: figuring out the MeasureSpec to
4926     * pass to a particular child. This method figures out the right MeasureSpec
4927     * for one dimension (height or width) of one child view.
4928     *
4929     * The goal is to combine information from our MeasureSpec with the
4930     * LayoutParams of the child to get the best possible results. For example,
4931     * if the this view knows its size (because its MeasureSpec has a mode of
4932     * EXACTLY), and the child has indicated in its LayoutParams that it wants
4933     * to be the same size as the parent, the parent should ask the child to
4934     * layout given an exact size.
4935     *
4936     * @param spec The requirements for this view
4937     * @param padding The padding of this view for the current dimension and
4938     *        margins, if applicable
4939     * @param childDimension How big the child wants to be in the current
4940     *        dimension
4941     * @return a MeasureSpec integer for the child
4942     */
4943    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
4944        int specMode = MeasureSpec.getMode(spec);
4945        int specSize = MeasureSpec.getSize(spec);
4946
4947        int size = Math.max(0, specSize - padding);
4948
4949        int resultSize = 0;
4950        int resultMode = 0;
4951
4952        switch (specMode) {
4953        // Parent has imposed an exact size on us
4954        case MeasureSpec.EXACTLY:
4955            if (childDimension >= 0) {
4956                resultSize = childDimension;
4957                resultMode = MeasureSpec.EXACTLY;
4958            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4959                // Child wants to be our size. So be it.
4960                resultSize = size;
4961                resultMode = MeasureSpec.EXACTLY;
4962            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4963                // Child wants to determine its own size. It can't be
4964                // bigger than us.
4965                resultSize = size;
4966                resultMode = MeasureSpec.AT_MOST;
4967            }
4968            break;
4969
4970        // Parent has imposed a maximum size on us
4971        case MeasureSpec.AT_MOST:
4972            if (childDimension >= 0) {
4973                // Child wants a specific size... so be it
4974                resultSize = childDimension;
4975                resultMode = MeasureSpec.EXACTLY;
4976            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4977                // Child wants to be our size, but our size is not fixed.
4978                // Constrain child to not be bigger than us.
4979                resultSize = size;
4980                resultMode = MeasureSpec.AT_MOST;
4981            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4982                // Child wants to determine its own size. It can't be
4983                // bigger than us.
4984                resultSize = size;
4985                resultMode = MeasureSpec.AT_MOST;
4986            }
4987            break;
4988
4989        // Parent asked to see how big we want to be
4990        case MeasureSpec.UNSPECIFIED:
4991            if (childDimension >= 0) {
4992                // Child wants a specific size... let him have it
4993                resultSize = childDimension;
4994                resultMode = MeasureSpec.EXACTLY;
4995            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4996                // Child wants to be our size... find out how big it should
4997                // be
4998                resultSize = 0;
4999                resultMode = MeasureSpec.UNSPECIFIED;
5000            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
5001                // Child wants to determine its own size.... find out how
5002                // big it should be
5003                resultSize = 0;
5004                resultMode = MeasureSpec.UNSPECIFIED;
5005            }
5006            break;
5007        }
5008        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
5009    }
5010
5011
5012    /**
5013     * Removes any pending animations for views that have been removed. Call
5014     * this if you don't want animations for exiting views to stack up.
5015     */
5016    public void clearDisappearingChildren() {
5017        if (mDisappearingChildren != null) {
5018            mDisappearingChildren.clear();
5019            invalidate();
5020        }
5021    }
5022
5023    /**
5024     * Add a view which is removed from mChildren but still needs animation
5025     *
5026     * @param v View to add
5027     */
5028    private void addDisappearingView(View v) {
5029        ArrayList<View> disappearingChildren = mDisappearingChildren;
5030
5031        if (disappearingChildren == null) {
5032            disappearingChildren = mDisappearingChildren = new ArrayList<View>();
5033        }
5034
5035        disappearingChildren.add(v);
5036    }
5037
5038    /**
5039     * Cleanup a view when its animation is done. This may mean removing it from
5040     * the list of disappearing views.
5041     *
5042     * @param view The view whose animation has finished
5043     * @param animation The animation, cannot be null
5044     */
5045    void finishAnimatingView(final View view, Animation animation) {
5046        final ArrayList<View> disappearingChildren = mDisappearingChildren;
5047        if (disappearingChildren != null) {
5048            if (disappearingChildren.contains(view)) {
5049                disappearingChildren.remove(view);
5050
5051                if (view.mAttachInfo != null) {
5052                    view.dispatchDetachedFromWindow();
5053                }
5054
5055                view.clearAnimation();
5056                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
5057            }
5058        }
5059
5060        if (animation != null && !animation.getFillAfter()) {
5061            view.clearAnimation();
5062        }
5063
5064        if ((view.mPrivateFlags & PFLAG_ANIMATION_STARTED) == PFLAG_ANIMATION_STARTED) {
5065            view.onAnimationEnd();
5066            // Should be performed by onAnimationEnd() but this avoid an infinite loop,
5067            // so we'd rather be safe than sorry
5068            view.mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
5069            // Draw one more frame after the animation is done
5070            mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
5071        }
5072    }
5073
5074    /**
5075     * Utility function called by View during invalidation to determine whether a view that
5076     * is invisible or gone should still be invalidated because it is being transitioned (and
5077     * therefore still needs to be drawn).
5078     */
5079    boolean isViewTransitioning(View view) {
5080        return (mTransitioningViews != null && mTransitioningViews.contains(view));
5081    }
5082
5083    /**
5084     * This method tells the ViewGroup that the given View object, which should have this
5085     * ViewGroup as its parent,
5086     * should be kept around  (re-displayed when the ViewGroup draws its children) even if it
5087     * is removed from its parent. This allows animations, such as those used by
5088     * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate
5089     * the removal of views. A call to this method should always be accompanied by a later call
5090     * to {@link #endViewTransition(View)}, such as after an animation on the View has finished,
5091     * so that the View finally gets removed.
5092     *
5093     * @param view The View object to be kept visible even if it gets removed from its parent.
5094     */
5095    public void startViewTransition(View view) {
5096        if (view.mParent == this) {
5097            if (mTransitioningViews == null) {
5098                mTransitioningViews = new ArrayList<View>();
5099            }
5100            mTransitioningViews.add(view);
5101        }
5102    }
5103
5104    /**
5105     * This method should always be called following an earlier call to
5106     * {@link #startViewTransition(View)}. The given View is finally removed from its parent
5107     * and will no longer be displayed. Note that this method does not perform the functionality
5108     * of removing a view from its parent; it just discontinues the display of a View that
5109     * has previously been removed.
5110     *
5111     * @return view The View object that has been removed but is being kept around in the visible
5112     * hierarchy by an earlier call to {@link #startViewTransition(View)}.
5113     */
5114    public void endViewTransition(View view) {
5115        if (mTransitioningViews != null) {
5116            mTransitioningViews.remove(view);
5117            final ArrayList<View> disappearingChildren = mDisappearingChildren;
5118            if (disappearingChildren != null && disappearingChildren.contains(view)) {
5119                disappearingChildren.remove(view);
5120                if (mVisibilityChangingChildren != null &&
5121                        mVisibilityChangingChildren.contains(view)) {
5122                    mVisibilityChangingChildren.remove(view);
5123                } else {
5124                    if (view.mAttachInfo != null) {
5125                        view.dispatchDetachedFromWindow();
5126                    }
5127                    if (view.mParent != null) {
5128                        view.mParent = null;
5129                    }
5130                }
5131                invalidate();
5132            }
5133        }
5134    }
5135
5136    private LayoutTransition.TransitionListener mLayoutTransitionListener =
5137            new LayoutTransition.TransitionListener() {
5138        @Override
5139        public void startTransition(LayoutTransition transition, ViewGroup container,
5140                View view, int transitionType) {
5141            // We only care about disappearing items, since we need special logic to keep
5142            // those items visible after they've been 'removed'
5143            if (transitionType == LayoutTransition.DISAPPEARING) {
5144                startViewTransition(view);
5145            }
5146        }
5147
5148        @Override
5149        public void endTransition(LayoutTransition transition, ViewGroup container,
5150                View view, int transitionType) {
5151            if (mLayoutSuppressed && !transition.isChangingLayout()) {
5152                requestLayout();
5153                mLayoutSuppressed = false;
5154            }
5155            if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
5156                endViewTransition(view);
5157            }
5158        }
5159    };
5160
5161    /**
5162     * {@inheritDoc}
5163     */
5164    @Override
5165    public boolean gatherTransparentRegion(Region region) {
5166        // If no transparent regions requested, we are always opaque.
5167        final boolean meOpaque = (mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0;
5168        if (meOpaque && region == null) {
5169            // The caller doesn't care about the region, so stop now.
5170            return true;
5171        }
5172        super.gatherTransparentRegion(region);
5173        final View[] children = mChildren;
5174        final int count = mChildrenCount;
5175        boolean noneOfTheChildrenAreTransparent = true;
5176        for (int i = 0; i < count; i++) {
5177            final View child = children[i];
5178            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
5179                if (!child.gatherTransparentRegion(region)) {
5180                    noneOfTheChildrenAreTransparent = false;
5181                }
5182            }
5183        }
5184        return meOpaque || noneOfTheChildrenAreTransparent;
5185    }
5186
5187    /**
5188     * {@inheritDoc}
5189     */
5190    public void requestTransparentRegion(View child) {
5191        if (child != null) {
5192            child.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
5193            if (mParent != null) {
5194                mParent.requestTransparentRegion(this);
5195            }
5196        }
5197    }
5198
5199
5200    @Override
5201    protected boolean fitSystemWindows(Rect insets) {
5202        boolean done = super.fitSystemWindows(insets);
5203        if (!done) {
5204            final int count = mChildrenCount;
5205            final View[] children = mChildren;
5206            for (int i = 0; i < count; i++) {
5207                done = children[i].fitSystemWindows(insets);
5208                if (done) {
5209                    break;
5210                }
5211            }
5212        }
5213        return done;
5214    }
5215
5216    /**
5217     * Returns the animation listener to which layout animation events are
5218     * sent.
5219     *
5220     * @return an {@link android.view.animation.Animation.AnimationListener}
5221     */
5222    public Animation.AnimationListener getLayoutAnimationListener() {
5223        return mAnimationListener;
5224    }
5225
5226    @Override
5227    protected void drawableStateChanged() {
5228        super.drawableStateChanged();
5229
5230        if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
5231            if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5232                throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
5233                        + " child has duplicateParentState set to true");
5234            }
5235
5236            final View[] children = mChildren;
5237            final int count = mChildrenCount;
5238
5239            for (int i = 0; i < count; i++) {
5240                final View child = children[i];
5241                if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
5242                    child.refreshDrawableState();
5243                }
5244            }
5245        }
5246    }
5247
5248    @Override
5249    public void jumpDrawablesToCurrentState() {
5250        super.jumpDrawablesToCurrentState();
5251        final View[] children = mChildren;
5252        final int count = mChildrenCount;
5253        for (int i = 0; i < count; i++) {
5254            children[i].jumpDrawablesToCurrentState();
5255        }
5256    }
5257
5258    @Override
5259    protected int[] onCreateDrawableState(int extraSpace) {
5260        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) {
5261            return super.onCreateDrawableState(extraSpace);
5262        }
5263
5264        int need = 0;
5265        int n = getChildCount();
5266        for (int i = 0; i < n; i++) {
5267            int[] childState = getChildAt(i).getDrawableState();
5268
5269            if (childState != null) {
5270                need += childState.length;
5271            }
5272        }
5273
5274        int[] state = super.onCreateDrawableState(extraSpace + need);
5275
5276        for (int i = 0; i < n; i++) {
5277            int[] childState = getChildAt(i).getDrawableState();
5278
5279            if (childState != null) {
5280                state = mergeDrawableStates(state, childState);
5281            }
5282        }
5283
5284        return state;
5285    }
5286
5287    /**
5288     * Sets whether this ViewGroup's drawable states also include
5289     * its children's drawable states.  This is used, for example, to
5290     * make a group appear to be focused when its child EditText or button
5291     * is focused.
5292     */
5293    public void setAddStatesFromChildren(boolean addsStates) {
5294        if (addsStates) {
5295            mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN;
5296        } else {
5297            mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN;
5298        }
5299
5300        refreshDrawableState();
5301    }
5302
5303    /**
5304     * Returns whether this ViewGroup's drawable states also include
5305     * its children's drawable states.  This is used, for example, to
5306     * make a group appear to be focused when its child EditText or button
5307     * is focused.
5308     */
5309    public boolean addStatesFromChildren() {
5310        return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0;
5311    }
5312
5313    /**
5314     * If {@link #addStatesFromChildren} is true, refreshes this group's
5315     * drawable state (to include the states from its children).
5316     */
5317    public void childDrawableStateChanged(View child) {
5318        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5319            refreshDrawableState();
5320        }
5321    }
5322
5323    /**
5324     * Specifies the animation listener to which layout animation events must
5325     * be sent. Only
5326     * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)}
5327     * and
5328     * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)}
5329     * are invoked.
5330     *
5331     * @param animationListener the layout animation listener
5332     */
5333    public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
5334        mAnimationListener = animationListener;
5335    }
5336
5337    /**
5338     * This method is called by LayoutTransition when there are 'changing' animations that need
5339     * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who
5340     * starts all pending transitions prior to the drawing phase in the current traversal.
5341     *
5342     * @param transition The LayoutTransition to be started on the next traversal.
5343     *
5344     * @hide
5345     */
5346    public void requestTransitionStart(LayoutTransition transition) {
5347        ViewRootImpl viewAncestor = getViewRootImpl();
5348        if (viewAncestor != null) {
5349            viewAncestor.requestTransitionStart(transition);
5350        }
5351    }
5352
5353    /**
5354     * @hide
5355     */
5356    @Override
5357    public void resolveRtlPropertiesIfNeeded() {
5358        super.resolveRtlPropertiesIfNeeded();
5359        int count = getChildCount();
5360        for (int i = 0; i < count; i++) {
5361            final View child = getChildAt(i);
5362            if (child.isLayoutDirectionInherited()) {
5363                child.resolveRtlPropertiesIfNeeded();
5364            }
5365        }
5366    }
5367
5368    /**
5369     * @hide
5370     */
5371    @Override
5372    public boolean resolveLayoutDirection() {
5373        final boolean result = super.resolveLayoutDirection();
5374        if (result) {
5375            int count = getChildCount();
5376            for (int i = 0; i < count; i++) {
5377                final View child = getChildAt(i);
5378                if (child.isLayoutDirectionInherited()) {
5379                    child.resolveLayoutDirection();
5380                }
5381            }
5382        }
5383        return result;
5384    }
5385
5386    /**
5387     * @hide
5388     */
5389    @Override
5390    public boolean resolveTextDirection() {
5391        final boolean result = super.resolveTextDirection();
5392        if (result) {
5393            int count = getChildCount();
5394            for (int i = 0; i < count; i++) {
5395                final View child = getChildAt(i);
5396                if (child.isTextDirectionInherited()) {
5397                    child.resolveTextDirection();
5398                }
5399            }
5400        }
5401        return result;
5402    }
5403
5404    /**
5405     * @hide
5406     */
5407    @Override
5408    public boolean resolveTextAlignment() {
5409        final boolean result = super.resolveTextAlignment();
5410        if (result) {
5411            int count = getChildCount();
5412            for (int i = 0; i < count; i++) {
5413                final View child = getChildAt(i);
5414                if (child.isTextAlignmentInherited()) {
5415                    child.resolveTextAlignment();
5416                }
5417            }
5418        }
5419        return result;
5420    }
5421
5422    /**
5423     * @hide
5424     */
5425    @Override
5426    public void resolvePadding() {
5427        super.resolvePadding();
5428        int count = getChildCount();
5429        for (int i = 0; i < count; i++) {
5430            final View child = getChildAt(i);
5431            if (child.isLayoutDirectionInherited()) {
5432                child.resolvePadding();
5433            }
5434        }
5435    }
5436
5437    /**
5438     * @hide
5439     */
5440    @Override
5441    protected void resolveDrawables() {
5442        super.resolveDrawables();
5443        int count = getChildCount();
5444        for (int i = 0; i < count; i++) {
5445            final View child = getChildAt(i);
5446            if (child.isLayoutDirectionInherited()) {
5447                child.resolveDrawables();
5448            }
5449        }
5450    }
5451
5452    /**
5453     * @hide
5454     */
5455    @Override
5456    public void resetRtlProperties() {
5457        super.resetRtlProperties();
5458        int count = getChildCount();
5459        for (int i = 0; i < count; i++) {
5460            final View child = getChildAt(i);
5461            if (child.isLayoutDirectionInherited()) {
5462                child.resetRtlProperties();
5463            }
5464        }
5465    }
5466
5467    /**
5468     * @hide
5469     */
5470    @Override
5471    public void resetResolvedLayoutDirection() {
5472        super.resetResolvedLayoutDirection();
5473
5474        int count = getChildCount();
5475        for (int i = 0; i < count; i++) {
5476            final View child = getChildAt(i);
5477            if (child.isLayoutDirectionInherited()) {
5478                child.resetResolvedLayoutDirection();
5479            }
5480        }
5481    }
5482
5483    /**
5484     * @hide
5485     */
5486    @Override
5487    public void resetResolvedTextDirection() {
5488        super.resetResolvedTextDirection();
5489
5490        int count = getChildCount();
5491        for (int i = 0; i < count; i++) {
5492            final View child = getChildAt(i);
5493            if (child.isTextDirectionInherited()) {
5494                child.resetResolvedTextDirection();
5495            }
5496        }
5497    }
5498
5499    /**
5500     * @hide
5501     */
5502    @Override
5503    public void resetResolvedTextAlignment() {
5504        super.resetResolvedTextAlignment();
5505
5506        int count = getChildCount();
5507        for (int i = 0; i < count; i++) {
5508            final View child = getChildAt(i);
5509            if (child.isTextAlignmentInherited()) {
5510                child.resetResolvedTextAlignment();
5511            }
5512        }
5513    }
5514
5515    /**
5516     * @hide
5517     */
5518    @Override
5519    public void resetResolvedPadding() {
5520        super.resetResolvedPadding();
5521
5522        int count = getChildCount();
5523        for (int i = 0; i < count; i++) {
5524            final View child = getChildAt(i);
5525            if (child.isLayoutDirectionInherited()) {
5526                child.resetResolvedPadding();
5527            }
5528        }
5529    }
5530
5531    /**
5532     * @hide
5533     */
5534    @Override
5535    protected void resetResolvedDrawables() {
5536        super.resetResolvedDrawables();
5537
5538        int count = getChildCount();
5539        for (int i = 0; i < count; i++) {
5540            final View child = getChildAt(i);
5541            if (child.isLayoutDirectionInherited()) {
5542                child.resetResolvedDrawables();
5543            }
5544        }
5545    }
5546
5547    /**
5548     * Return true if the pressed state should be delayed for children or descendants of this
5549     * ViewGroup. Generally, this should be done for containers that can scroll, such as a List.
5550     * This prevents the pressed state from appearing when the user is actually trying to scroll
5551     * the content.
5552     *
5553     * The default implementation returns true for compatibility reasons. Subclasses that do
5554     * not scroll should generally override this method and return false.
5555     */
5556    public boolean shouldDelayChildPressedState() {
5557        return true;
5558    }
5559
5560    /** @hide */
5561    protected void onSetLayoutParams(View child, LayoutParams layoutParams) {
5562    }
5563
5564    /**
5565     * LayoutParams are used by views to tell their parents how they want to be
5566     * laid out. See
5567     * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes}
5568     * for a list of all child view attributes that this class supports.
5569     *
5570     * <p>
5571     * The base LayoutParams class just describes how big the view wants to be
5572     * for both width and height. For each dimension, it can specify one of:
5573     * <ul>
5574     * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
5575     * means that the view wants to be as big as its parent (minus padding)
5576     * <li> WRAP_CONTENT, which means that the view wants to be just big enough
5577     * to enclose its content (plus padding)
5578     * <li> an exact number
5579     * </ul>
5580     * There are subclasses of LayoutParams for different subclasses of
5581     * ViewGroup. For example, AbsoluteLayout has its own subclass of
5582     * LayoutParams which adds an X and Y value.</p>
5583     *
5584     * <div class="special reference">
5585     * <h3>Developer Guides</h3>
5586     * <p>For more information about creating user interface layouts, read the
5587     * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer
5588     * guide.</p></div>
5589     *
5590     * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
5591     * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
5592     */
5593    public static class LayoutParams {
5594        /**
5595         * Special value for the height or width requested by a View.
5596         * FILL_PARENT means that the view wants to be as big as its parent,
5597         * minus the parent's padding, if any. This value is deprecated
5598         * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
5599         */
5600        @SuppressWarnings({"UnusedDeclaration"})
5601        @Deprecated
5602        public static final int FILL_PARENT = -1;
5603
5604        /**
5605         * Special value for the height or width requested by a View.
5606         * MATCH_PARENT means that the view wants to be as big as its parent,
5607         * minus the parent's padding, if any. Introduced in API Level 8.
5608         */
5609        public static final int MATCH_PARENT = -1;
5610
5611        /**
5612         * Special value for the height or width requested by a View.
5613         * WRAP_CONTENT means that the view wants to be just large enough to fit
5614         * its own internal content, taking its own padding into account.
5615         */
5616        public static final int WRAP_CONTENT = -2;
5617
5618        /**
5619         * Information about how wide the view wants to be. Can be one of the
5620         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5621         * in API Level 8) or WRAP_CONTENT. or an exact size.
5622         */
5623        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5624            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5625            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5626        })
5627        public int width;
5628
5629        /**
5630         * Information about how tall the view wants to be. Can be one of the
5631         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5632         * in API Level 8) or WRAP_CONTENT. or an exact size.
5633         */
5634        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5635            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5636            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5637        })
5638        public int height;
5639
5640        /**
5641         * Used to animate layouts.
5642         */
5643        public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
5644
5645        /**
5646         * Creates a new set of layout parameters. The values are extracted from
5647         * the supplied attributes set and context. The XML attributes mapped
5648         * to this set of layout parameters are:
5649         *
5650         * <ul>
5651         *   <li><code>layout_width</code>: the width, either an exact value,
5652         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5653         *   {@link #MATCH_PARENT} in API Level 8)</li>
5654         *   <li><code>layout_height</code>: the height, either an exact value,
5655         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5656         *   {@link #MATCH_PARENT} in API Level 8)</li>
5657         * </ul>
5658         *
5659         * @param c the application environment
5660         * @param attrs the set of attributes from which to extract the layout
5661         *              parameters' values
5662         */
5663        public LayoutParams(Context c, AttributeSet attrs) {
5664            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
5665            setBaseAttributes(a,
5666                    R.styleable.ViewGroup_Layout_layout_width,
5667                    R.styleable.ViewGroup_Layout_layout_height);
5668            a.recycle();
5669        }
5670
5671        /**
5672         * Creates a new set of layout parameters with the specified width
5673         * and height.
5674         *
5675         * @param width the width, either {@link #WRAP_CONTENT},
5676         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5677         *        API Level 8), or a fixed size in pixels
5678         * @param height the height, either {@link #WRAP_CONTENT},
5679         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5680         *        API Level 8), or a fixed size in pixels
5681         */
5682        public LayoutParams(int width, int height) {
5683            this.width = width;
5684            this.height = height;
5685        }
5686
5687        /**
5688         * Copy constructor. Clones the width and height values of the source.
5689         *
5690         * @param source The layout params to copy from.
5691         */
5692        public LayoutParams(LayoutParams source) {
5693            this.width = source.width;
5694            this.height = source.height;
5695        }
5696
5697        /**
5698         * Used internally by MarginLayoutParams.
5699         * @hide
5700         */
5701        LayoutParams() {
5702        }
5703
5704        /**
5705         * Extracts the layout parameters from the supplied attributes.
5706         *
5707         * @param a the style attributes to extract the parameters from
5708         * @param widthAttr the identifier of the width attribute
5709         * @param heightAttr the identifier of the height attribute
5710         */
5711        protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
5712            width = a.getLayoutDimension(widthAttr, "layout_width");
5713            height = a.getLayoutDimension(heightAttr, "layout_height");
5714        }
5715
5716        /**
5717         * Resolve layout parameters depending on the layout direction. Subclasses that care about
5718         * layoutDirection changes should override this method. The default implementation does
5719         * nothing.
5720         *
5721         * @param layoutDirection the direction of the layout
5722         *
5723         * {@link View#LAYOUT_DIRECTION_LTR}
5724         * {@link View#LAYOUT_DIRECTION_RTL}
5725         */
5726        public void resolveLayoutDirection(int layoutDirection) {
5727        }
5728
5729        /**
5730         * Returns a String representation of this set of layout parameters.
5731         *
5732         * @param output the String to prepend to the internal representation
5733         * @return a String with the following format: output +
5734         *         "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }"
5735         *
5736         * @hide
5737         */
5738        public String debug(String output) {
5739            return output + "ViewGroup.LayoutParams={ width="
5740                    + sizeToString(width) + ", height=" + sizeToString(height) + " }";
5741        }
5742
5743        /**
5744         * Use {@code canvas} to draw suitable debugging annotations for these LayoutParameters.
5745         *
5746         * @param view the view that contains these layout parameters
5747         * @param canvas the canvas on which to draw
5748         *
5749         * @hide
5750         */
5751        public void onDebugDraw(View view, Canvas canvas, Paint paint) {
5752        }
5753
5754        /**
5755         * Converts the specified size to a readable String.
5756         *
5757         * @param size the size to convert
5758         * @return a String instance representing the supplied size
5759         *
5760         * @hide
5761         */
5762        protected static String sizeToString(int size) {
5763            if (size == WRAP_CONTENT) {
5764                return "wrap-content";
5765            }
5766            if (size == MATCH_PARENT) {
5767                return "match-parent";
5768            }
5769            return String.valueOf(size);
5770        }
5771    }
5772
5773    /**
5774     * Per-child layout information for layouts that support margins.
5775     * See
5776     * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes}
5777     * for a list of all child view attributes that this class supports.
5778     */
5779    public static class MarginLayoutParams extends ViewGroup.LayoutParams {
5780        /**
5781         * The left margin in pixels of the child.
5782         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5783         * to this field.
5784         */
5785        @ViewDebug.ExportedProperty(category = "layout")
5786        public int leftMargin;
5787
5788        /**
5789         * The top margin in pixels of the child.
5790         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5791         * to this field.
5792         */
5793        @ViewDebug.ExportedProperty(category = "layout")
5794        public int topMargin;
5795
5796        /**
5797         * The right margin in pixels of the child.
5798         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5799         * to this field.
5800         */
5801        @ViewDebug.ExportedProperty(category = "layout")
5802        public int rightMargin;
5803
5804        /**
5805         * The bottom margin in pixels of the child.
5806         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5807         * to this field.
5808         */
5809        @ViewDebug.ExportedProperty(category = "layout")
5810        public int bottomMargin;
5811
5812        /**
5813         * The start margin in pixels of the child.
5814         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5815         * to this field.
5816         */
5817        @ViewDebug.ExportedProperty(category = "layout")
5818        private int startMargin = DEFAULT_RELATIVE;
5819
5820        /**
5821         * The end margin in pixels of the child.
5822         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5823         * to this field.
5824         */
5825        @ViewDebug.ExportedProperty(category = "layout")
5826        private int endMargin = DEFAULT_RELATIVE;
5827
5828        /**
5829         * The default start and end margin.
5830         * @hide
5831         */
5832        public static final int DEFAULT_RELATIVE = Integer.MIN_VALUE;
5833
5834        private int initialLeftMargin;
5835        private int initialRightMargin;
5836
5837        private static int LAYOUT_DIRECTION_UNDEFINED = -1;
5838
5839        // Layout direction undefined by default
5840        private int layoutDirection = LAYOUT_DIRECTION_UNDEFINED;
5841
5842        /**
5843         * Creates a new set of layout parameters. The values are extracted from
5844         * the supplied attributes set and context.
5845         *
5846         * @param c the application environment
5847         * @param attrs the set of attributes from which to extract the layout
5848         *              parameters' values
5849         */
5850        public MarginLayoutParams(Context c, AttributeSet attrs) {
5851            super();
5852
5853            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
5854            setBaseAttributes(a,
5855                    R.styleable.ViewGroup_MarginLayout_layout_width,
5856                    R.styleable.ViewGroup_MarginLayout_layout_height);
5857
5858            int margin = a.getDimensionPixelSize(
5859                    com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
5860            if (margin >= 0) {
5861                leftMargin = margin;
5862                topMargin = margin;
5863                rightMargin= margin;
5864                bottomMargin = margin;
5865            } else {
5866                leftMargin = a.getDimensionPixelSize(
5867                        R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0);
5868                topMargin = a.getDimensionPixelSize(
5869                        R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0);
5870                rightMargin = a.getDimensionPixelSize(
5871                        R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0);
5872                bottomMargin = a.getDimensionPixelSize(
5873                        R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0);
5874                startMargin = a.getDimensionPixelSize(
5875                        R.styleable.ViewGroup_MarginLayout_layout_marginStart, DEFAULT_RELATIVE);
5876                endMargin = a.getDimensionPixelSize(
5877                        R.styleable.ViewGroup_MarginLayout_layout_marginEnd, DEFAULT_RELATIVE);
5878            }
5879
5880            initialLeftMargin = leftMargin;
5881            initialRightMargin = rightMargin;
5882
5883            a.recycle();
5884        }
5885
5886        /**
5887         * {@inheritDoc}
5888         */
5889        public MarginLayoutParams(int width, int height) {
5890            super(width, height);
5891        }
5892
5893        /**
5894         * Copy constructor. Clones the width, height and margin values of the source.
5895         *
5896         * @param source The layout params to copy from.
5897         */
5898        public MarginLayoutParams(MarginLayoutParams source) {
5899            this.width = source.width;
5900            this.height = source.height;
5901
5902            this.leftMargin = source.leftMargin;
5903            this.topMargin = source.topMargin;
5904            this.rightMargin = source.rightMargin;
5905            this.bottomMargin = source.bottomMargin;
5906            this.startMargin = source.startMargin;
5907            this.endMargin = source.endMargin;
5908
5909            this.initialLeftMargin = source.leftMargin;
5910            this.initialRightMargin = source.rightMargin;
5911
5912            setLayoutDirection(source.layoutDirection);
5913        }
5914
5915        /**
5916         * {@inheritDoc}
5917         */
5918        public MarginLayoutParams(LayoutParams source) {
5919            super(source);
5920        }
5921
5922        /**
5923         * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs
5924         * to be done so that the new margins are taken into account. Left and right margins may be
5925         * overriden by {@link android.view.View#requestLayout()} depending on layout direction.
5926         *
5927         * @param left the left margin size
5928         * @param top the top margin size
5929         * @param right the right margin size
5930         * @param bottom the bottom margin size
5931         *
5932         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
5933         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5934         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
5935         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5936         */
5937        public void setMargins(int left, int top, int right, int bottom) {
5938            leftMargin = left;
5939            topMargin = top;
5940            rightMargin = right;
5941            bottomMargin = bottom;
5942            initialLeftMargin = left;
5943            initialRightMargin = right;
5944        }
5945
5946        /**
5947         * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()}
5948         * needs to be done so that the new relative margins are taken into account. Left and right
5949         * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout
5950         * direction.
5951         *
5952         * @param start the start margin size
5953         * @param top the top margin size
5954         * @param end the right margin size
5955         * @param bottom the bottom margin size
5956         *
5957         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5958         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5959         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5960         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5961         *
5962         * @hide
5963         */
5964        public void setMarginsRelative(int start, int top, int end, int bottom) {
5965            startMargin = start;
5966            topMargin = top;
5967            endMargin = end;
5968            bottomMargin = bottom;
5969            initialLeftMargin = 0;
5970            initialRightMargin = 0;
5971        }
5972
5973        /**
5974         * Sets the relative start margin.
5975         *
5976         * @param start the start margin size
5977         *
5978         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5979         */
5980        public void setMarginStart(int start) {
5981            startMargin = start;
5982        }
5983
5984        /**
5985         * Returns the start margin in pixels.
5986         *
5987         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5988         *
5989         * @return the start margin in pixels.
5990         */
5991        public int getMarginStart() {
5992            if (startMargin != DEFAULT_RELATIVE) return startMargin;
5993            switch(layoutDirection) {
5994                case View.LAYOUT_DIRECTION_RTL:
5995                    return rightMargin;
5996                case View.LAYOUT_DIRECTION_LTR:
5997                default:
5998                    return leftMargin;
5999            }
6000        }
6001
6002        /**
6003         * Sets the relative end margin.
6004         *
6005         * @param end the end margin size
6006         *
6007         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
6008         */
6009        public void setMarginEnd(int end) {
6010            endMargin = end;
6011        }
6012
6013        /**
6014         * Returns the end margin in pixels.
6015         *
6016         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
6017         *
6018         * @return the end margin in pixels.
6019         */
6020        public int getMarginEnd() {
6021            if (endMargin != DEFAULT_RELATIVE) return endMargin;
6022            switch(layoutDirection) {
6023                case View.LAYOUT_DIRECTION_RTL:
6024                    return leftMargin;
6025                case View.LAYOUT_DIRECTION_LTR:
6026                default:
6027                    return rightMargin;
6028            }
6029        }
6030
6031        /**
6032         * Check if margins are relative.
6033         *
6034         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
6035         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
6036         *
6037         * @return true if either marginStart or marginEnd has been set.
6038         */
6039        public boolean isMarginRelative() {
6040            return (startMargin != DEFAULT_RELATIVE) || (endMargin != DEFAULT_RELATIVE);
6041        }
6042
6043        /**
6044         * Set the layout direction
6045         * @param layoutDirection the layout direction.
6046         *        Should be either {@link View#LAYOUT_DIRECTION_LTR}
6047         *                     or {@link View#LAYOUT_DIRECTION_RTL}.
6048         */
6049        public void setLayoutDirection(int layoutDirection) {
6050            if (layoutDirection != View.LAYOUT_DIRECTION_LTR &&
6051                    layoutDirection != View.LAYOUT_DIRECTION_RTL) return;
6052            this.layoutDirection = layoutDirection;
6053        }
6054
6055        /**
6056         * Retuns the layout direction. Can be either {@link View#LAYOUT_DIRECTION_LTR} or
6057         * {@link View#LAYOUT_DIRECTION_RTL}.
6058         *
6059         * @return the layout direction.
6060         */
6061        public int getLayoutDirection() {
6062            return layoutDirection;
6063        }
6064
6065        /**
6066         * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins
6067         * may be overridden depending on layout direction.
6068         */
6069        @Override
6070        public void resolveLayoutDirection(int layoutDirection) {
6071            setLayoutDirection(layoutDirection);
6072
6073            if (!isMarginRelative()) return;
6074
6075            switch(layoutDirection) {
6076                case View.LAYOUT_DIRECTION_RTL:
6077                    leftMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : initialLeftMargin;
6078                    rightMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : initialRightMargin;
6079                    break;
6080                case View.LAYOUT_DIRECTION_LTR:
6081                default:
6082                    leftMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : initialLeftMargin;
6083                    rightMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : initialRightMargin;
6084                    break;
6085            }
6086        }
6087
6088        /**
6089         * @hide
6090         */
6091        public boolean isLayoutRtl() {
6092            return (layoutDirection == View.LAYOUT_DIRECTION_RTL);
6093        }
6094
6095        /**
6096         * @hide
6097         */
6098        @Override
6099        public void onDebugDraw(View view, Canvas canvas, Paint paint) {
6100            Insets oi = isLayoutModeOptical(view.mParent) ? view.getOpticalInsets() : Insets.NONE;
6101
6102            fillDifference(canvas,
6103                    view.getLeft()   + oi.left,
6104                    view.getTop()    + oi.top,
6105                    view.getRight()  - oi.right,
6106                    view.getBottom() - oi.bottom,
6107                    leftMargin,
6108                    topMargin,
6109                    rightMargin,
6110                    bottomMargin,
6111                    paint);
6112        }
6113    }
6114
6115    /* Describes a touched view and the ids of the pointers that it has captured.
6116     *
6117     * This code assumes that pointer ids are always in the range 0..31 such that
6118     * it can use a bitfield to track which pointer ids are present.
6119     * As it happens, the lower layers of the input dispatch pipeline also use the
6120     * same trick so the assumption should be safe here...
6121     */
6122    private static final class TouchTarget {
6123        private static final int MAX_RECYCLED = 32;
6124        private static final Object sRecycleLock = new Object();
6125        private static TouchTarget sRecycleBin;
6126        private static int sRecycledCount;
6127
6128        public static final int ALL_POINTER_IDS = -1; // all ones
6129
6130        // The touched child view.
6131        public View child;
6132
6133        // The combined bit mask of pointer ids for all pointers captured by the target.
6134        public int pointerIdBits;
6135
6136        // The next target in the target list.
6137        public TouchTarget next;
6138
6139        private TouchTarget() {
6140        }
6141
6142        public static TouchTarget obtain(View child, int pointerIdBits) {
6143            final TouchTarget target;
6144            synchronized (sRecycleLock) {
6145                if (sRecycleBin == null) {
6146                    target = new TouchTarget();
6147                } else {
6148                    target = sRecycleBin;
6149                    sRecycleBin = target.next;
6150                     sRecycledCount--;
6151                    target.next = null;
6152                }
6153            }
6154            target.child = child;
6155            target.pointerIdBits = pointerIdBits;
6156            return target;
6157        }
6158
6159        public void recycle() {
6160            synchronized (sRecycleLock) {
6161                if (sRecycledCount < MAX_RECYCLED) {
6162                    next = sRecycleBin;
6163                    sRecycleBin = this;
6164                    sRecycledCount += 1;
6165                } else {
6166                    next = null;
6167                }
6168                child = null;
6169            }
6170        }
6171    }
6172
6173    /* Describes a hovered view. */
6174    private static final class HoverTarget {
6175        private static final int MAX_RECYCLED = 32;
6176        private static final Object sRecycleLock = new Object();
6177        private static HoverTarget sRecycleBin;
6178        private static int sRecycledCount;
6179
6180        // The hovered child view.
6181        public View child;
6182
6183        // The next target in the target list.
6184        public HoverTarget next;
6185
6186        private HoverTarget() {
6187        }
6188
6189        public static HoverTarget obtain(View child) {
6190            final HoverTarget target;
6191            synchronized (sRecycleLock) {
6192                if (sRecycleBin == null) {
6193                    target = new HoverTarget();
6194                } else {
6195                    target = sRecycleBin;
6196                    sRecycleBin = target.next;
6197                     sRecycledCount--;
6198                    target.next = null;
6199                }
6200            }
6201            target.child = child;
6202            return target;
6203        }
6204
6205        public void recycle() {
6206            synchronized (sRecycleLock) {
6207                if (sRecycledCount < MAX_RECYCLED) {
6208                    next = sRecycleBin;
6209                    sRecycleBin = this;
6210                    sRecycledCount += 1;
6211                } else {
6212                    next = null;
6213                }
6214                child = null;
6215            }
6216        }
6217    }
6218
6219    /**
6220     * Pooled class that orderes the children of a ViewGroup from start
6221     * to end based on how they are laid out and the layout direction.
6222     */
6223    static class ChildListForAccessibility {
6224
6225        private static final int MAX_POOL_SIZE = 32;
6226
6227        private static final Object sPoolLock = new Object();
6228
6229        private static ChildListForAccessibility sPool;
6230
6231        private static int sPoolSize;
6232
6233        private boolean mIsPooled;
6234
6235        private ChildListForAccessibility mNext;
6236
6237        private final ArrayList<View> mChildren = new ArrayList<View>();
6238
6239        private final ArrayList<ViewLocationHolder> mHolders = new ArrayList<ViewLocationHolder>();
6240
6241        public static ChildListForAccessibility obtain(ViewGroup parent, boolean sort) {
6242            ChildListForAccessibility list = null;
6243            synchronized (sPoolLock) {
6244                if (sPool != null) {
6245                    list = sPool;
6246                    sPool = list.mNext;
6247                    list.mNext = null;
6248                    list.mIsPooled = false;
6249                    sPoolSize--;
6250                } else {
6251                    list = new ChildListForAccessibility();
6252                }
6253                list.init(parent, sort);
6254                return list;
6255            }
6256        }
6257
6258        public void recycle() {
6259            if (mIsPooled) {
6260                throw new IllegalStateException("Instance already recycled.");
6261            }
6262            clear();
6263            synchronized (sPoolLock) {
6264                if (sPoolSize < MAX_POOL_SIZE) {
6265                    mNext = sPool;
6266                    mIsPooled = true;
6267                    sPool = this;
6268                    sPoolSize++;
6269                }
6270            }
6271        }
6272
6273        public int getChildCount() {
6274            return mChildren.size();
6275        }
6276
6277        public View getChildAt(int index) {
6278            return mChildren.get(index);
6279        }
6280
6281        public int getChildIndex(View child) {
6282            return mChildren.indexOf(child);
6283        }
6284
6285        private void init(ViewGroup parent, boolean sort) {
6286            ArrayList<View> children = mChildren;
6287            final int childCount = parent.getChildCount();
6288            for (int i = 0; i < childCount; i++) {
6289                View child = parent.getChildAt(i);
6290                children.add(child);
6291            }
6292            if (sort) {
6293                ArrayList<ViewLocationHolder> holders = mHolders;
6294                for (int i = 0; i < childCount; i++) {
6295                    View child = children.get(i);
6296                    ViewLocationHolder holder = ViewLocationHolder.obtain(parent, child);
6297                    holders.add(holder);
6298                }
6299                Collections.sort(holders);
6300                for (int i = 0; i < childCount; i++) {
6301                    ViewLocationHolder holder = holders.get(i);
6302                    children.set(i, holder.mView);
6303                    holder.recycle();
6304                }
6305                holders.clear();
6306            }
6307        }
6308
6309        private void clear() {
6310            mChildren.clear();
6311        }
6312    }
6313
6314    /**
6315     * Pooled class that holds a View and its location with respect to
6316     * a specified root. This enables sorting of views based on their
6317     * coordinates without recomputing the position relative to the root
6318     * on every comparison.
6319     */
6320    static class ViewLocationHolder implements Comparable<ViewLocationHolder> {
6321
6322        private static final int MAX_POOL_SIZE = 32;
6323
6324        private static final Object sPoolLock = new Object();
6325
6326        private static ViewLocationHolder sPool;
6327
6328        private static int sPoolSize;
6329
6330        private boolean mIsPooled;
6331
6332        private ViewLocationHolder mNext;
6333
6334        private final Rect mLocation = new Rect();
6335
6336        public View mView;
6337
6338        private int mLayoutDirection;
6339
6340        public static ViewLocationHolder obtain(ViewGroup root, View view) {
6341            ViewLocationHolder holder = null;
6342            synchronized (sPoolLock) {
6343                if (sPool != null) {
6344                    holder = sPool;
6345                    sPool = holder.mNext;
6346                    holder.mNext = null;
6347                    holder.mIsPooled = false;
6348                    sPoolSize--;
6349                } else {
6350                    holder = new ViewLocationHolder();
6351                }
6352                holder.init(root, view);
6353                return holder;
6354            }
6355        }
6356
6357        public void recycle() {
6358            if (mIsPooled) {
6359                throw new IllegalStateException("Instance already recycled.");
6360            }
6361            clear();
6362            synchronized (sPoolLock) {
6363                if (sPoolSize < MAX_POOL_SIZE) {
6364                    mNext = sPool;
6365                    mIsPooled = true;
6366                    sPool = this;
6367                    sPoolSize++;
6368                }
6369            }
6370        }
6371
6372        @Override
6373        public int compareTo(ViewLocationHolder another) {
6374            // This instance is greater than an invalid argument.
6375            if (another == null) {
6376                return 1;
6377            }
6378            if (getClass() != another.getClass()) {
6379                return 1;
6380            }
6381            // First is above second.
6382            if (mLocation.bottom - another.mLocation.top <= 0) {
6383                return -1;
6384            }
6385            // First is below second.
6386            if (mLocation.top - another.mLocation.bottom >= 0) {
6387                return 1;
6388            }
6389            // LTR
6390            if (mLayoutDirection == LAYOUT_DIRECTION_LTR) {
6391                final int leftDifference = mLocation.left - another.mLocation.left;
6392                // First more to the left than second.
6393                if (leftDifference != 0) {
6394                    return leftDifference;
6395                }
6396            } else { // RTL
6397                final int rightDifference = mLocation.right - another.mLocation.right;
6398                // First more to the right than second.
6399                if (rightDifference != 0) {
6400                    return -rightDifference;
6401                }
6402            }
6403            // Break tie by top.
6404            final int topDiference = mLocation.top - another.mLocation.top;
6405            if (topDiference != 0) {
6406                return topDiference;
6407            }
6408            // Break tie by height.
6409            final int heightDiference = mLocation.height() - another.mLocation.height();
6410            if (heightDiference != 0) {
6411                return -heightDiference;
6412            }
6413            // Break tie by width.
6414            final int widthDiference = mLocation.width() - another.mLocation.width();
6415            if (widthDiference != 0) {
6416                return -widthDiference;
6417            }
6418            // Just break the tie somehow. The accessibliity ids are unique
6419            // and stable, hence this is deterministic tie breaking.
6420            return mView.getAccessibilityViewId() - another.mView.getAccessibilityViewId();
6421        }
6422
6423        private void init(ViewGroup root, View view) {
6424            Rect viewLocation = mLocation;
6425            view.getDrawingRect(viewLocation);
6426            root.offsetDescendantRectToMyCoords(view, viewLocation);
6427            mView = view;
6428            mLayoutDirection = root.getLayoutDirection();
6429        }
6430
6431        private void clear() {
6432            mView = null;
6433            mLocation.set(0, 0, 0, 0);
6434        }
6435    }
6436
6437    private static Paint getDebugPaint() {
6438        if (sDebugPaint == null) {
6439            sDebugPaint = new Paint();
6440            sDebugPaint.setAntiAlias(false);
6441        }
6442        return sDebugPaint;
6443    }
6444
6445    private void drawRect(Canvas canvas, Paint paint, int x1, int y1, int x2, int y2) {
6446        if (sDebugLines== null) {
6447            sDebugLines = new float[16];
6448        }
6449
6450        sDebugLines[0] = x1;
6451        sDebugLines[1] = y1;
6452        sDebugLines[2] = x2;
6453        sDebugLines[3] = y1;
6454
6455        sDebugLines[4] = x2;
6456        sDebugLines[5] = y1;
6457        sDebugLines[6] = x2;
6458        sDebugLines[7] = y2;
6459
6460        sDebugLines[8] = x2;
6461        sDebugLines[9] = y2;
6462        sDebugLines[10] = x1;
6463        sDebugLines[11] = y2;
6464
6465        sDebugLines[12] = x1;
6466        sDebugLines[13] = y2;
6467        sDebugLines[14] = x1;
6468        sDebugLines[15] = y1;
6469
6470        canvas.drawLines(sDebugLines, paint);
6471    }
6472}
6473