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