ViewGroup.java revision 8c549d6ffec427ed3f8f99eb25ffefaf55003893
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            PathEffect pathEffect = paint.getPathEffect();
2788            int len = dipsToPixels(4);
2789            paint.setPathEffect(new DashPathEffect(new float[]{len, len}, 0));
2790
2791            for (int i = 0; i < getChildCount(); i++) {
2792                View c = getChildAt(i);
2793                Insets insets = c.getOpticalInsets();
2794
2795                drawRect(canvas, paint,
2796                        c.getLeft()   + insets.left,
2797                        c.getTop()    + insets.top,
2798                        c.getRight()  - insets.right  - 1,
2799                        c.getBottom() - insets.bottom - 1);
2800            }
2801            paint.setPathEffect(pathEffect);
2802        }
2803
2804        // Draw margins
2805        {
2806            paint.setColor(Color.argb(63, 255, 0, 255));
2807            paint.setStyle(Paint.Style.FILL);
2808
2809            onDebugDrawMargins(canvas, paint);
2810        }
2811
2812        // Draw clip bounds
2813        {
2814            paint.setColor(Color.rgb(63, 127, 255));
2815            paint.setStyle(Paint.Style.FILL);
2816
2817            int lineLength = dipsToPixels(8);
2818            int lineWidth = dipsToPixels(1);
2819            for (int i = 0; i < getChildCount(); i++) {
2820                View c = getChildAt(i);
2821                drawRectCorners(canvas, c.getLeft(), c.getTop(), c.getRight(), c.getBottom(),
2822                        paint, lineLength, lineWidth);
2823            }
2824        }
2825    }
2826
2827    /**
2828     * {@inheritDoc}
2829     */
2830    @Override
2831    protected void dispatchDraw(Canvas canvas) {
2832        final int count = mChildrenCount;
2833        final View[] children = mChildren;
2834        int flags = mGroupFlags;
2835
2836        if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
2837            final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
2838
2839            final boolean buildCache = !isHardwareAccelerated();
2840            for (int i = 0; i < count; i++) {
2841                final View child = children[i];
2842                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
2843                    final LayoutParams params = child.getLayoutParams();
2844                    attachLayoutAnimationParameters(child, params, i, count);
2845                    bindLayoutAnimation(child);
2846                    if (cache) {
2847                        child.setDrawingCacheEnabled(true);
2848                        if (buildCache) {
2849                            child.buildDrawingCache(true);
2850                        }
2851                    }
2852                }
2853            }
2854
2855            final LayoutAnimationController controller = mLayoutAnimationController;
2856            if (controller.willOverlap()) {
2857                mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
2858            }
2859
2860            controller.start();
2861
2862            mGroupFlags &= ~FLAG_RUN_ANIMATION;
2863            mGroupFlags &= ~FLAG_ANIMATION_DONE;
2864
2865            if (cache) {
2866                mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
2867            }
2868
2869            if (mAnimationListener != null) {
2870                mAnimationListener.onAnimationStart(controller.getAnimation());
2871            }
2872        }
2873
2874        int saveCount = 0;
2875        final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
2876        if (clipToPadding) {
2877            saveCount = canvas.save();
2878            canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
2879                    mScrollX + mRight - mLeft - mPaddingRight,
2880                    mScrollY + mBottom - mTop - mPaddingBottom);
2881
2882        }
2883
2884        // We will draw our child's animation, let's reset the flag
2885        mPrivateFlags &= ~PFLAG_DRAW_ANIMATION;
2886        mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
2887
2888        boolean more = false;
2889        final long drawingTime = getDrawingTime();
2890
2891        if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {
2892            for (int i = 0; i < count; i++) {
2893                final View child = children[i];
2894                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
2895                    more |= drawChild(canvas, child, drawingTime);
2896                }
2897            }
2898        } else {
2899            for (int i = 0; i < count; i++) {
2900                final View child = children[getChildDrawingOrder(count, i)];
2901                if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
2902                    more |= drawChild(canvas, child, drawingTime);
2903                }
2904            }
2905        }
2906
2907        // Draw any disappearing views that have animations
2908        if (mDisappearingChildren != null) {
2909            final ArrayList<View> disappearingChildren = mDisappearingChildren;
2910            final int disappearingCount = disappearingChildren.size() - 1;
2911            // Go backwards -- we may delete as animations finish
2912            for (int i = disappearingCount; i >= 0; i--) {
2913                final View child = disappearingChildren.get(i);
2914                more |= drawChild(canvas, child, drawingTime);
2915            }
2916        }
2917
2918        if (debugDraw()) {
2919            onDebugDraw(canvas);
2920        }
2921
2922        if (clipToPadding) {
2923            canvas.restoreToCount(saveCount);
2924        }
2925
2926        // mGroupFlags might have been updated by drawChild()
2927        flags = mGroupFlags;
2928
2929        if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
2930            invalidate(true);
2931        }
2932
2933        if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
2934                mLayoutAnimationController.isDone() && !more) {
2935            // We want to erase the drawing cache and notify the listener after the
2936            // next frame is drawn because one extra invalidate() is caused by
2937            // drawChild() after the animation is over
2938            mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
2939            final Runnable end = new Runnable() {
2940               public void run() {
2941                   notifyAnimationListener();
2942               }
2943            };
2944            post(end);
2945        }
2946    }
2947
2948    /**
2949     * Returns the index of the child to draw for this iteration. Override this
2950     * if you want to change the drawing order of children. By default, it
2951     * returns i.
2952     * <p>
2953     * NOTE: In order for this method to be called, you must enable child ordering
2954     * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}.
2955     *
2956     * @param i The current iteration.
2957     * @return The index of the child to draw this iteration.
2958     *
2959     * @see #setChildrenDrawingOrderEnabled(boolean)
2960     * @see #isChildrenDrawingOrderEnabled()
2961     */
2962    protected int getChildDrawingOrder(int childCount, int i) {
2963        return i;
2964    }
2965
2966    private void notifyAnimationListener() {
2967        mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER;
2968        mGroupFlags |= FLAG_ANIMATION_DONE;
2969
2970        if (mAnimationListener != null) {
2971           final Runnable end = new Runnable() {
2972               public void run() {
2973                   mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation());
2974               }
2975           };
2976           post(end);
2977        }
2978
2979        if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
2980            mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
2981            if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
2982                setChildrenDrawingCacheEnabled(false);
2983            }
2984        }
2985
2986        invalidate(true);
2987    }
2988
2989    /**
2990     * This method is used to cause children of this ViewGroup to restore or recreate their
2991     * display lists. It is called by getDisplayList() when the parent ViewGroup does not need
2992     * to recreate its own display list, which would happen if it went through the normal
2993     * draw/dispatchDraw mechanisms.
2994     *
2995     * @hide
2996     */
2997    @Override
2998    protected void dispatchGetDisplayList() {
2999        final int count = mChildrenCount;
3000        final View[] children = mChildren;
3001        for (int i = 0; i < count; i++) {
3002            final View child = children[i];
3003            if (((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) &&
3004                    child.hasStaticLayer()) {
3005                child.mRecreateDisplayList = (child.mPrivateFlags & PFLAG_INVALIDATED)
3006                        == PFLAG_INVALIDATED;
3007                child.mPrivateFlags &= ~PFLAG_INVALIDATED;
3008                child.getDisplayList();
3009                child.mRecreateDisplayList = false;
3010            }
3011        }
3012    }
3013
3014    /**
3015     * Draw one child of this View Group. This method is responsible for getting
3016     * the canvas in the right state. This includes clipping, translating so
3017     * that the child's scrolled origin is at 0, 0, and applying any animation
3018     * transformations.
3019     *
3020     * @param canvas The canvas on which to draw the child
3021     * @param child Who to draw
3022     * @param drawingTime The time at which draw is occurring
3023     * @return True if an invalidate() was issued
3024     */
3025    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
3026        return child.draw(canvas, this, drawingTime);
3027    }
3028
3029    /**
3030     * By default, children are clipped to their bounds before drawing. This
3031     * allows view groups to override this behavior for animations, etc.
3032     *
3033     * @param clipChildren true to clip children to their bounds,
3034     *        false otherwise
3035     * @attr ref android.R.styleable#ViewGroup_clipChildren
3036     */
3037    public void setClipChildren(boolean clipChildren) {
3038        boolean previousValue = (mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN;
3039        if (clipChildren != previousValue) {
3040            setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren);
3041            for (int i = 0; i < mChildrenCount; ++i) {
3042                View child = getChildAt(i);
3043                if (child.mDisplayList != null) {
3044                    child.mDisplayList.setClipChildren(clipChildren);
3045                }
3046            }
3047        }
3048    }
3049
3050    /**
3051     * By default, children are clipped to the padding of the ViewGroup. This
3052     * allows view groups to override this behavior
3053     *
3054     * @param clipToPadding true to clip children to the padding of the
3055     *        group, false otherwise
3056     * @attr ref android.R.styleable#ViewGroup_clipToPadding
3057     */
3058    public void setClipToPadding(boolean clipToPadding) {
3059        setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
3060    }
3061
3062    /**
3063     * {@inheritDoc}
3064     */
3065    @Override
3066    public void dispatchSetSelected(boolean selected) {
3067        final View[] children = mChildren;
3068        final int count = mChildrenCount;
3069        for (int i = 0; i < count; i++) {
3070            children[i].setSelected(selected);
3071        }
3072    }
3073
3074    /**
3075     * {@inheritDoc}
3076     */
3077    @Override
3078    public void dispatchSetActivated(boolean activated) {
3079        final View[] children = mChildren;
3080        final int count = mChildrenCount;
3081        for (int i = 0; i < count; i++) {
3082            children[i].setActivated(activated);
3083        }
3084    }
3085
3086    @Override
3087    protected void dispatchSetPressed(boolean pressed) {
3088        final View[] children = mChildren;
3089        final int count = mChildrenCount;
3090        for (int i = 0; i < count; i++) {
3091            final View child = children[i];
3092            // Children that are clickable on their own should not
3093            // show a pressed state when their parent view does.
3094            // Clearing a pressed state always propagates.
3095            if (!pressed || (!child.isClickable() && !child.isLongClickable())) {
3096                child.setPressed(pressed);
3097            }
3098        }
3099    }
3100
3101    /**
3102     * When this property is set to true, this ViewGroup supports static transformations on
3103     * children; this causes
3104     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
3105     * invoked when a child is drawn.
3106     *
3107     * Any subclass overriding
3108     * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
3109     * set this property to true.
3110     *
3111     * @param enabled True to enable static transformations on children, false otherwise.
3112     *
3113     * @see #getChildStaticTransformation(View, android.view.animation.Transformation)
3114     */
3115    protected void setStaticTransformationsEnabled(boolean enabled) {
3116        setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled);
3117    }
3118
3119    /**
3120     * Sets  <code>t</code> to be the static transformation of the child, if set, returning a
3121     * boolean to indicate whether a static transform was set. The default implementation
3122     * simply returns <code>false</code>; subclasses may override this method for different
3123     * behavior. {@link #setStaticTransformationsEnabled(boolean)} must be set to true
3124     * for this method to be called.
3125     *
3126     * @param child The child view whose static transform is being requested
3127     * @param t The Transformation which will hold the result
3128     * @return true if the transformation was set, false otherwise
3129     * @see #setStaticTransformationsEnabled(boolean)
3130     */
3131    protected boolean getChildStaticTransformation(View child, Transformation t) {
3132        return false;
3133    }
3134
3135    /**
3136     * {@hide}
3137     */
3138    @Override
3139    protected View findViewTraversal(int id) {
3140        if (id == mID) {
3141            return this;
3142        }
3143
3144        final View[] where = mChildren;
3145        final int len = mChildrenCount;
3146
3147        for (int i = 0; i < len; i++) {
3148            View v = where[i];
3149
3150            if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
3151                v = v.findViewById(id);
3152
3153                if (v != null) {
3154                    return v;
3155                }
3156            }
3157        }
3158
3159        return null;
3160    }
3161
3162    /**
3163     * {@hide}
3164     */
3165    @Override
3166    protected View findViewWithTagTraversal(Object tag) {
3167        if (tag != null && tag.equals(mTag)) {
3168            return this;
3169        }
3170
3171        final View[] where = mChildren;
3172        final int len = mChildrenCount;
3173
3174        for (int i = 0; i < len; i++) {
3175            View v = where[i];
3176
3177            if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
3178                v = v.findViewWithTag(tag);
3179
3180                if (v != null) {
3181                    return v;
3182                }
3183            }
3184        }
3185
3186        return null;
3187    }
3188
3189    /**
3190     * {@hide}
3191     */
3192    @Override
3193    protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) {
3194        if (predicate.apply(this)) {
3195            return this;
3196        }
3197
3198        final View[] where = mChildren;
3199        final int len = mChildrenCount;
3200
3201        for (int i = 0; i < len; i++) {
3202            View v = where[i];
3203
3204            if (v != childToSkip && (v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
3205                v = v.findViewByPredicate(predicate);
3206
3207                if (v != null) {
3208                    return v;
3209                }
3210            }
3211        }
3212
3213        return null;
3214    }
3215
3216    /**
3217     * <p>Adds a child view. If no layout parameters are already set on the child, the
3218     * default parameters for this ViewGroup are set on the child.</p>
3219     *
3220     * <p><strong>Note:</strong> do not invoke this method from
3221     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3222     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3223     *
3224     * @param child the child view to add
3225     *
3226     * @see #generateDefaultLayoutParams()
3227     */
3228    public void addView(View child) {
3229        addView(child, -1);
3230    }
3231
3232    /**
3233     * Adds a child view. If no layout parameters are already set on the child, the
3234     * default parameters for this ViewGroup are set on the child.
3235     *
3236     * <p><strong>Note:</strong> do not invoke this method from
3237     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3238     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3239     *
3240     * @param child the child view to add
3241     * @param index the position at which to add the child
3242     *
3243     * @see #generateDefaultLayoutParams()
3244     */
3245    public void addView(View child, int index) {
3246        LayoutParams params = child.getLayoutParams();
3247        if (params == null) {
3248            params = generateDefaultLayoutParams();
3249            if (params == null) {
3250                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
3251            }
3252        }
3253        addView(child, index, params);
3254    }
3255
3256    /**
3257     * Adds a child view with this ViewGroup's default layout parameters and the
3258     * specified width and height.
3259     *
3260     * <p><strong>Note:</strong> do not invoke this method from
3261     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3262     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3263     *
3264     * @param child the child view to add
3265     */
3266    public void addView(View child, int width, int height) {
3267        final LayoutParams params = generateDefaultLayoutParams();
3268        params.width = width;
3269        params.height = height;
3270        addView(child, -1, params);
3271    }
3272
3273    /**
3274     * Adds a child view with the specified layout parameters.
3275     *
3276     * <p><strong>Note:</strong> do not invoke this method from
3277     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3278     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3279     *
3280     * @param child the child view to add
3281     * @param params the layout parameters to set on the child
3282     */
3283    public void addView(View child, LayoutParams params) {
3284        addView(child, -1, params);
3285    }
3286
3287    /**
3288     * Adds a child view with the specified layout parameters.
3289     *
3290     * <p><strong>Note:</strong> do not invoke this method from
3291     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3292     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3293     *
3294     * @param child the child view to add
3295     * @param index the position at which to add the child
3296     * @param params the layout parameters to set on the child
3297     */
3298    public void addView(View child, int index, LayoutParams params) {
3299        if (DBG) {
3300            System.out.println(this + " addView");
3301        }
3302
3303        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
3304        // therefore, we call requestLayout() on ourselves before, so that the child's request
3305        // will be blocked at our level
3306        requestLayout();
3307        invalidate(true);
3308        addViewInner(child, index, params, false);
3309    }
3310
3311    /**
3312     * {@inheritDoc}
3313     */
3314    public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
3315        if (!checkLayoutParams(params)) {
3316            throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this);
3317        }
3318        if (view.mParent != this) {
3319            throw new IllegalArgumentException("Given view not a child of " + this);
3320        }
3321        view.setLayoutParams(params);
3322    }
3323
3324    /**
3325     * {@inheritDoc}
3326     */
3327    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
3328        return  p != null;
3329    }
3330
3331    /**
3332     * Interface definition for a callback to be invoked when the hierarchy
3333     * within this view changed. The hierarchy changes whenever a child is added
3334     * to or removed from this view.
3335     */
3336    public interface OnHierarchyChangeListener {
3337        /**
3338         * Called when a new child is added to a parent view.
3339         *
3340         * @param parent the view in which a child was added
3341         * @param child the new child view added in the hierarchy
3342         */
3343        void onChildViewAdded(View parent, View child);
3344
3345        /**
3346         * Called when a child is removed from a parent view.
3347         *
3348         * @param parent the view from which the child was removed
3349         * @param child the child removed from the hierarchy
3350         */
3351        void onChildViewRemoved(View parent, View child);
3352    }
3353
3354    /**
3355     * Register a callback to be invoked when a child is added to or removed
3356     * from this view.
3357     *
3358     * @param listener the callback to invoke on hierarchy change
3359     */
3360    public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
3361        mOnHierarchyChangeListener = listener;
3362    }
3363
3364    /**
3365     * @hide
3366     */
3367    protected void onViewAdded(View child) {
3368        if (mOnHierarchyChangeListener != null) {
3369            mOnHierarchyChangeListener.onChildViewAdded(this, child);
3370        }
3371    }
3372
3373    /**
3374     * @hide
3375     */
3376    protected void onViewRemoved(View child) {
3377        if (mOnHierarchyChangeListener != null) {
3378            mOnHierarchyChangeListener.onChildViewRemoved(this, child);
3379        }
3380    }
3381
3382    /**
3383     * Adds a view during layout. This is useful if in your onLayout() method,
3384     * you need to add more views (as does the list view for example).
3385     *
3386     * If index is negative, it means put it at the end of the list.
3387     *
3388     * @param child the view to add to the group
3389     * @param index the index at which the child must be added
3390     * @param params the layout parameters to associate with the child
3391     * @return true if the child was added, false otherwise
3392     */
3393    protected boolean addViewInLayout(View child, int index, LayoutParams params) {
3394        return addViewInLayout(child, index, params, false);
3395    }
3396
3397    /**
3398     * Adds a view during layout. This is useful if in your onLayout() method,
3399     * you need to add more views (as does the list view for example).
3400     *
3401     * If index is negative, it means put it at the end of the list.
3402     *
3403     * @param child the view to add to the group
3404     * @param index the index at which the child must be added
3405     * @param params the layout parameters to associate with the child
3406     * @param preventRequestLayout if true, calling this method will not trigger a
3407     *        layout request on child
3408     * @return true if the child was added, false otherwise
3409     */
3410    protected boolean addViewInLayout(View child, int index, LayoutParams params,
3411            boolean preventRequestLayout) {
3412        child.mParent = null;
3413        addViewInner(child, index, params, preventRequestLayout);
3414        child.mPrivateFlags = (child.mPrivateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
3415        return true;
3416    }
3417
3418    /**
3419     * Prevents the specified child to be laid out during the next layout pass.
3420     *
3421     * @param child the child on which to perform the cleanup
3422     */
3423    protected void cleanupLayoutState(View child) {
3424        child.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT;
3425    }
3426
3427    private void addViewInner(View child, int index, LayoutParams params,
3428            boolean preventRequestLayout) {
3429
3430        if (mTransition != null) {
3431            // Don't prevent other add transitions from completing, but cancel remove
3432            // transitions to let them complete the process before we add to the container
3433            mTransition.cancel(LayoutTransition.DISAPPEARING);
3434        }
3435
3436        if (child.getParent() != null) {
3437            throw new IllegalStateException("The specified child already has a parent. " +
3438                    "You must call removeView() on the child's parent first.");
3439        }
3440
3441        if (mTransition != null) {
3442            mTransition.addChild(this, child);
3443        }
3444
3445        if (!checkLayoutParams(params)) {
3446            params = generateLayoutParams(params);
3447        }
3448
3449        if (preventRequestLayout) {
3450            child.mLayoutParams = params;
3451        } else {
3452            child.setLayoutParams(params);
3453        }
3454
3455        if (index < 0) {
3456            index = mChildrenCount;
3457        }
3458
3459        addInArray(child, index);
3460
3461        // tell our children
3462        if (preventRequestLayout) {
3463            child.assignParent(this);
3464        } else {
3465            child.mParent = this;
3466        }
3467
3468        if (child.hasFocus()) {
3469            requestChildFocus(child, child.findFocus());
3470        }
3471
3472        AttachInfo ai = mAttachInfo;
3473        if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) {
3474            boolean lastKeepOn = ai.mKeepScreenOn;
3475            ai.mKeepScreenOn = false;
3476            child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
3477            if (ai.mKeepScreenOn) {
3478                needGlobalAttributesUpdate(true);
3479            }
3480            ai.mKeepScreenOn = lastKeepOn;
3481        }
3482
3483        onViewAdded(child);
3484
3485        if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
3486            mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
3487        }
3488
3489        if (child.hasTransientState()) {
3490            childHasTransientStateChanged(child, true);
3491        }
3492
3493        if (child.isLayoutDirectionInherited()) {
3494            child.resetResolvedLayoutDirection();
3495            child.resolveRtlProperties();
3496        }
3497    }
3498
3499    private void addInArray(View child, int index) {
3500        View[] children = mChildren;
3501        final int count = mChildrenCount;
3502        final int size = children.length;
3503        if (index == count) {
3504            if (size == count) {
3505                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3506                System.arraycopy(children, 0, mChildren, 0, size);
3507                children = mChildren;
3508            }
3509            children[mChildrenCount++] = child;
3510        } else if (index < count) {
3511            if (size == count) {
3512                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
3513                System.arraycopy(children, 0, mChildren, 0, index);
3514                System.arraycopy(children, index, mChildren, index + 1, count - index);
3515                children = mChildren;
3516            } else {
3517                System.arraycopy(children, index, children, index + 1, count - index);
3518            }
3519            children[index] = child;
3520            mChildrenCount++;
3521            if (mLastTouchDownIndex >= index) {
3522                mLastTouchDownIndex++;
3523            }
3524        } else {
3525            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
3526        }
3527    }
3528
3529    // This method also sets the child's mParent to null
3530    private void removeFromArray(int index) {
3531        final View[] children = mChildren;
3532        if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
3533            children[index].mParent = null;
3534        }
3535        final int count = mChildrenCount;
3536        if (index == count - 1) {
3537            children[--mChildrenCount] = null;
3538        } else if (index >= 0 && index < count) {
3539            System.arraycopy(children, index + 1, children, index, count - index - 1);
3540            children[--mChildrenCount] = null;
3541        } else {
3542            throw new IndexOutOfBoundsException();
3543        }
3544        if (mLastTouchDownIndex == index) {
3545            mLastTouchDownTime = 0;
3546            mLastTouchDownIndex = -1;
3547        } else if (mLastTouchDownIndex > index) {
3548            mLastTouchDownIndex--;
3549        }
3550    }
3551
3552    // This method also sets the children's mParent to null
3553    private void removeFromArray(int start, int count) {
3554        final View[] children = mChildren;
3555        final int childrenCount = mChildrenCount;
3556
3557        start = Math.max(0, start);
3558        final int end = Math.min(childrenCount, start + count);
3559
3560        if (start == end) {
3561            return;
3562        }
3563
3564        if (end == childrenCount) {
3565            for (int i = start; i < end; i++) {
3566                children[i].mParent = null;
3567                children[i] = null;
3568            }
3569        } else {
3570            for (int i = start; i < end; i++) {
3571                children[i].mParent = null;
3572            }
3573
3574            // Since we're looping above, we might as well do the copy, but is arraycopy()
3575            // faster than the extra 2 bounds checks we would do in the loop?
3576            System.arraycopy(children, end, children, start, childrenCount - end);
3577
3578            for (int i = childrenCount - (end - start); i < childrenCount; i++) {
3579                children[i] = null;
3580            }
3581        }
3582
3583        mChildrenCount -= (end - start);
3584    }
3585
3586    private void bindLayoutAnimation(View child) {
3587        Animation a = mLayoutAnimationController.getAnimationForView(child);
3588        child.setAnimation(a);
3589    }
3590
3591    /**
3592     * Subclasses should override this method to set layout animation
3593     * parameters on the supplied child.
3594     *
3595     * @param child the child to associate with animation parameters
3596     * @param params the child's layout parameters which hold the animation
3597     *        parameters
3598     * @param index the index of the child in the view group
3599     * @param count the number of children in the view group
3600     */
3601    protected void attachLayoutAnimationParameters(View child,
3602            LayoutParams params, int index, int count) {
3603        LayoutAnimationController.AnimationParameters animationParams =
3604                    params.layoutAnimationParameters;
3605        if (animationParams == null) {
3606            animationParams = new LayoutAnimationController.AnimationParameters();
3607            params.layoutAnimationParameters = animationParams;
3608        }
3609
3610        animationParams.count = count;
3611        animationParams.index = index;
3612    }
3613
3614    /**
3615     * {@inheritDoc}
3616     *
3617     * <p><strong>Note:</strong> do not invoke this method from
3618     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3619     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3620     */
3621    public void removeView(View view) {
3622        removeViewInternal(view);
3623        requestLayout();
3624        invalidate(true);
3625    }
3626
3627    /**
3628     * Removes a view during layout. This is useful if in your onLayout() method,
3629     * you need to remove more views.
3630     *
3631     * <p><strong>Note:</strong> do not invoke this method from
3632     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3633     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3634     *
3635     * @param view the view to remove from the group
3636     */
3637    public void removeViewInLayout(View view) {
3638        removeViewInternal(view);
3639    }
3640
3641    /**
3642     * Removes a range of views during layout. This is useful if in your onLayout() method,
3643     * you need to remove more views.
3644     *
3645     * <p><strong>Note:</strong> do not invoke this method from
3646     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3647     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3648     *
3649     * @param start the index of the first view to remove from the group
3650     * @param count the number of views to remove from the group
3651     */
3652    public void removeViewsInLayout(int start, int count) {
3653        removeViewsInternal(start, count);
3654    }
3655
3656    /**
3657     * Removes the view at the specified position in the group.
3658     *
3659     * <p><strong>Note:</strong> do not invoke this method from
3660     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3661     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3662     *
3663     * @param index the position in the group of the view to remove
3664     */
3665    public void removeViewAt(int index) {
3666        removeViewInternal(index, getChildAt(index));
3667        requestLayout();
3668        invalidate(true);
3669    }
3670
3671    /**
3672     * Removes the specified range of views from the group.
3673     *
3674     * <p><strong>Note:</strong> do not invoke this method from
3675     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3676     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3677     *
3678     * @param start the first position in the group of the range of views to remove
3679     * @param count the number of views to remove
3680     */
3681    public void removeViews(int start, int count) {
3682        removeViewsInternal(start, count);
3683        requestLayout();
3684        invalidate(true);
3685    }
3686
3687    private void removeViewInternal(View view) {
3688        final int index = indexOfChild(view);
3689        if (index >= 0) {
3690            removeViewInternal(index, view);
3691        }
3692    }
3693
3694    private void removeViewInternal(int index, View view) {
3695
3696        if (mTransition != null) {
3697            mTransition.removeChild(this, view);
3698        }
3699
3700        boolean clearChildFocus = false;
3701        if (view == mFocused) {
3702            view.unFocus();
3703            clearChildFocus = true;
3704        }
3705
3706        view.clearAccessibilityFocus();
3707
3708        cancelTouchTarget(view);
3709        cancelHoverTarget(view);
3710
3711        if (view.getAnimation() != null ||
3712                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3713            addDisappearingView(view);
3714        } else if (view.mAttachInfo != null) {
3715           view.dispatchDetachedFromWindow();
3716        }
3717
3718        if (view.hasTransientState()) {
3719            childHasTransientStateChanged(view, false);
3720        }
3721
3722        view.resetResolvedLayoutDirection();
3723
3724        onViewRemoved(view);
3725
3726        needGlobalAttributesUpdate(false);
3727
3728        removeFromArray(index);
3729
3730        if (clearChildFocus) {
3731            clearChildFocus(view);
3732            ensureInputFocusOnFirstFocusable();
3733        }
3734
3735        if (view.isAccessibilityFocused()) {
3736            view.clearAccessibilityFocus();
3737        }
3738    }
3739
3740    /**
3741     * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3742     * not null, changes in layout which occur because of children being added to or removed from
3743     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3744     * object. By default, the transition object is null (so layout changes are not animated).
3745     *
3746     * @param transition The LayoutTransition object that will animated changes in layout. A value
3747     * of <code>null</code> means no transition will run on layout changes.
3748     * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
3749     */
3750    public void setLayoutTransition(LayoutTransition transition) {
3751        if (mTransition != null) {
3752            mTransition.removeTransitionListener(mLayoutTransitionListener);
3753        }
3754        mTransition = transition;
3755        if (mTransition != null) {
3756            mTransition.addTransitionListener(mLayoutTransitionListener);
3757        }
3758    }
3759
3760    /**
3761     * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
3762     * not null, changes in layout which occur because of children being added to or removed from
3763     * the ViewGroup will be animated according to the animations defined in that LayoutTransition
3764     * object. By default, the transition object is null (so layout changes are not animated).
3765     *
3766     * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
3767     * A value of <code>null</code> means no transition will run on layout changes.
3768     */
3769    public LayoutTransition getLayoutTransition() {
3770        return mTransition;
3771    }
3772
3773    private void removeViewsInternal(int start, int count) {
3774        final View focused = mFocused;
3775        final boolean detach = mAttachInfo != null;
3776        View clearChildFocus = null;
3777
3778        final View[] children = mChildren;
3779        final int end = start + count;
3780
3781        for (int i = start; i < end; i++) {
3782            final View view = children[i];
3783
3784            if (mTransition != null) {
3785                mTransition.removeChild(this, view);
3786            }
3787
3788            if (view == focused) {
3789                view.unFocus();
3790                clearChildFocus = view;
3791            }
3792
3793            view.clearAccessibilityFocus();
3794
3795            cancelTouchTarget(view);
3796            cancelHoverTarget(view);
3797
3798            if (view.getAnimation() != null ||
3799                (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3800                addDisappearingView(view);
3801            } else if (detach) {
3802               view.dispatchDetachedFromWindow();
3803            }
3804
3805            if (view.hasTransientState()) {
3806                childHasTransientStateChanged(view, false);
3807            }
3808
3809            needGlobalAttributesUpdate(false);
3810
3811            onViewRemoved(view);
3812        }
3813
3814        removeFromArray(start, count);
3815
3816        if (clearChildFocus != null) {
3817            clearChildFocus(clearChildFocus);
3818            ensureInputFocusOnFirstFocusable();
3819        }
3820    }
3821
3822    /**
3823     * Call this method to remove all child views from the
3824     * ViewGroup.
3825     *
3826     * <p><strong>Note:</strong> do not invoke this method from
3827     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3828     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3829     */
3830    public void removeAllViews() {
3831        removeAllViewsInLayout();
3832        requestLayout();
3833        invalidate(true);
3834    }
3835
3836    /**
3837     * Called by a ViewGroup subclass to remove child views from itself,
3838     * when it must first know its size on screen before it can calculate how many
3839     * child views it will render. An example is a Gallery or a ListView, which
3840     * may "have" 50 children, but actually only render the number of children
3841     * that can currently fit inside the object on screen. Do not call
3842     * this method unless you are extending ViewGroup and understand the
3843     * view measuring and layout pipeline.
3844     *
3845     * <p><strong>Note:</strong> do not invoke this method from
3846     * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)},
3847     * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p>
3848     */
3849    public void removeAllViewsInLayout() {
3850        final int count = mChildrenCount;
3851        if (count <= 0) {
3852            return;
3853        }
3854
3855        final View[] children = mChildren;
3856        mChildrenCount = 0;
3857
3858        final View focused = mFocused;
3859        final boolean detach = mAttachInfo != null;
3860        View clearChildFocus = null;
3861
3862        needGlobalAttributesUpdate(false);
3863
3864        for (int i = count - 1; i >= 0; i--) {
3865            final View view = children[i];
3866
3867            if (mTransition != null) {
3868                mTransition.removeChild(this, view);
3869            }
3870
3871            if (view == focused) {
3872                view.unFocus();
3873                clearChildFocus = view;
3874            }
3875
3876            view.clearAccessibilityFocus();
3877
3878            cancelTouchTarget(view);
3879            cancelHoverTarget(view);
3880
3881            if (view.getAnimation() != null ||
3882                    (mTransitioningViews != null && mTransitioningViews.contains(view))) {
3883                addDisappearingView(view);
3884            } else if (detach) {
3885               view.dispatchDetachedFromWindow();
3886            }
3887
3888            if (view.hasTransientState()) {
3889                childHasTransientStateChanged(view, false);
3890            }
3891
3892            onViewRemoved(view);
3893
3894            view.mParent = null;
3895            children[i] = null;
3896        }
3897
3898        if (clearChildFocus != null) {
3899            clearChildFocus(clearChildFocus);
3900            ensureInputFocusOnFirstFocusable();
3901        }
3902    }
3903
3904    /**
3905     * Finishes the removal of a detached view. This method will dispatch the detached from
3906     * window event and notify the hierarchy change listener.
3907     * <p>
3908     * This method is intended to be lightweight and makes no assumptions about whether the
3909     * parent or child should be redrawn. Proper use of this method will include also making
3910     * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls.
3911     * For example, callers can {@link #post(Runnable) post} a {@link Runnable}
3912     * which performs a {@link #requestLayout()} on the next frame, after all detach/remove
3913     * calls are finished, causing layout to be run prior to redrawing the view hierarchy.
3914     *
3915     * @param child the child to be definitely removed from the view hierarchy
3916     * @param animate if true and the view has an animation, the view is placed in the
3917     *                disappearing views list, otherwise, it is detached from the window
3918     *
3919     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
3920     * @see #detachAllViewsFromParent()
3921     * @see #detachViewFromParent(View)
3922     * @see #detachViewFromParent(int)
3923     */
3924    protected void removeDetachedView(View child, boolean animate) {
3925        if (mTransition != null) {
3926            mTransition.removeChild(this, child);
3927        }
3928
3929        if (child == mFocused) {
3930            child.clearFocus();
3931        }
3932
3933        child.clearAccessibilityFocus();
3934
3935        cancelTouchTarget(child);
3936        cancelHoverTarget(child);
3937
3938        if ((animate && child.getAnimation() != null) ||
3939                (mTransitioningViews != null && mTransitioningViews.contains(child))) {
3940            addDisappearingView(child);
3941        } else if (child.mAttachInfo != null) {
3942            child.dispatchDetachedFromWindow();
3943        }
3944
3945        if (child.hasTransientState()) {
3946            childHasTransientStateChanged(child, false);
3947        }
3948
3949        onViewRemoved(child);
3950    }
3951
3952    /**
3953     * Attaches a view to this view group. Attaching a view assigns this group as the parent,
3954     * sets the layout parameters and puts the view in the list of children so that
3955     * it can be retrieved by calling {@link #getChildAt(int)}.
3956     * <p>
3957     * This method is intended to be lightweight and makes no assumptions about whether the
3958     * parent or child should be redrawn. Proper use of this method will include also making
3959     * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls.
3960     * For example, callers can {@link #post(Runnable) post} a {@link Runnable}
3961     * which performs a {@link #requestLayout()} on the next frame, after all detach/attach
3962     * calls are finished, causing layout to be run prior to redrawing the view hierarchy.
3963     * <p>
3964     * This method should be called only for views which were detached from their parent.
3965     *
3966     * @param child the child to attach
3967     * @param index the index at which the child should be attached
3968     * @param params the layout parameters of the child
3969     *
3970     * @see #removeDetachedView(View, boolean)
3971     * @see #detachAllViewsFromParent()
3972     * @see #detachViewFromParent(View)
3973     * @see #detachViewFromParent(int)
3974     */
3975    protected void attachViewToParent(View child, int index, LayoutParams params) {
3976        child.mLayoutParams = params;
3977
3978        if (index < 0) {
3979            index = mChildrenCount;
3980        }
3981
3982        addInArray(child, index);
3983
3984        child.mParent = this;
3985        child.mPrivateFlags = (child.mPrivateFlags & ~PFLAG_DIRTY_MASK
3986                        & ~PFLAG_DRAWING_CACHE_VALID)
3987                | PFLAG_DRAWN | PFLAG_INVALIDATED;
3988        this.mPrivateFlags |= PFLAG_INVALIDATED;
3989
3990        if (child.hasFocus()) {
3991            requestChildFocus(child, child.findFocus());
3992        }
3993    }
3994
3995    /**
3996     * Detaches a view from its parent. Detaching a view should be followed
3997     * either by a call to
3998     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
3999     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4000     * temporary; reattachment or removal should happen within the same drawing cycle as
4001     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4002     * call to {@link #getChildAt(int)}.
4003     *
4004     * @param child the child to detach
4005     *
4006     * @see #detachViewFromParent(int)
4007     * @see #detachViewsFromParent(int, int)
4008     * @see #detachAllViewsFromParent()
4009     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4010     * @see #removeDetachedView(View, boolean)
4011     */
4012    protected void detachViewFromParent(View child) {
4013        removeFromArray(indexOfChild(child));
4014    }
4015
4016    /**
4017     * Detaches a view from its parent. Detaching a view should be followed
4018     * either by a call to
4019     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4020     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4021     * temporary; reattachment or removal should happen within the same drawing cycle as
4022     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4023     * call to {@link #getChildAt(int)}.
4024     *
4025     * @param index the index of the child to detach
4026     *
4027     * @see #detachViewFromParent(View)
4028     * @see #detachAllViewsFromParent()
4029     * @see #detachViewsFromParent(int, int)
4030     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4031     * @see #removeDetachedView(View, boolean)
4032     */
4033    protected void detachViewFromParent(int index) {
4034        removeFromArray(index);
4035    }
4036
4037    /**
4038     * Detaches a range of views from their parents. Detaching a view should be followed
4039     * either by a call to
4040     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4041     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4042     * temporary; reattachment or removal should happen within the same drawing cycle as
4043     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4044     * call to {@link #getChildAt(int)}.
4045     *
4046     * @param start the first index of the childrend range to detach
4047     * @param count the number of children to detach
4048     *
4049     * @see #detachViewFromParent(View)
4050     * @see #detachViewFromParent(int)
4051     * @see #detachAllViewsFromParent()
4052     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4053     * @see #removeDetachedView(View, boolean)
4054     */
4055    protected void detachViewsFromParent(int start, int count) {
4056        removeFromArray(start, count);
4057    }
4058
4059    /**
4060     * Detaches all views from the parent. Detaching a view should be followed
4061     * either by a call to
4062     * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
4063     * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be
4064     * temporary; reattachment or removal should happen within the same drawing cycle as
4065     * detachment. When a view is detached, its parent is null and cannot be retrieved by a
4066     * call to {@link #getChildAt(int)}.
4067     *
4068     * @see #detachViewFromParent(View)
4069     * @see #detachViewFromParent(int)
4070     * @see #detachViewsFromParent(int, int)
4071     * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
4072     * @see #removeDetachedView(View, boolean)
4073     */
4074    protected void detachAllViewsFromParent() {
4075        final int count = mChildrenCount;
4076        if (count <= 0) {
4077            return;
4078        }
4079
4080        final View[] children = mChildren;
4081        mChildrenCount = 0;
4082
4083        for (int i = count - 1; i >= 0; i--) {
4084            children[i].mParent = null;
4085            children[i] = null;
4086        }
4087    }
4088
4089    /**
4090     * Don't call or override this method. It is used for the implementation of
4091     * the view hierarchy.
4092     */
4093    public final void invalidateChild(View child, final Rect dirty) {
4094        ViewParent parent = this;
4095
4096        final AttachInfo attachInfo = mAttachInfo;
4097        if (attachInfo != null) {
4098            // If the child is drawing an animation, we want to copy this flag onto
4099            // ourselves and the parent to make sure the invalidate request goes
4100            // through
4101            final boolean drawAnimation = (child.mPrivateFlags & PFLAG_DRAW_ANIMATION)
4102                    == PFLAG_DRAW_ANIMATION;
4103
4104            // Check whether the child that requests the invalidate is fully opaque
4105            // Views being animated or transformed are not considered opaque because we may
4106            // be invalidating their old position and need the parent to paint behind them.
4107            Matrix childMatrix = child.getMatrix();
4108            final boolean isOpaque = child.isOpaque() && !drawAnimation &&
4109                    child.getAnimation() == null && childMatrix.isIdentity();
4110            // Mark the child as dirty, using the appropriate flag
4111            // Make sure we do not set both flags at the same time
4112            int opaqueFlag = isOpaque ? PFLAG_DIRTY_OPAQUE : PFLAG_DIRTY;
4113
4114            if (child.mLayerType != LAYER_TYPE_NONE) {
4115                mPrivateFlags |= PFLAG_INVALIDATED;
4116                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
4117                child.mLocalDirtyRect.union(dirty);
4118            }
4119
4120            final int[] location = attachInfo.mInvalidateChildLocation;
4121            location[CHILD_LEFT_INDEX] = child.mLeft;
4122            location[CHILD_TOP_INDEX] = child.mTop;
4123            if (!childMatrix.isIdentity() ||
4124                    (mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
4125                RectF boundingRect = attachInfo.mTmpTransformRect;
4126                boundingRect.set(dirty);
4127                Matrix transformMatrix;
4128                if ((mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) {
4129                    Transformation t = attachInfo.mTmpTransformation;
4130                    boolean transformed = getChildStaticTransformation(child, t);
4131                    if (transformed) {
4132                        transformMatrix = attachInfo.mTmpMatrix;
4133                        transformMatrix.set(t.getMatrix());
4134                        if (!childMatrix.isIdentity()) {
4135                            transformMatrix.preConcat(childMatrix);
4136                        }
4137                    } else {
4138                        transformMatrix = childMatrix;
4139                    }
4140                } else {
4141                    transformMatrix = childMatrix;
4142                }
4143                transformMatrix.mapRect(boundingRect);
4144                dirty.set((int) (boundingRect.left - 0.5f),
4145                        (int) (boundingRect.top - 0.5f),
4146                        (int) (boundingRect.right + 0.5f),
4147                        (int) (boundingRect.bottom + 0.5f));
4148            }
4149
4150            do {
4151                View view = null;
4152                if (parent instanceof View) {
4153                    view = (View) parent;
4154                }
4155
4156                if (drawAnimation) {
4157                    if (view != null) {
4158                        view.mPrivateFlags |= PFLAG_DRAW_ANIMATION;
4159                    } else if (parent instanceof ViewRootImpl) {
4160                        ((ViewRootImpl) parent).mIsAnimating = true;
4161                    }
4162                }
4163
4164                // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
4165                // flag coming from the child that initiated the invalidate
4166                if (view != null) {
4167                    if ((view.mViewFlags & FADING_EDGE_MASK) != 0 &&
4168                            view.getSolidColor() == 0) {
4169                        opaqueFlag = PFLAG_DIRTY;
4170                    }
4171                    if ((view.mPrivateFlags & PFLAG_DIRTY_MASK) != PFLAG_DIRTY) {
4172                        view.mPrivateFlags = (view.mPrivateFlags & ~PFLAG_DIRTY_MASK) | opaqueFlag;
4173                    }
4174                }
4175
4176                parent = parent.invalidateChildInParent(location, dirty);
4177                if (view != null) {
4178                    // Account for transform on current parent
4179                    Matrix m = view.getMatrix();
4180                    if (!m.isIdentity()) {
4181                        RectF boundingRect = attachInfo.mTmpTransformRect;
4182                        boundingRect.set(dirty);
4183                        m.mapRect(boundingRect);
4184                        dirty.set((int) (boundingRect.left - 0.5f),
4185                                (int) (boundingRect.top - 0.5f),
4186                                (int) (boundingRect.right + 0.5f),
4187                                (int) (boundingRect.bottom + 0.5f));
4188                    }
4189                }
4190            } while (parent != null);
4191        }
4192    }
4193
4194    /**
4195     * Don't call or override this method. It is used for the implementation of
4196     * the view hierarchy.
4197     *
4198     * This implementation returns null if this ViewGroup does not have a parent,
4199     * if this ViewGroup is already fully invalidated or if the dirty rectangle
4200     * does not intersect with this ViewGroup's bounds.
4201     */
4202    public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
4203        if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN ||
4204                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) {
4205            if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
4206                        FLAG_OPTIMIZE_INVALIDATE) {
4207                dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
4208                        location[CHILD_TOP_INDEX] - mScrollY);
4209
4210                final int left = mLeft;
4211                final int top = mTop;
4212
4213                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
4214                    if (!dirty.intersect(0, 0, mRight - left, mBottom - top)) {
4215                        dirty.setEmpty();
4216                    }
4217                }
4218                mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID;
4219
4220                location[CHILD_LEFT_INDEX] = left;
4221                location[CHILD_TOP_INDEX] = top;
4222
4223                if (mLayerType != LAYER_TYPE_NONE) {
4224                    mPrivateFlags |= PFLAG_INVALIDATED;
4225                    mLocalDirtyRect.union(dirty);
4226                }
4227
4228                return mParent;
4229
4230            } else {
4231                mPrivateFlags &= ~PFLAG_DRAWN & ~PFLAG_DRAWING_CACHE_VALID;
4232
4233                location[CHILD_LEFT_INDEX] = mLeft;
4234                location[CHILD_TOP_INDEX] = mTop;
4235                if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
4236                    dirty.set(0, 0, mRight - mLeft, mBottom - mTop);
4237                } else {
4238                    // in case the dirty rect extends outside the bounds of this container
4239                    dirty.union(0, 0, mRight - mLeft, mBottom - mTop);
4240                }
4241
4242                if (mLayerType != LAYER_TYPE_NONE) {
4243                    mPrivateFlags |= PFLAG_INVALIDATED;
4244                    mLocalDirtyRect.union(dirty);
4245                }
4246
4247                return mParent;
4248            }
4249        }
4250
4251        return null;
4252    }
4253
4254    /**
4255     * Quick invalidation method called by View.invalidateViewProperty. This doesn't set the
4256     * DRAWN flags and doesn't handle the Animation logic that the default invalidation methods
4257     * do; all we want to do here is schedule a traversal with the appropriate dirty rect.
4258     *
4259     * @hide
4260     */
4261    public void invalidateChildFast(View child, final Rect dirty) {
4262        ViewParent parent = this;
4263
4264        final AttachInfo attachInfo = mAttachInfo;
4265        if (attachInfo != null) {
4266            if (child.mLayerType != LAYER_TYPE_NONE) {
4267                child.mLocalDirtyRect.union(dirty);
4268            }
4269
4270            int left = child.mLeft;
4271            int top = child.mTop;
4272            if (!child.getMatrix().isIdentity()) {
4273                child.transformRect(dirty);
4274            }
4275
4276            do {
4277                if (parent instanceof ViewGroup) {
4278                    ViewGroup parentVG = (ViewGroup) parent;
4279                    if (parentVG.mLayerType != LAYER_TYPE_NONE) {
4280                        // Layered parents should be recreated, not just re-issued
4281                        parentVG.invalidate();
4282                        parent = null;
4283                    } else {
4284                        parent = parentVG.invalidateChildInParentFast(left, top, dirty);
4285                        left = parentVG.mLeft;
4286                        top = parentVG.mTop;
4287                    }
4288                } else {
4289                    // Reached the top; this calls into the usual invalidate method in
4290                    // ViewRootImpl, which schedules a traversal
4291                    final int[] location = attachInfo.mInvalidateChildLocation;
4292                    location[0] = left;
4293                    location[1] = top;
4294                    parent = parent.invalidateChildInParent(location, dirty);
4295                }
4296            } while (parent != null);
4297        }
4298    }
4299
4300    /**
4301     * Quick invalidation method that simply transforms the dirty rect into the parent's
4302     * coordinate system, pruning the invalidation if the parent has already been invalidated.
4303     */
4304    private ViewParent invalidateChildInParentFast(int left, int top, final Rect dirty) {
4305        if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN ||
4306                (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) {
4307            dirty.offset(left - mScrollX, top - mScrollY);
4308
4309            if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0 ||
4310                    dirty.intersect(0, 0, mRight - mLeft, mBottom - mTop)) {
4311
4312                if (mLayerType != LAYER_TYPE_NONE) {
4313                    mLocalDirtyRect.union(dirty);
4314                }
4315                if (!getMatrix().isIdentity()) {
4316                    transformRect(dirty);
4317                }
4318
4319                return mParent;
4320            }
4321        }
4322
4323        return null;
4324    }
4325
4326    /**
4327     * Offset a rectangle that is in a descendant's coordinate
4328     * space into our coordinate space.
4329     * @param descendant A descendant of this view
4330     * @param rect A rectangle defined in descendant's coordinate space.
4331     */
4332    public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) {
4333        offsetRectBetweenParentAndChild(descendant, rect, true, false);
4334    }
4335
4336    /**
4337     * Offset a rectangle that is in our coordinate space into an ancestor's
4338     * coordinate space.
4339     * @param descendant A descendant of this view
4340     * @param rect A rectangle defined in descendant's coordinate space.
4341     */
4342    public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) {
4343        offsetRectBetweenParentAndChild(descendant, rect, false, false);
4344    }
4345
4346    /**
4347     * Helper method that offsets a rect either from parent to descendant or
4348     * descendant to parent.
4349     */
4350    void offsetRectBetweenParentAndChild(View descendant, Rect rect,
4351            boolean offsetFromChildToParent, boolean clipToBounds) {
4352
4353        // already in the same coord system :)
4354        if (descendant == this) {
4355            return;
4356        }
4357
4358        ViewParent theParent = descendant.mParent;
4359
4360        // search and offset up to the parent
4361        while ((theParent != null)
4362                && (theParent instanceof View)
4363                && (theParent != this)) {
4364
4365            if (offsetFromChildToParent) {
4366                rect.offset(descendant.mLeft - descendant.mScrollX,
4367                        descendant.mTop - descendant.mScrollY);
4368                if (clipToBounds) {
4369                    View p = (View) theParent;
4370                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4371                }
4372            } else {
4373                if (clipToBounds) {
4374                    View p = (View) theParent;
4375                    rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
4376                }
4377                rect.offset(descendant.mScrollX - descendant.mLeft,
4378                        descendant.mScrollY - descendant.mTop);
4379            }
4380
4381            descendant = (View) theParent;
4382            theParent = descendant.mParent;
4383        }
4384
4385        // now that we are up to this view, need to offset one more time
4386        // to get into our coordinate space
4387        if (theParent == this) {
4388            if (offsetFromChildToParent) {
4389                rect.offset(descendant.mLeft - descendant.mScrollX,
4390                        descendant.mTop - descendant.mScrollY);
4391            } else {
4392                rect.offset(descendant.mScrollX - descendant.mLeft,
4393                        descendant.mScrollY - descendant.mTop);
4394            }
4395        } else {
4396            throw new IllegalArgumentException("parameter must be a descendant of this view");
4397        }
4398    }
4399
4400    /**
4401     * Offset the vertical location of all children of this view by the specified number of pixels.
4402     *
4403     * @param offset the number of pixels to offset
4404     *
4405     * @hide
4406     */
4407    public void offsetChildrenTopAndBottom(int offset) {
4408        final int count = mChildrenCount;
4409        final View[] children = mChildren;
4410
4411        for (int i = 0; i < count; i++) {
4412            final View v = children[i];
4413            v.mTop += offset;
4414            v.mBottom += offset;
4415            if (v.mDisplayList != null) {
4416                v.mDisplayList.offsetTopBottom(offset);
4417                invalidateViewProperty(false, false);
4418            }
4419        }
4420    }
4421
4422    /**
4423     * {@inheritDoc}
4424     */
4425    public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
4426        // It doesn't make a whole lot of sense to call this on a view that isn't attached,
4427        // but for some simple tests it can be useful. If we don't have attach info this
4428        // will allocate memory.
4429        final RectF rect = mAttachInfo != null ? mAttachInfo.mTmpTransformRect : new RectF();
4430        rect.set(r);
4431
4432        if (!child.hasIdentityMatrix()) {
4433           child.getMatrix().mapRect(rect);
4434        }
4435
4436        int dx = child.mLeft - mScrollX;
4437        int dy = child.mTop - mScrollY;
4438
4439        rect.offset(dx, dy);
4440
4441        if (offset != null) {
4442            if (!child.hasIdentityMatrix()) {
4443                float[] position = mAttachInfo != null ? mAttachInfo.mTmpTransformLocation
4444                        : new float[2];
4445                position[0] = offset.x;
4446                position[1] = offset.y;
4447                child.getMatrix().mapPoints(position);
4448                offset.x = (int) (position[0] + 0.5f);
4449                offset.y = (int) (position[1] + 0.5f);
4450            }
4451            offset.x += dx;
4452            offset.y += dy;
4453        }
4454
4455        if (rect.intersect(0, 0, mRight - mLeft, mBottom - mTop)) {
4456            if (mParent == null) return true;
4457            r.set((int) (rect.left + 0.5f), (int) (rect.top + 0.5f),
4458                    (int) (rect.right + 0.5f), (int) (rect.bottom + 0.5f));
4459            return mParent.getChildVisibleRect(this, r, offset);
4460        }
4461
4462        return false;
4463    }
4464
4465    /**
4466     * {@inheritDoc}
4467     */
4468    @Override
4469    public final void layout(int l, int t, int r, int b) {
4470        if (mTransition == null || !mTransition.isChangingLayout()) {
4471            if (mTransition != null) {
4472                mTransition.layoutChange(this);
4473            }
4474            super.layout(l, t, r, b);
4475        } else {
4476            // record the fact that we noop'd it; request layout when transition finishes
4477            mLayoutSuppressed = true;
4478        }
4479    }
4480
4481    /**
4482     * {@inheritDoc}
4483     */
4484    @Override
4485    protected abstract void onLayout(boolean changed,
4486            int l, int t, int r, int b);
4487
4488    /**
4489     * Indicates whether the view group has the ability to animate its children
4490     * after the first layout.
4491     *
4492     * @return true if the children can be animated, false otherwise
4493     */
4494    protected boolean canAnimate() {
4495        return mLayoutAnimationController != null;
4496    }
4497
4498    /**
4499     * Runs the layout animation. Calling this method triggers a relayout of
4500     * this view group.
4501     */
4502    public void startLayoutAnimation() {
4503        if (mLayoutAnimationController != null) {
4504            mGroupFlags |= FLAG_RUN_ANIMATION;
4505            requestLayout();
4506        }
4507    }
4508
4509    /**
4510     * Schedules the layout animation to be played after the next layout pass
4511     * of this view group. This can be used to restart the layout animation
4512     * when the content of the view group changes or when the activity is
4513     * paused and resumed.
4514     */
4515    public void scheduleLayoutAnimation() {
4516        mGroupFlags |= FLAG_RUN_ANIMATION;
4517    }
4518
4519    /**
4520     * Sets the layout animation controller used to animate the group's
4521     * children after the first layout.
4522     *
4523     * @param controller the animation controller
4524     */
4525    public void setLayoutAnimation(LayoutAnimationController controller) {
4526        mLayoutAnimationController = controller;
4527        if (mLayoutAnimationController != null) {
4528            mGroupFlags |= FLAG_RUN_ANIMATION;
4529        }
4530    }
4531
4532    /**
4533     * Returns the layout animation controller used to animate the group's
4534     * children.
4535     *
4536     * @return the current animation controller
4537     */
4538    public LayoutAnimationController getLayoutAnimation() {
4539        return mLayoutAnimationController;
4540    }
4541
4542    /**
4543     * Indicates whether the children's drawing cache is used during a layout
4544     * animation. By default, the drawing cache is enabled but this will prevent
4545     * nested layout animations from working. To nest animations, you must disable
4546     * the cache.
4547     *
4548     * @return true if the animation cache is enabled, false otherwise
4549     *
4550     * @see #setAnimationCacheEnabled(boolean)
4551     * @see View#setDrawingCacheEnabled(boolean)
4552     */
4553    @ViewDebug.ExportedProperty
4554    public boolean isAnimationCacheEnabled() {
4555        return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
4556    }
4557
4558    /**
4559     * Enables or disables the children's drawing cache during a layout animation.
4560     * By default, the drawing cache is enabled but this will prevent nested
4561     * layout animations from working. To nest animations, you must disable the
4562     * cache.
4563     *
4564     * @param enabled true to enable the animation cache, false otherwise
4565     *
4566     * @see #isAnimationCacheEnabled()
4567     * @see View#setDrawingCacheEnabled(boolean)
4568     */
4569    public void setAnimationCacheEnabled(boolean enabled) {
4570        setBooleanFlag(FLAG_ANIMATION_CACHE, enabled);
4571    }
4572
4573    /**
4574     * Indicates whether this ViewGroup will always try to draw its children using their
4575     * drawing cache. By default this property is enabled.
4576     *
4577     * @return true if the animation cache is enabled, false otherwise
4578     *
4579     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4580     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4581     * @see View#setDrawingCacheEnabled(boolean)
4582     */
4583    @ViewDebug.ExportedProperty(category = "drawing")
4584    public boolean isAlwaysDrawnWithCacheEnabled() {
4585        return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE;
4586    }
4587
4588    /**
4589     * Indicates whether this ViewGroup will always try to draw its children using their
4590     * drawing cache. This property can be set to true when the cache rendering is
4591     * slightly different from the children's normal rendering. Renderings can be different,
4592     * for instance, when the cache's quality is set to low.
4593     *
4594     * When this property is disabled, the ViewGroup will use the drawing cache of its
4595     * children only when asked to. It's usually the task of subclasses to tell ViewGroup
4596     * when to start using the drawing cache and when to stop using it.
4597     *
4598     * @param always true to always draw with the drawing cache, false otherwise
4599     *
4600     * @see #isAlwaysDrawnWithCacheEnabled()
4601     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4602     * @see View#setDrawingCacheEnabled(boolean)
4603     * @see View#setDrawingCacheQuality(int)
4604     */
4605    public void setAlwaysDrawnWithCacheEnabled(boolean always) {
4606        setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always);
4607    }
4608
4609    /**
4610     * Indicates whether the ViewGroup is currently drawing its children using
4611     * their drawing cache.
4612     *
4613     * @return true if children should be drawn with their cache, false otherwise
4614     *
4615     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4616     * @see #setChildrenDrawnWithCacheEnabled(boolean)
4617     */
4618    @ViewDebug.ExportedProperty(category = "drawing")
4619    protected boolean isChildrenDrawnWithCacheEnabled() {
4620        return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE;
4621    }
4622
4623    /**
4624     * Tells the ViewGroup to draw its children using their drawing cache. This property
4625     * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache
4626     * will be used only if it has been enabled.
4627     *
4628     * Subclasses should call this method to start and stop using the drawing cache when
4629     * they perform performance sensitive operations, like scrolling or animating.
4630     *
4631     * @param enabled true if children should be drawn with their cache, false otherwise
4632     *
4633     * @see #setAlwaysDrawnWithCacheEnabled(boolean)
4634     * @see #isChildrenDrawnWithCacheEnabled()
4635     */
4636    protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
4637        setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled);
4638    }
4639
4640    /**
4641     * Indicates whether the ViewGroup is drawing its children in the order defined by
4642     * {@link #getChildDrawingOrder(int, int)}.
4643     *
4644     * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)},
4645     *         false otherwise
4646     *
4647     * @see #setChildrenDrawingOrderEnabled(boolean)
4648     * @see #getChildDrawingOrder(int, int)
4649     */
4650    @ViewDebug.ExportedProperty(category = "drawing")
4651    protected boolean isChildrenDrawingOrderEnabled() {
4652        return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER;
4653    }
4654
4655    /**
4656     * Tells the ViewGroup whether to draw its children in the order defined by the method
4657     * {@link #getChildDrawingOrder(int, int)}.
4658     *
4659     * @param enabled true if the order of the children when drawing is determined by
4660     *        {@link #getChildDrawingOrder(int, int)}, false otherwise
4661     *
4662     * @see #isChildrenDrawingOrderEnabled()
4663     * @see #getChildDrawingOrder(int, int)
4664     */
4665    protected void setChildrenDrawingOrderEnabled(boolean enabled) {
4666        setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled);
4667    }
4668
4669    private void setBooleanFlag(int flag, boolean value) {
4670        if (value) {
4671            mGroupFlags |= flag;
4672        } else {
4673            mGroupFlags &= ~flag;
4674        }
4675    }
4676
4677    /**
4678     * Returns an integer indicating what types of drawing caches are kept in memory.
4679     *
4680     * @see #setPersistentDrawingCache(int)
4681     * @see #setAnimationCacheEnabled(boolean)
4682     *
4683     * @return one or a combination of {@link #PERSISTENT_NO_CACHE},
4684     *         {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4685     *         and {@link #PERSISTENT_ALL_CACHES}
4686     */
4687    @ViewDebug.ExportedProperty(category = "drawing", mapping = {
4688        @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE,        to = "NONE"),
4689        @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"),
4690        @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"),
4691        @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES,      to = "ALL")
4692    })
4693    public int getPersistentDrawingCache() {
4694        return mPersistentDrawingCache;
4695    }
4696
4697    /**
4698     * Indicates what types of drawing caches should be kept in memory after
4699     * they have been created.
4700     *
4701     * @see #getPersistentDrawingCache()
4702     * @see #setAnimationCacheEnabled(boolean)
4703     *
4704     * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE},
4705     *        {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
4706     *        and {@link #PERSISTENT_ALL_CACHES}
4707     */
4708    public void setPersistentDrawingCache(int drawingCacheToKeep) {
4709        mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES;
4710    }
4711
4712    /**
4713     * Returns the basis of alignment during layout operations on this view group:
4714     * either {@link #LAYOUT_MODE_CLIP_BOUNDS} or {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
4715     *
4716     * @return the layout mode to use during layout operations
4717     *
4718     * @see #setLayoutMode(int)
4719     */
4720    public int getLayoutMode() {
4721        return mLayoutMode;
4722    }
4723
4724    /**
4725     * Sets the basis of alignment during the layout of this view group.
4726     * Valid values are either {@link #LAYOUT_MODE_CLIP_BOUNDS} or
4727     * {@link #LAYOUT_MODE_OPTICAL_BOUNDS}.
4728     * <p>
4729     * The default is {@link #LAYOUT_MODE_CLIP_BOUNDS}.
4730     *
4731     * @param layoutMode the layout mode to use during layout operations
4732     *
4733     * @see #getLayoutMode()
4734     */
4735    public void setLayoutMode(int layoutMode) {
4736        if (mLayoutMode != layoutMode) {
4737            mLayoutMode = layoutMode;
4738            requestLayout();
4739        }
4740    }
4741
4742    /**
4743     * Returns a new set of layout parameters based on the supplied attributes set.
4744     *
4745     * @param attrs the attributes to build the layout parameters from
4746     *
4747     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4748     *         of its descendants
4749     */
4750    public LayoutParams generateLayoutParams(AttributeSet attrs) {
4751        return new LayoutParams(getContext(), attrs);
4752    }
4753
4754    /**
4755     * Returns a safe set of layout parameters based on the supplied layout params.
4756     * When a ViewGroup is passed a View whose layout params do not pass the test of
4757     * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
4758     * is invoked. This method should return a new set of layout params suitable for
4759     * this ViewGroup, possibly by copying the appropriate attributes from the
4760     * specified set of layout params.
4761     *
4762     * @param p The layout parameters to convert into a suitable set of layout parameters
4763     *          for this ViewGroup.
4764     *
4765     * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
4766     *         of its descendants
4767     */
4768    protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
4769        return p;
4770    }
4771
4772    /**
4773     * Returns a set of default layout parameters. These parameters are requested
4774     * when the View passed to {@link #addView(View)} has no layout parameters
4775     * already set. If null is returned, an exception is thrown from addView.
4776     *
4777     * @return a set of default layout parameters or null
4778     */
4779    protected LayoutParams generateDefaultLayoutParams() {
4780        return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
4781    }
4782
4783    /**
4784     * {@inheritDoc}
4785     */
4786    @Override
4787    protected void debug(int depth) {
4788        super.debug(depth);
4789        String output;
4790
4791        if (mFocused != null) {
4792            output = debugIndent(depth);
4793            output += "mFocused";
4794            Log.d(VIEW_LOG_TAG, output);
4795        }
4796        if (mChildrenCount != 0) {
4797            output = debugIndent(depth);
4798            output += "{";
4799            Log.d(VIEW_LOG_TAG, output);
4800        }
4801        int count = mChildrenCount;
4802        for (int i = 0; i < count; i++) {
4803            View child = mChildren[i];
4804            child.debug(depth + 1);
4805        }
4806
4807        if (mChildrenCount != 0) {
4808            output = debugIndent(depth);
4809            output += "}";
4810            Log.d(VIEW_LOG_TAG, output);
4811        }
4812    }
4813
4814    /**
4815     * Returns the position in the group of the specified child view.
4816     *
4817     * @param child the view for which to get the position
4818     * @return a positive integer representing the position of the view in the
4819     *         group, or -1 if the view does not exist in the group
4820     */
4821    public int indexOfChild(View child) {
4822        final int count = mChildrenCount;
4823        final View[] children = mChildren;
4824        for (int i = 0; i < count; i++) {
4825            if (children[i] == child) {
4826                return i;
4827            }
4828        }
4829        return -1;
4830    }
4831
4832    /**
4833     * Returns the number of children in the group.
4834     *
4835     * @return a positive integer representing the number of children in
4836     *         the group
4837     */
4838    public int getChildCount() {
4839        return mChildrenCount;
4840    }
4841
4842    /**
4843     * Returns the view at the specified position in the group.
4844     *
4845     * @param index the position at which to get the view from
4846     * @return the view at the specified position or null if the position
4847     *         does not exist within the group
4848     */
4849    public View getChildAt(int index) {
4850        if (index < 0 || index >= mChildrenCount) {
4851            return null;
4852        }
4853        return mChildren[index];
4854    }
4855
4856    /**
4857     * Ask all of the children of this view to measure themselves, taking into
4858     * account both the MeasureSpec requirements for this view and its padding.
4859     * We skip children that are in the GONE state The heavy lifting is done in
4860     * getChildMeasureSpec.
4861     *
4862     * @param widthMeasureSpec The width requirements for this view
4863     * @param heightMeasureSpec The height requirements for this view
4864     */
4865    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
4866        final int size = mChildrenCount;
4867        final View[] children = mChildren;
4868        for (int i = 0; i < size; ++i) {
4869            final View child = children[i];
4870            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
4871                measureChild(child, widthMeasureSpec, heightMeasureSpec);
4872            }
4873        }
4874    }
4875
4876    /**
4877     * Ask one of the children of this view to measure itself, taking into
4878     * account both the MeasureSpec requirements for this view and its padding.
4879     * The heavy lifting is done in getChildMeasureSpec.
4880     *
4881     * @param child The child to measure
4882     * @param parentWidthMeasureSpec The width requirements for this view
4883     * @param parentHeightMeasureSpec The height requirements for this view
4884     */
4885    protected void measureChild(View child, int parentWidthMeasureSpec,
4886            int parentHeightMeasureSpec) {
4887        final LayoutParams lp = child.getLayoutParams();
4888
4889        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4890                mPaddingLeft + mPaddingRight, lp.width);
4891        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4892                mPaddingTop + mPaddingBottom, lp.height);
4893
4894        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4895    }
4896
4897    /**
4898     * Ask one of the children of this view to measure itself, taking into
4899     * account both the MeasureSpec requirements for this view and its padding
4900     * and margins. The child must have MarginLayoutParams The heavy lifting is
4901     * done in getChildMeasureSpec.
4902     *
4903     * @param child The child to measure
4904     * @param parentWidthMeasureSpec The width requirements for this view
4905     * @param widthUsed Extra space that has been used up by the parent
4906     *        horizontally (possibly by other children of the parent)
4907     * @param parentHeightMeasureSpec The height requirements for this view
4908     * @param heightUsed Extra space that has been used up by the parent
4909     *        vertically (possibly by other children of the parent)
4910     */
4911    protected void measureChildWithMargins(View child,
4912            int parentWidthMeasureSpec, int widthUsed,
4913            int parentHeightMeasureSpec, int heightUsed) {
4914        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
4915
4916        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
4917                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
4918                        + widthUsed, lp.width);
4919        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
4920                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
4921                        + heightUsed, lp.height);
4922
4923        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
4924    }
4925
4926    /**
4927     * Does the hard part of measureChildren: figuring out the MeasureSpec to
4928     * pass to a particular child. This method figures out the right MeasureSpec
4929     * for one dimension (height or width) of one child view.
4930     *
4931     * The goal is to combine information from our MeasureSpec with the
4932     * LayoutParams of the child to get the best possible results. For example,
4933     * if the this view knows its size (because its MeasureSpec has a mode of
4934     * EXACTLY), and the child has indicated in its LayoutParams that it wants
4935     * to be the same size as the parent, the parent should ask the child to
4936     * layout given an exact size.
4937     *
4938     * @param spec The requirements for this view
4939     * @param padding The padding of this view for the current dimension and
4940     *        margins, if applicable
4941     * @param childDimension How big the child wants to be in the current
4942     *        dimension
4943     * @return a MeasureSpec integer for the child
4944     */
4945    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
4946        int specMode = MeasureSpec.getMode(spec);
4947        int specSize = MeasureSpec.getSize(spec);
4948
4949        int size = Math.max(0, specSize - padding);
4950
4951        int resultSize = 0;
4952        int resultMode = 0;
4953
4954        switch (specMode) {
4955        // Parent has imposed an exact size on us
4956        case MeasureSpec.EXACTLY:
4957            if (childDimension >= 0) {
4958                resultSize = childDimension;
4959                resultMode = MeasureSpec.EXACTLY;
4960            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4961                // Child wants to be our size. So be it.
4962                resultSize = size;
4963                resultMode = MeasureSpec.EXACTLY;
4964            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4965                // Child wants to determine its own size. It can't be
4966                // bigger than us.
4967                resultSize = size;
4968                resultMode = MeasureSpec.AT_MOST;
4969            }
4970            break;
4971
4972        // Parent has imposed a maximum size on us
4973        case MeasureSpec.AT_MOST:
4974            if (childDimension >= 0) {
4975                // Child wants a specific size... so be it
4976                resultSize = childDimension;
4977                resultMode = MeasureSpec.EXACTLY;
4978            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4979                // Child wants to be our size, but our size is not fixed.
4980                // Constrain child to not be bigger than us.
4981                resultSize = size;
4982                resultMode = MeasureSpec.AT_MOST;
4983            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
4984                // Child wants to determine its own size. It can't be
4985                // bigger than us.
4986                resultSize = size;
4987                resultMode = MeasureSpec.AT_MOST;
4988            }
4989            break;
4990
4991        // Parent asked to see how big we want to be
4992        case MeasureSpec.UNSPECIFIED:
4993            if (childDimension >= 0) {
4994                // Child wants a specific size... let him have it
4995                resultSize = childDimension;
4996                resultMode = MeasureSpec.EXACTLY;
4997            } else if (childDimension == LayoutParams.MATCH_PARENT) {
4998                // Child wants to be our size... find out how big it should
4999                // be
5000                resultSize = 0;
5001                resultMode = MeasureSpec.UNSPECIFIED;
5002            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
5003                // Child wants to determine its own size.... find out how
5004                // big it should be
5005                resultSize = 0;
5006                resultMode = MeasureSpec.UNSPECIFIED;
5007            }
5008            break;
5009        }
5010        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
5011    }
5012
5013
5014    /**
5015     * Removes any pending animations for views that have been removed. Call
5016     * this if you don't want animations for exiting views to stack up.
5017     */
5018    public void clearDisappearingChildren() {
5019        if (mDisappearingChildren != null) {
5020            mDisappearingChildren.clear();
5021            invalidate();
5022        }
5023    }
5024
5025    /**
5026     * Add a view which is removed from mChildren but still needs animation
5027     *
5028     * @param v View to add
5029     */
5030    private void addDisappearingView(View v) {
5031        ArrayList<View> disappearingChildren = mDisappearingChildren;
5032
5033        if (disappearingChildren == null) {
5034            disappearingChildren = mDisappearingChildren = new ArrayList<View>();
5035        }
5036
5037        disappearingChildren.add(v);
5038    }
5039
5040    /**
5041     * Cleanup a view when its animation is done. This may mean removing it from
5042     * the list of disappearing views.
5043     *
5044     * @param view The view whose animation has finished
5045     * @param animation The animation, cannot be null
5046     */
5047    void finishAnimatingView(final View view, Animation animation) {
5048        final ArrayList<View> disappearingChildren = mDisappearingChildren;
5049        if (disappearingChildren != null) {
5050            if (disappearingChildren.contains(view)) {
5051                disappearingChildren.remove(view);
5052
5053                if (view.mAttachInfo != null) {
5054                    view.dispatchDetachedFromWindow();
5055                }
5056
5057                view.clearAnimation();
5058                mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
5059            }
5060        }
5061
5062        if (animation != null && !animation.getFillAfter()) {
5063            view.clearAnimation();
5064        }
5065
5066        if ((view.mPrivateFlags & PFLAG_ANIMATION_STARTED) == PFLAG_ANIMATION_STARTED) {
5067            view.onAnimationEnd();
5068            // Should be performed by onAnimationEnd() but this avoid an infinite loop,
5069            // so we'd rather be safe than sorry
5070            view.mPrivateFlags &= ~PFLAG_ANIMATION_STARTED;
5071            // Draw one more frame after the animation is done
5072            mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
5073        }
5074    }
5075
5076    /**
5077     * Utility function called by View during invalidation to determine whether a view that
5078     * is invisible or gone should still be invalidated because it is being transitioned (and
5079     * therefore still needs to be drawn).
5080     */
5081    boolean isViewTransitioning(View view) {
5082        return (mTransitioningViews != null && mTransitioningViews.contains(view));
5083    }
5084
5085    /**
5086     * This method tells the ViewGroup that the given View object, which should have this
5087     * ViewGroup as its parent,
5088     * should be kept around  (re-displayed when the ViewGroup draws its children) even if it
5089     * is removed from its parent. This allows animations, such as those used by
5090     * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate
5091     * the removal of views. A call to this method should always be accompanied by a later call
5092     * to {@link #endViewTransition(View)}, such as after an animation on the View has finished,
5093     * so that the View finally gets removed.
5094     *
5095     * @param view The View object to be kept visible even if it gets removed from its parent.
5096     */
5097    public void startViewTransition(View view) {
5098        if (view.mParent == this) {
5099            if (mTransitioningViews == null) {
5100                mTransitioningViews = new ArrayList<View>();
5101            }
5102            mTransitioningViews.add(view);
5103        }
5104    }
5105
5106    /**
5107     * This method should always be called following an earlier call to
5108     * {@link #startViewTransition(View)}. The given View is finally removed from its parent
5109     * and will no longer be displayed. Note that this method does not perform the functionality
5110     * of removing a view from its parent; it just discontinues the display of a View that
5111     * has previously been removed.
5112     *
5113     * @return view The View object that has been removed but is being kept around in the visible
5114     * hierarchy by an earlier call to {@link #startViewTransition(View)}.
5115     */
5116    public void endViewTransition(View view) {
5117        if (mTransitioningViews != null) {
5118            mTransitioningViews.remove(view);
5119            final ArrayList<View> disappearingChildren = mDisappearingChildren;
5120            if (disappearingChildren != null && disappearingChildren.contains(view)) {
5121                disappearingChildren.remove(view);
5122                if (mVisibilityChangingChildren != null &&
5123                        mVisibilityChangingChildren.contains(view)) {
5124                    mVisibilityChangingChildren.remove(view);
5125                } else {
5126                    if (view.mAttachInfo != null) {
5127                        view.dispatchDetachedFromWindow();
5128                    }
5129                    if (view.mParent != null) {
5130                        view.mParent = null;
5131                    }
5132                }
5133                invalidate();
5134            }
5135        }
5136    }
5137
5138    private LayoutTransition.TransitionListener mLayoutTransitionListener =
5139            new LayoutTransition.TransitionListener() {
5140        @Override
5141        public void startTransition(LayoutTransition transition, ViewGroup container,
5142                View view, int transitionType) {
5143            // We only care about disappearing items, since we need special logic to keep
5144            // those items visible after they've been 'removed'
5145            if (transitionType == LayoutTransition.DISAPPEARING) {
5146                startViewTransition(view);
5147            }
5148        }
5149
5150        @Override
5151        public void endTransition(LayoutTransition transition, ViewGroup container,
5152                View view, int transitionType) {
5153            if (mLayoutSuppressed && !transition.isChangingLayout()) {
5154                requestLayout();
5155                mLayoutSuppressed = false;
5156            }
5157            if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
5158                endViewTransition(view);
5159            }
5160        }
5161    };
5162
5163    /**
5164     * {@inheritDoc}
5165     */
5166    @Override
5167    public boolean gatherTransparentRegion(Region region) {
5168        // If no transparent regions requested, we are always opaque.
5169        final boolean meOpaque = (mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0;
5170        if (meOpaque && region == null) {
5171            // The caller doesn't care about the region, so stop now.
5172            return true;
5173        }
5174        super.gatherTransparentRegion(region);
5175        final View[] children = mChildren;
5176        final int count = mChildrenCount;
5177        boolean noneOfTheChildrenAreTransparent = true;
5178        for (int i = 0; i < count; i++) {
5179            final View child = children[i];
5180            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
5181                if (!child.gatherTransparentRegion(region)) {
5182                    noneOfTheChildrenAreTransparent = false;
5183                }
5184            }
5185        }
5186        return meOpaque || noneOfTheChildrenAreTransparent;
5187    }
5188
5189    /**
5190     * {@inheritDoc}
5191     */
5192    public void requestTransparentRegion(View child) {
5193        if (child != null) {
5194            child.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS;
5195            if (mParent != null) {
5196                mParent.requestTransparentRegion(this);
5197            }
5198        }
5199    }
5200
5201
5202    @Override
5203    protected boolean fitSystemWindows(Rect insets) {
5204        boolean done = super.fitSystemWindows(insets);
5205        if (!done) {
5206            final int count = mChildrenCount;
5207            final View[] children = mChildren;
5208            for (int i = 0; i < count; i++) {
5209                done = children[i].fitSystemWindows(insets);
5210                if (done) {
5211                    break;
5212                }
5213            }
5214        }
5215        return done;
5216    }
5217
5218    /**
5219     * Returns the animation listener to which layout animation events are
5220     * sent.
5221     *
5222     * @return an {@link android.view.animation.Animation.AnimationListener}
5223     */
5224    public Animation.AnimationListener getLayoutAnimationListener() {
5225        return mAnimationListener;
5226    }
5227
5228    @Override
5229    protected void drawableStateChanged() {
5230        super.drawableStateChanged();
5231
5232        if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
5233            if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5234                throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
5235                        + " child has duplicateParentState set to true");
5236            }
5237
5238            final View[] children = mChildren;
5239            final int count = mChildrenCount;
5240
5241            for (int i = 0; i < count; i++) {
5242                final View child = children[i];
5243                if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
5244                    child.refreshDrawableState();
5245                }
5246            }
5247        }
5248    }
5249
5250    @Override
5251    public void jumpDrawablesToCurrentState() {
5252        super.jumpDrawablesToCurrentState();
5253        final View[] children = mChildren;
5254        final int count = mChildrenCount;
5255        for (int i = 0; i < count; i++) {
5256            children[i].jumpDrawablesToCurrentState();
5257        }
5258    }
5259
5260    @Override
5261    protected int[] onCreateDrawableState(int extraSpace) {
5262        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) {
5263            return super.onCreateDrawableState(extraSpace);
5264        }
5265
5266        int need = 0;
5267        int n = getChildCount();
5268        for (int i = 0; i < n; i++) {
5269            int[] childState = getChildAt(i).getDrawableState();
5270
5271            if (childState != null) {
5272                need += childState.length;
5273            }
5274        }
5275
5276        int[] state = super.onCreateDrawableState(extraSpace + need);
5277
5278        for (int i = 0; i < n; i++) {
5279            int[] childState = getChildAt(i).getDrawableState();
5280
5281            if (childState != null) {
5282                state = mergeDrawableStates(state, childState);
5283            }
5284        }
5285
5286        return state;
5287    }
5288
5289    /**
5290     * Sets whether this ViewGroup's drawable states also include
5291     * its children's drawable states.  This is used, for example, to
5292     * make a group appear to be focused when its child EditText or button
5293     * is focused.
5294     */
5295    public void setAddStatesFromChildren(boolean addsStates) {
5296        if (addsStates) {
5297            mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN;
5298        } else {
5299            mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN;
5300        }
5301
5302        refreshDrawableState();
5303    }
5304
5305    /**
5306     * Returns whether this ViewGroup's drawable states also include
5307     * its children's drawable states.  This is used, for example, to
5308     * make a group appear to be focused when its child EditText or button
5309     * is focused.
5310     */
5311    public boolean addStatesFromChildren() {
5312        return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0;
5313    }
5314
5315    /**
5316     * If {@link #addStatesFromChildren} is true, refreshes this group's
5317     * drawable state (to include the states from its children).
5318     */
5319    public void childDrawableStateChanged(View child) {
5320        if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
5321            refreshDrawableState();
5322        }
5323    }
5324
5325    /**
5326     * Specifies the animation listener to which layout animation events must
5327     * be sent. Only
5328     * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)}
5329     * and
5330     * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)}
5331     * are invoked.
5332     *
5333     * @param animationListener the layout animation listener
5334     */
5335    public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
5336        mAnimationListener = animationListener;
5337    }
5338
5339    /**
5340     * This method is called by LayoutTransition when there are 'changing' animations that need
5341     * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who
5342     * starts all pending transitions prior to the drawing phase in the current traversal.
5343     *
5344     * @param transition The LayoutTransition to be started on the next traversal.
5345     *
5346     * @hide
5347     */
5348    public void requestTransitionStart(LayoutTransition transition) {
5349        ViewRootImpl viewAncestor = getViewRootImpl();
5350        if (viewAncestor != null) {
5351            viewAncestor.requestTransitionStart(transition);
5352        }
5353    }
5354
5355    /**
5356     * @hide
5357     */
5358    @Override
5359    public void resetResolvedLayoutDirection() {
5360        super.resetResolvedLayoutDirection();
5361
5362        // Take care of resetting the children resolution too
5363        int count = getChildCount();
5364        for (int i = 0; i < count; i++) {
5365            final View child = getChildAt(i);
5366            if (child.isLayoutDirectionInherited()) {
5367                child.resetResolvedLayoutDirection();
5368            }
5369            if (child.isTextDirectionInherited()) {
5370                child.resetResolvedTextDirection();
5371            }
5372            if (child.isTextAlignmentInherited()) {
5373                child.resetResolvedTextAlignment();
5374            }
5375        }
5376    }
5377
5378    /**
5379     * Return true if the pressed state should be delayed for children or descendants of this
5380     * ViewGroup. Generally, this should be done for containers that can scroll, such as a List.
5381     * This prevents the pressed state from appearing when the user is actually trying to scroll
5382     * the content.
5383     *
5384     * The default implementation returns true for compatibility reasons. Subclasses that do
5385     * not scroll should generally override this method and return false.
5386     */
5387    public boolean shouldDelayChildPressedState() {
5388        return true;
5389    }
5390
5391    /** @hide */
5392    protected void onSetLayoutParams(View child, LayoutParams layoutParams) {
5393    }
5394
5395    /**
5396     * LayoutParams are used by views to tell their parents how they want to be
5397     * laid out. See
5398     * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes}
5399     * for a list of all child view attributes that this class supports.
5400     *
5401     * <p>
5402     * The base LayoutParams class just describes how big the view wants to be
5403     * for both width and height. For each dimension, it can specify one of:
5404     * <ul>
5405     * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
5406     * means that the view wants to be as big as its parent (minus padding)
5407     * <li> WRAP_CONTENT, which means that the view wants to be just big enough
5408     * to enclose its content (plus padding)
5409     * <li> an exact number
5410     * </ul>
5411     * There are subclasses of LayoutParams for different subclasses of
5412     * ViewGroup. For example, AbsoluteLayout has its own subclass of
5413     * LayoutParams which adds an X and Y value.</p>
5414     *
5415     * <div class="special reference">
5416     * <h3>Developer Guides</h3>
5417     * <p>For more information about creating user interface layouts, read the
5418     * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer
5419     * guide.</p></div>
5420     *
5421     * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
5422     * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
5423     */
5424    public static class LayoutParams {
5425        /**
5426         * Special value for the height or width requested by a View.
5427         * FILL_PARENT means that the view wants to be as big as its parent,
5428         * minus the parent's padding, if any. This value is deprecated
5429         * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
5430         */
5431        @SuppressWarnings({"UnusedDeclaration"})
5432        @Deprecated
5433        public static final int FILL_PARENT = -1;
5434
5435        /**
5436         * Special value for the height or width requested by a View.
5437         * MATCH_PARENT means that the view wants to be as big as its parent,
5438         * minus the parent's padding, if any. Introduced in API Level 8.
5439         */
5440        public static final int MATCH_PARENT = -1;
5441
5442        /**
5443         * Special value for the height or width requested by a View.
5444         * WRAP_CONTENT means that the view wants to be just large enough to fit
5445         * its own internal content, taking its own padding into account.
5446         */
5447        public static final int WRAP_CONTENT = -2;
5448
5449        /**
5450         * Information about how wide the view wants to be. Can be one of the
5451         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5452         * in API Level 8) or WRAP_CONTENT. or an exact size.
5453         */
5454        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5455            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5456            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5457        })
5458        public int width;
5459
5460        /**
5461         * Information about how tall the view wants to be. Can be one of the
5462         * constants FILL_PARENT (replaced by MATCH_PARENT ,
5463         * in API Level 8) or WRAP_CONTENT. or an exact size.
5464         */
5465        @ViewDebug.ExportedProperty(category = "layout", mapping = {
5466            @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
5467            @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
5468        })
5469        public int height;
5470
5471        /**
5472         * Used to animate layouts.
5473         */
5474        public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
5475
5476        /**
5477         * Creates a new set of layout parameters. The values are extracted from
5478         * the supplied attributes set and context. The XML attributes mapped
5479         * to this set of layout parameters are:
5480         *
5481         * <ul>
5482         *   <li><code>layout_width</code>: the width, either an exact value,
5483         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5484         *   {@link #MATCH_PARENT} in API Level 8)</li>
5485         *   <li><code>layout_height</code>: the height, either an exact value,
5486         *   {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
5487         *   {@link #MATCH_PARENT} in API Level 8)</li>
5488         * </ul>
5489         *
5490         * @param c the application environment
5491         * @param attrs the set of attributes from which to extract the layout
5492         *              parameters' values
5493         */
5494        public LayoutParams(Context c, AttributeSet attrs) {
5495            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
5496            setBaseAttributes(a,
5497                    R.styleable.ViewGroup_Layout_layout_width,
5498                    R.styleable.ViewGroup_Layout_layout_height);
5499            a.recycle();
5500        }
5501
5502        /**
5503         * Creates a new set of layout parameters with the specified width
5504         * and height.
5505         *
5506         * @param width the width, either {@link #WRAP_CONTENT},
5507         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5508         *        API Level 8), or a fixed size in pixels
5509         * @param height the height, either {@link #WRAP_CONTENT},
5510         *        {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
5511         *        API Level 8), or a fixed size in pixels
5512         */
5513        public LayoutParams(int width, int height) {
5514            this.width = width;
5515            this.height = height;
5516        }
5517
5518        /**
5519         * Copy constructor. Clones the width and height values of the source.
5520         *
5521         * @param source The layout params to copy from.
5522         */
5523        public LayoutParams(LayoutParams source) {
5524            this.width = source.width;
5525            this.height = source.height;
5526        }
5527
5528        /**
5529         * Used internally by MarginLayoutParams.
5530         * @hide
5531         */
5532        LayoutParams() {
5533        }
5534
5535        /**
5536         * Extracts the <code>width</code> and <code>height</code> layout parameters
5537         * from the supplied TypedArray, <code>a</code>, and assigns them
5538         * to the appropriate fields. If, <code>a</code>, does not contain an
5539         * entry for either attribute, the value, {@link ViewGroup.LayoutParams#WRAP_CONTENT},
5540         * is used as a default.
5541         *
5542         * @param a the style attributes to extract the parameters from
5543         * @param widthAttr the identifier of the width attribute
5544         * @param heightAttr the identifier of the height attribute
5545         */
5546        protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
5547            width = a.getLayoutDimension(widthAttr, WRAP_CONTENT);
5548            height = a.getLayoutDimension(heightAttr, WRAP_CONTENT);
5549        }
5550
5551        /**
5552         * Resolve layout parameters depending on the layout direction. Subclasses that care about
5553         * layoutDirection changes should override this method. The default implementation does
5554         * nothing.
5555         *
5556         * @param layoutDirection the direction of the layout
5557         *
5558         * {@link View#LAYOUT_DIRECTION_LTR}
5559         * {@link View#LAYOUT_DIRECTION_RTL}
5560         */
5561        public void onResolveLayoutDirection(int layoutDirection) {
5562        }
5563
5564        /**
5565         * Returns a String representation of this set of layout parameters.
5566         *
5567         * @param output the String to prepend to the internal representation
5568         * @return a String with the following format: output +
5569         *         "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }"
5570         *
5571         * @hide
5572         */
5573        public String debug(String output) {
5574            return output + "ViewGroup.LayoutParams={ width="
5575                    + sizeToString(width) + ", height=" + sizeToString(height) + " }";
5576        }
5577
5578        /**
5579         * Use {@code canvas} to draw suitable debugging annotations for these LayoutParameters.
5580         *
5581         * @param view the view that contains these layout parameters
5582         * @param canvas the canvas on which to draw
5583         *
5584         * @hide
5585         */
5586        public void onDebugDraw(View view, Canvas canvas, Paint paint) {
5587        }
5588
5589        /**
5590         * Converts the specified size to a readable String.
5591         *
5592         * @param size the size to convert
5593         * @return a String instance representing the supplied size
5594         *
5595         * @hide
5596         */
5597        protected static String sizeToString(int size) {
5598            if (size == WRAP_CONTENT) {
5599                return "wrap-content";
5600            }
5601            if (size == MATCH_PARENT) {
5602                return "match-parent";
5603            }
5604            return String.valueOf(size);
5605        }
5606    }
5607
5608    /**
5609     * Per-child layout information for layouts that support margins.
5610     * See
5611     * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes}
5612     * for a list of all child view attributes that this class supports.
5613     */
5614    public static class MarginLayoutParams extends ViewGroup.LayoutParams {
5615        /**
5616         * The left margin in pixels of the child.
5617         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5618         * to this field.
5619         */
5620        @ViewDebug.ExportedProperty(category = "layout")
5621        public int leftMargin;
5622
5623        /**
5624         * The top margin in pixels of the child.
5625         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5626         * to this field.
5627         */
5628        @ViewDebug.ExportedProperty(category = "layout")
5629        public int topMargin;
5630
5631        /**
5632         * The right margin in pixels of the child.
5633         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5634         * to this field.
5635         */
5636        @ViewDebug.ExportedProperty(category = "layout")
5637        public int rightMargin;
5638
5639        /**
5640         * The bottom margin in pixels of the child.
5641         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5642         * to this field.
5643         */
5644        @ViewDebug.ExportedProperty(category = "layout")
5645        public int bottomMargin;
5646
5647        /**
5648         * The start margin in pixels of the child.
5649         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5650         * to this field.
5651         */
5652        @ViewDebug.ExportedProperty(category = "layout")
5653        private int startMargin = DEFAULT_RELATIVE;
5654
5655        /**
5656         * The end margin in pixels of the child.
5657         * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value
5658         * to this field.
5659         */
5660        @ViewDebug.ExportedProperty(category = "layout")
5661        private int endMargin = DEFAULT_RELATIVE;
5662
5663        /**
5664         * The default start and end margin.
5665         * @hide
5666         */
5667        public static final int DEFAULT_RELATIVE = Integer.MIN_VALUE;
5668
5669        private int initialLeftMargin;
5670        private int initialRightMargin;
5671
5672        private static int LAYOUT_DIRECTION_UNDEFINED = -1;
5673
5674        // Layout direction undefined by default
5675        private int layoutDirection = LAYOUT_DIRECTION_UNDEFINED;
5676
5677        /**
5678         * Creates a new set of layout parameters. The values are extracted from
5679         * the supplied attributes set and context.
5680         *
5681         * @param c the application environment
5682         * @param attrs the set of attributes from which to extract the layout
5683         *              parameters' values
5684         */
5685        public MarginLayoutParams(Context c, AttributeSet attrs) {
5686            super();
5687
5688            TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
5689            setBaseAttributes(a,
5690                    R.styleable.ViewGroup_MarginLayout_layout_width,
5691                    R.styleable.ViewGroup_MarginLayout_layout_height);
5692
5693            int margin = a.getDimensionPixelSize(
5694                    com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
5695            if (margin >= 0) {
5696                leftMargin = margin;
5697                topMargin = margin;
5698                rightMargin= margin;
5699                bottomMargin = margin;
5700            } else {
5701                leftMargin = a.getDimensionPixelSize(
5702                        R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0);
5703                topMargin = a.getDimensionPixelSize(
5704                        R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0);
5705                rightMargin = a.getDimensionPixelSize(
5706                        R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0);
5707                bottomMargin = a.getDimensionPixelSize(
5708                        R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0);
5709                startMargin = a.getDimensionPixelSize(
5710                        R.styleable.ViewGroup_MarginLayout_layout_marginStart, DEFAULT_RELATIVE);
5711                endMargin = a.getDimensionPixelSize(
5712                        R.styleable.ViewGroup_MarginLayout_layout_marginEnd, DEFAULT_RELATIVE);
5713            }
5714
5715            initialLeftMargin = leftMargin;
5716            initialRightMargin = rightMargin;
5717
5718            a.recycle();
5719        }
5720
5721        /**
5722         * {@inheritDoc}
5723         */
5724        public MarginLayoutParams(int width, int height) {
5725            super(width, height);
5726        }
5727
5728        /**
5729         * Copy constructor. Clones the width, height and margin values of the source.
5730         *
5731         * @param source The layout params to copy from.
5732         */
5733        public MarginLayoutParams(MarginLayoutParams source) {
5734            this.width = source.width;
5735            this.height = source.height;
5736
5737            this.leftMargin = source.leftMargin;
5738            this.topMargin = source.topMargin;
5739            this.rightMargin = source.rightMargin;
5740            this.bottomMargin = source.bottomMargin;
5741            this.startMargin = source.startMargin;
5742            this.endMargin = source.endMargin;
5743
5744            this.initialLeftMargin = source.leftMargin;
5745            this.initialRightMargin = source.rightMargin;
5746
5747            setLayoutDirection(source.layoutDirection);
5748        }
5749
5750        /**
5751         * {@inheritDoc}
5752         */
5753        public MarginLayoutParams(LayoutParams source) {
5754            super(source);
5755        }
5756
5757        /**
5758         * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs
5759         * to be done so that the new margins are taken into account. Left and right margins may be
5760         * overriden by {@link android.view.View#requestLayout()} depending on layout direction.
5761         *
5762         * @param left the left margin size
5763         * @param top the top margin size
5764         * @param right the right margin size
5765         * @param bottom the bottom margin size
5766         *
5767         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
5768         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5769         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
5770         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5771         */
5772        public void setMargins(int left, int top, int right, int bottom) {
5773            leftMargin = left;
5774            topMargin = top;
5775            rightMargin = right;
5776            bottomMargin = bottom;
5777            initialLeftMargin = left;
5778            initialRightMargin = right;
5779        }
5780
5781        /**
5782         * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()}
5783         * needs to be done so that the new relative margins are taken into account. Left and right
5784         * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout
5785         * direction.
5786         *
5787         * @param start the start margin size
5788         * @param top the top margin size
5789         * @param end the right margin size
5790         * @param bottom the bottom margin size
5791         *
5792         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5793         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
5794         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5795         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
5796         *
5797         * @hide
5798         */
5799        public void setMarginsRelative(int start, int top, int end, int bottom) {
5800            startMargin = start;
5801            topMargin = top;
5802            endMargin = end;
5803            bottomMargin = bottom;
5804            initialLeftMargin = 0;
5805            initialRightMargin = 0;
5806        }
5807
5808        /**
5809         * Sets the relative start margin.
5810         *
5811         * @param start the start margin size
5812         *
5813         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5814         */
5815        public void setMarginStart(int start) {
5816            startMargin = start;
5817        }
5818
5819        /**
5820         * Returns the start margin in pixels.
5821         *
5822         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5823         *
5824         * @return the start margin in pixels.
5825         */
5826        public int getMarginStart() {
5827            if (startMargin != DEFAULT_RELATIVE) return startMargin;
5828            switch(layoutDirection) {
5829                case View.LAYOUT_DIRECTION_RTL:
5830                    return rightMargin;
5831                case View.LAYOUT_DIRECTION_LTR:
5832                default:
5833                    return leftMargin;
5834            }
5835        }
5836
5837        /**
5838         * Sets the relative end margin.
5839         *
5840         * @param end the end margin size
5841         *
5842         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5843         */
5844        public void setMarginEnd(int end) {
5845            endMargin = end;
5846        }
5847
5848        /**
5849         * Returns the end margin in pixels.
5850         *
5851         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5852         *
5853         * @return the end margin in pixels.
5854         */
5855        public int getMarginEnd() {
5856            if (endMargin != DEFAULT_RELATIVE) return endMargin;
5857            switch(layoutDirection) {
5858                case View.LAYOUT_DIRECTION_RTL:
5859                    return leftMargin;
5860                case View.LAYOUT_DIRECTION_LTR:
5861                default:
5862                    return rightMargin;
5863            }
5864        }
5865
5866        /**
5867         * Check if margins are relative.
5868         *
5869         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart
5870         * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd
5871         *
5872         * @return true if either marginStart or marginEnd has been set.
5873         */
5874        public boolean isMarginRelative() {
5875            return (startMargin != DEFAULT_RELATIVE) || (endMargin != DEFAULT_RELATIVE);
5876        }
5877
5878        /**
5879         * Set the layout direction
5880         * @param layoutDirection the layout direction.
5881         *        Should be either {@link View#LAYOUT_DIRECTION_LTR}
5882         *                     or {@link View#LAYOUT_DIRECTION_RTL}.
5883         */
5884        public void setLayoutDirection(int layoutDirection) {
5885            if (layoutDirection != View.LAYOUT_DIRECTION_LTR &&
5886                    layoutDirection != View.LAYOUT_DIRECTION_RTL) return;
5887            this.layoutDirection = layoutDirection;
5888        }
5889
5890        /**
5891         * Retuns the layout direction. Can be either {@link View#LAYOUT_DIRECTION_LTR} or
5892         * {@link View#LAYOUT_DIRECTION_RTL}.
5893         *
5894         * @return the layout direction.
5895         */
5896        public int getLayoutDirection() {
5897            return layoutDirection;
5898        }
5899
5900        /**
5901         * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins
5902         * may be overridden depending on layout direction.
5903         */
5904        @Override
5905        public void onResolveLayoutDirection(int layoutDirection) {
5906            setLayoutDirection(layoutDirection);
5907
5908            if (!isMarginRelative()) return;
5909
5910            switch(layoutDirection) {
5911                case View.LAYOUT_DIRECTION_RTL:
5912                    leftMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : initialLeftMargin;
5913                    rightMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : initialRightMargin;
5914                    break;
5915                case View.LAYOUT_DIRECTION_LTR:
5916                default:
5917                    leftMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : initialLeftMargin;
5918                    rightMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : initialRightMargin;
5919                    break;
5920            }
5921        }
5922
5923        protected boolean isLayoutRtl() {
5924            return (layoutDirection == View.LAYOUT_DIRECTION_RTL);
5925        }
5926
5927        /**
5928         * @hide
5929         */
5930        @Override
5931        public void onDebugDraw(View view, Canvas canvas, Paint paint) {
5932            Insets oi = isLayoutModeOptical(view.mParent) ? view.getOpticalInsets() : Insets.NONE;
5933
5934            fillDifference(canvas,
5935                    view.getLeft()   + oi.left,
5936                    view.getTop()    + oi.top,
5937                    view.getRight()  - oi.right,
5938                    view.getBottom() - oi.bottom,
5939                    leftMargin,
5940                    topMargin,
5941                    rightMargin,
5942                    bottomMargin,
5943                    paint);
5944        }
5945    }
5946
5947    /* Describes a touched view and the ids of the pointers that it has captured.
5948     *
5949     * This code assumes that pointer ids are always in the range 0..31 such that
5950     * it can use a bitfield to track which pointer ids are present.
5951     * As it happens, the lower layers of the input dispatch pipeline also use the
5952     * same trick so the assumption should be safe here...
5953     */
5954    private static final class TouchTarget {
5955        private static final int MAX_RECYCLED = 32;
5956        private static final Object sRecycleLock = new Object();
5957        private static TouchTarget sRecycleBin;
5958        private static int sRecycledCount;
5959
5960        public static final int ALL_POINTER_IDS = -1; // all ones
5961
5962        // The touched child view.
5963        public View child;
5964
5965        // The combined bit mask of pointer ids for all pointers captured by the target.
5966        public int pointerIdBits;
5967
5968        // The next target in the target list.
5969        public TouchTarget next;
5970
5971        private TouchTarget() {
5972        }
5973
5974        public static TouchTarget obtain(View child, int pointerIdBits) {
5975            final TouchTarget target;
5976            synchronized (sRecycleLock) {
5977                if (sRecycleBin == null) {
5978                    target = new TouchTarget();
5979                } else {
5980                    target = sRecycleBin;
5981                    sRecycleBin = target.next;
5982                     sRecycledCount--;
5983                    target.next = null;
5984                }
5985            }
5986            target.child = child;
5987            target.pointerIdBits = pointerIdBits;
5988            return target;
5989        }
5990
5991        public void recycle() {
5992            synchronized (sRecycleLock) {
5993                if (sRecycledCount < MAX_RECYCLED) {
5994                    next = sRecycleBin;
5995                    sRecycleBin = this;
5996                    sRecycledCount += 1;
5997                } else {
5998                    next = null;
5999                }
6000                child = null;
6001            }
6002        }
6003    }
6004
6005    /* Describes a hovered view. */
6006    private static final class HoverTarget {
6007        private static final int MAX_RECYCLED = 32;
6008        private static final Object sRecycleLock = new Object();
6009        private static HoverTarget sRecycleBin;
6010        private static int sRecycledCount;
6011
6012        // The hovered child view.
6013        public View child;
6014
6015        // The next target in the target list.
6016        public HoverTarget next;
6017
6018        private HoverTarget() {
6019        }
6020
6021        public static HoverTarget obtain(View child) {
6022            final HoverTarget target;
6023            synchronized (sRecycleLock) {
6024                if (sRecycleBin == null) {
6025                    target = new HoverTarget();
6026                } else {
6027                    target = sRecycleBin;
6028                    sRecycleBin = target.next;
6029                     sRecycledCount--;
6030                    target.next = null;
6031                }
6032            }
6033            target.child = child;
6034            return target;
6035        }
6036
6037        public void recycle() {
6038            synchronized (sRecycleLock) {
6039                if (sRecycledCount < MAX_RECYCLED) {
6040                    next = sRecycleBin;
6041                    sRecycleBin = this;
6042                    sRecycledCount += 1;
6043                } else {
6044                    next = null;
6045                }
6046                child = null;
6047            }
6048        }
6049    }
6050
6051    /**
6052     * Pooled class that orderes the children of a ViewGroup from start
6053     * to end based on how they are laid out and the layout direction.
6054     */
6055    static class ChildListForAccessibility {
6056
6057        private static final int MAX_POOL_SIZE = 32;
6058
6059        private static final Object sPoolLock = new Object();
6060
6061        private static ChildListForAccessibility sPool;
6062
6063        private static int sPoolSize;
6064
6065        private boolean mIsPooled;
6066
6067        private ChildListForAccessibility mNext;
6068
6069        private final ArrayList<View> mChildren = new ArrayList<View>();
6070
6071        private final ArrayList<ViewLocationHolder> mHolders = new ArrayList<ViewLocationHolder>();
6072
6073        public static ChildListForAccessibility obtain(ViewGroup parent, boolean sort) {
6074            ChildListForAccessibility list = null;
6075            synchronized (sPoolLock) {
6076                if (sPool != null) {
6077                    list = sPool;
6078                    sPool = list.mNext;
6079                    list.mNext = null;
6080                    list.mIsPooled = false;
6081                    sPoolSize--;
6082                } else {
6083                    list = new ChildListForAccessibility();
6084                }
6085                list.init(parent, sort);
6086                return list;
6087            }
6088        }
6089
6090        public void recycle() {
6091            if (mIsPooled) {
6092                throw new IllegalStateException("Instance already recycled.");
6093            }
6094            clear();
6095            synchronized (sPoolLock) {
6096                if (sPoolSize < MAX_POOL_SIZE) {
6097                    mNext = sPool;
6098                    mIsPooled = true;
6099                    sPool = this;
6100                    sPoolSize++;
6101                }
6102            }
6103        }
6104
6105        public int getChildCount() {
6106            return mChildren.size();
6107        }
6108
6109        public View getChildAt(int index) {
6110            return mChildren.get(index);
6111        }
6112
6113        public int getChildIndex(View child) {
6114            return mChildren.indexOf(child);
6115        }
6116
6117        private void init(ViewGroup parent, boolean sort) {
6118            ArrayList<View> children = mChildren;
6119            final int childCount = parent.getChildCount();
6120            for (int i = 0; i < childCount; i++) {
6121                View child = parent.getChildAt(i);
6122                children.add(child);
6123            }
6124            if (sort) {
6125                ArrayList<ViewLocationHolder> holders = mHolders;
6126                for (int i = 0; i < childCount; i++) {
6127                    View child = children.get(i);
6128                    ViewLocationHolder holder = ViewLocationHolder.obtain(parent, child);
6129                    holders.add(holder);
6130                }
6131                Collections.sort(holders);
6132                for (int i = 0; i < childCount; i++) {
6133                    ViewLocationHolder holder = holders.get(i);
6134                    children.set(i, holder.mView);
6135                    holder.recycle();
6136                }
6137                holders.clear();
6138            }
6139        }
6140
6141        private void clear() {
6142            mChildren.clear();
6143        }
6144    }
6145
6146    /**
6147     * Pooled class that holds a View and its location with respect to
6148     * a specified root. This enables sorting of views based on their
6149     * coordinates without recomputing the position relative to the root
6150     * on every comparison.
6151     */
6152    static class ViewLocationHolder implements Comparable<ViewLocationHolder> {
6153
6154        private static final int MAX_POOL_SIZE = 32;
6155
6156        private static final Object sPoolLock = new Object();
6157
6158        private static ViewLocationHolder sPool;
6159
6160        private static int sPoolSize;
6161
6162        private boolean mIsPooled;
6163
6164        private ViewLocationHolder mNext;
6165
6166        private final Rect mLocation = new Rect();
6167
6168        public View mView;
6169
6170        private int mLayoutDirection;
6171
6172        public static ViewLocationHolder obtain(ViewGroup root, View view) {
6173            ViewLocationHolder holder = null;
6174            synchronized (sPoolLock) {
6175                if (sPool != null) {
6176                    holder = sPool;
6177                    sPool = holder.mNext;
6178                    holder.mNext = null;
6179                    holder.mIsPooled = false;
6180                    sPoolSize--;
6181                } else {
6182                    holder = new ViewLocationHolder();
6183                }
6184                holder.init(root, view);
6185                return holder;
6186            }
6187        }
6188
6189        public void recycle() {
6190            if (mIsPooled) {
6191                throw new IllegalStateException("Instance already recycled.");
6192            }
6193            clear();
6194            synchronized (sPoolLock) {
6195                if (sPoolSize < MAX_POOL_SIZE) {
6196                    mNext = sPool;
6197                    mIsPooled = true;
6198                    sPool = this;
6199                    sPoolSize++;
6200                }
6201            }
6202        }
6203
6204        @Override
6205        public int compareTo(ViewLocationHolder another) {
6206            // This instance is greater than an invalid argument.
6207            if (another == null) {
6208                return 1;
6209            }
6210            if (getClass() != another.getClass()) {
6211                return 1;
6212            }
6213            // First is above second.
6214            if (mLocation.bottom - another.mLocation.top <= 0) {
6215                return -1;
6216            }
6217            // First is below second.
6218            if (mLocation.top - another.mLocation.bottom >= 0) {
6219                return 1;
6220            }
6221            // LTR
6222            if (mLayoutDirection == LAYOUT_DIRECTION_LTR) {
6223                final int leftDifference = mLocation.left - another.mLocation.left;
6224                // First more to the left than second.
6225                if (leftDifference != 0) {
6226                    return leftDifference;
6227                }
6228            } else { // RTL
6229                final int rightDifference = mLocation.right - another.mLocation.right;
6230                // First more to the right than second.
6231                if (rightDifference != 0) {
6232                    return -rightDifference;
6233                }
6234            }
6235            // Break tie by top.
6236            final int topDiference = mLocation.top - another.mLocation.top;
6237            if (topDiference != 0) {
6238                return topDiference;
6239            }
6240            // Break tie by height.
6241            final int heightDiference = mLocation.height() - another.mLocation.height();
6242            if (heightDiference != 0) {
6243                return -heightDiference;
6244            }
6245            // Break tie by width.
6246            final int widthDiference = mLocation.width() - another.mLocation.width();
6247            if (widthDiference != 0) {
6248                return -widthDiference;
6249            }
6250            // Just break the tie somehow. The accessibliity ids are unique
6251            // and stable, hence this is deterministic tie breaking.
6252            return mView.getAccessibilityViewId() - another.mView.getAccessibilityViewId();
6253        }
6254
6255        private void init(ViewGroup root, View view) {
6256            Rect viewLocation = mLocation;
6257            view.getDrawingRect(viewLocation);
6258            root.offsetDescendantRectToMyCoords(view, viewLocation);
6259            mView = view;
6260            mLayoutDirection = root.getLayoutDirection();
6261        }
6262
6263        private void clear() {
6264            mView = null;
6265            mLocation.set(0, 0, 0, 0);
6266        }
6267    }
6268
6269    private static Paint getDebugPaint() {
6270        if (sDebugPaint == null) {
6271            sDebugPaint = new Paint();
6272            sDebugPaint.setAntiAlias(false);
6273        }
6274        return sDebugPaint;
6275    }
6276
6277    private void drawRect(Canvas canvas, Paint paint, int x1, int y1, int x2, int y2) {
6278        if (sDebugLines== null) {
6279            sDebugLines = new float[16];
6280        }
6281
6282        sDebugLines[0] = x1;
6283        sDebugLines[1] = y1;
6284        sDebugLines[2] = x2;
6285        sDebugLines[3] = y1;
6286
6287        sDebugLines[4] = x2;
6288        sDebugLines[5] = y1;
6289        sDebugLines[6] = x2;
6290        sDebugLines[7] = y2;
6291
6292        sDebugLines[8] = x2;
6293        sDebugLines[9] = y2;
6294        sDebugLines[10] = x1;
6295        sDebugLines[11] = y2;
6296
6297        sDebugLines[12] = x1;
6298        sDebugLines[13] = y2;
6299        sDebugLines[14] = x1;
6300        sDebugLines[15] = y1;
6301
6302        canvas.drawLines(sDebugLines, paint);
6303    }
6304}
6305