blob: 12c49c4fad6378c42fed56fdb05fb7fec7bceb6a [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
Chet Haase21cd1382010-09-01 17:42:29 -070019import android.animation.LayoutTransition;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.R;
21
22import android.content.Context;
Dianne Hackborne36d6e22010-02-17 19:46:25 -080023import android.content.res.Configuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.res.TypedArray;
25import android.graphics.Bitmap;
26import android.graphics.Canvas;
Adam Powell6e346362010-07-23 10:18:23 -070027import android.graphics.Matrix;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.graphics.Paint;
29import android.graphics.Rect;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.graphics.RectF;
svetoslavganov75986cf2009-05-14 22:28:01 -070031import android.graphics.Region;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.os.Parcelable;
33import android.os.SystemClock;
34import android.util.AttributeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.util.Log;
36import android.util.SparseArray;
svetoslavganov75986cf2009-05-14 22:28:01 -070037import android.view.accessibility.AccessibilityEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.view.animation.Animation;
39import android.view.animation.AnimationUtils;
40import android.view.animation.LayoutAnimationController;
41import android.view.animation.Transformation;
42
43import java.util.ArrayList;
44
45/**
46 * <p>
47 * A <code>ViewGroup</code> is a special view that can contain other views
48 * (called children.) The view group is the base class for layouts and views
49 * containers. This class also defines the
50 * {@link android.view.ViewGroup.LayoutParams} class which serves as the base
51 * class for layouts parameters.
52 * </p>
53 *
54 * <p>
55 * Also see {@link LayoutParams} for layout attributes.
56 * </p>
Romain Guyd6a463a2009-05-21 23:10:10 -070057 *
58 * @attr ref android.R.styleable#ViewGroup_clipChildren
59 * @attr ref android.R.styleable#ViewGroup_clipToPadding
60 * @attr ref android.R.styleable#ViewGroup_layoutAnimation
61 * @attr ref android.R.styleable#ViewGroup_animationCache
62 * @attr ref android.R.styleable#ViewGroup_persistentDrawingCache
63 * @attr ref android.R.styleable#ViewGroup_alwaysDrawnWithCache
64 * @attr ref android.R.styleable#ViewGroup_addStatesFromChildren
65 * @attr ref android.R.styleable#ViewGroup_descendantFocusability
Chet Haase13cc1202010-09-03 15:39:20 -070066 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 */
68public abstract class ViewGroup extends View implements ViewParent, ViewManager {
Chet Haase21cd1382010-09-01 17:42:29 -070069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070 private static final boolean DBG = false;
71
72 /**
73 * Views which have been hidden or removed which need to be animated on
74 * their way out.
75 * This field should be made private, so it is hidden from the SDK.
76 * {@hide}
77 */
78 protected ArrayList<View> mDisappearingChildren;
79
80 /**
81 * Listener used to propagate events indicating when children are added
82 * and/or removed from a view group.
83 * This field should be made private, so it is hidden from the SDK.
84 * {@hide}
85 */
86 protected OnHierarchyChangeListener mOnHierarchyChangeListener;
87
88 // The view contained within this ViewGroup that has or contains focus.
89 private View mFocused;
90
Chet Haase48460322010-06-11 14:22:25 -070091 /**
92 * A Transformation used when drawing children, to
93 * apply on the child being drawn.
94 */
95 private final Transformation mChildTransformation = new Transformation();
96
97 /**
98 * Used to track the current invalidation region.
99 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private RectF mInvalidateRegion;
101
Chet Haase48460322010-06-11 14:22:25 -0700102 /**
103 * A Transformation used to calculate a correct
104 * invalidation area when the application is autoscaled.
105 */
106 private Transformation mInvalidationTransformation;
107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 // Target of Motion events
109 private View mMotionTarget;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Adam Powell2b342f02010-08-18 18:14:13 -0700111 // Targets of MotionEvents in split mode
112 private SplitMotionTargets mSplitMotionTargets;
113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 // Layout animation
115 private LayoutAnimationController mLayoutAnimationController;
116 private Animation.AnimationListener mAnimationListener;
117
118 /**
119 * Internal flags.
Romain Guy8506ab42009-06-11 17:35:47 -0700120 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * This field should be made private, so it is hidden from the SDK.
122 * {@hide}
123 */
124 protected int mGroupFlags;
125
126 // When set, ViewGroup invalidates only the child's rectangle
127 // Set by default
128 private static final int FLAG_CLIP_CHILDREN = 0x1;
129
130 // When set, ViewGroup excludes the padding area from the invalidate rectangle
131 // Set by default
132 private static final int FLAG_CLIP_TO_PADDING = 0x2;
133
134 // When set, dispatchDraw() will invoke invalidate(); this is set by drawChild() when
135 // a child needs to be invalidated and FLAG_OPTIMIZE_INVALIDATE is set
136 private static final int FLAG_INVALIDATE_REQUIRED = 0x4;
137
138 // When set, dispatchDraw() will run the layout animation and unset the flag
139 private static final int FLAG_RUN_ANIMATION = 0x8;
140
141 // When set, there is either no layout animation on the ViewGroup or the layout
142 // animation is over
143 // Set by default
144 private static final int FLAG_ANIMATION_DONE = 0x10;
145
146 // If set, this ViewGroup has padding; if unset there is no padding and we don't need
147 // to clip it, even if FLAG_CLIP_TO_PADDING is set
148 private static final int FLAG_PADDING_NOT_NULL = 0x20;
149
150 // When set, this ViewGroup caches its children in a Bitmap before starting a layout animation
151 // Set by default
152 private static final int FLAG_ANIMATION_CACHE = 0x40;
153
154 // When set, this ViewGroup converts calls to invalidate(Rect) to invalidate() during a
155 // layout animation; this avoid clobbering the hierarchy
156 // Automatically set when the layout animation starts, depending on the animation's
157 // characteristics
158 private static final int FLAG_OPTIMIZE_INVALIDATE = 0x80;
159
160 // When set, the next call to drawChild() will clear mChildTransformation's matrix
161 private static final int FLAG_CLEAR_TRANSFORMATION = 0x100;
162
163 // When set, this ViewGroup invokes mAnimationListener.onAnimationEnd() and removes
164 // the children's Bitmap caches if necessary
165 // This flag is set when the layout animation is over (after FLAG_ANIMATION_DONE is set)
166 private static final int FLAG_NOTIFY_ANIMATION_LISTENER = 0x200;
167
168 /**
169 * When set, the drawing method will call {@link #getChildDrawingOrder(int, int)}
170 * to get the index of the child to draw for that iteration.
Romain Guy293451e2009-11-04 13:59:48 -0800171 *
172 * @hide
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 */
174 protected static final int FLAG_USE_CHILD_DRAWING_ORDER = 0x400;
Romain Guy8506ab42009-06-11 17:35:47 -0700175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 /**
177 * When set, this ViewGroup supports static transformations on children; this causes
178 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
179 * invoked when a child is drawn.
180 *
181 * Any subclass overriding
182 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
183 * set this flags in {@link #mGroupFlags}.
Romain Guy8506ab42009-06-11 17:35:47 -0700184 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185 * {@hide}
186 */
187 protected static final int FLAG_SUPPORT_STATIC_TRANSFORMATIONS = 0x800;
188
189 // When the previous drawChild() invocation used an alpha value that was lower than
190 // 1.0 and set it in mCachePaint
191 private static final int FLAG_ALPHA_LOWER_THAN_ONE = 0x1000;
192
193 /**
194 * When set, this ViewGroup's drawable states also include those
195 * of its children.
196 */
197 private static final int FLAG_ADD_STATES_FROM_CHILDREN = 0x2000;
198
199 /**
200 * When set, this ViewGroup tries to always draw its children using their drawing cache.
201 */
202 private static final int FLAG_ALWAYS_DRAWN_WITH_CACHE = 0x4000;
203
204 /**
205 * When set, and if FLAG_ALWAYS_DRAWN_WITH_CACHE is not set, this ViewGroup will try to
206 * draw its children with their drawing cache.
207 */
208 private static final int FLAG_CHILDREN_DRAWN_WITH_CACHE = 0x8000;
209
210 /**
211 * When set, this group will go through its list of children to notify them of
212 * any drawable state change.
213 */
214 private static final int FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE = 0x10000;
215
216 private static final int FLAG_MASK_FOCUSABILITY = 0x60000;
217
218 /**
219 * This view will get focus before any of its descendants.
220 */
221 public static final int FOCUS_BEFORE_DESCENDANTS = 0x20000;
222
223 /**
224 * This view will get focus only if none of its descendants want it.
225 */
226 public static final int FOCUS_AFTER_DESCENDANTS = 0x40000;
227
228 /**
229 * This view will block any of its descendants from getting focus, even
230 * if they are focusable.
231 */
232 public static final int FOCUS_BLOCK_DESCENDANTS = 0x60000;
233
234 /**
235 * Used to map between enum in attrubutes and flag values.
236 */
237 private static final int[] DESCENDANT_FOCUSABILITY_FLAGS =
238 {FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS,
239 FOCUS_BLOCK_DESCENDANTS};
240
241 /**
242 * When set, this ViewGroup should not intercept touch events.
Adam Powell110486f2010-06-22 17:14:44 -0700243 * {@hide}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 */
Adam Powell110486f2010-06-22 17:14:44 -0700245 protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000;
Romain Guy8506ab42009-06-11 17:35:47 -0700246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 /**
Adam Powell2b342f02010-08-18 18:14:13 -0700248 * When set, this ViewGroup will split MotionEvents to multiple child Views when appropriate.
249 */
Adam Powellf37df072010-09-17 16:22:49 -0700250 private static final int FLAG_SPLIT_MOTION_EVENTS = 0x200000;
Adam Powell2b342f02010-08-18 18:14:13 -0700251
252 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 * Indicates which types of drawing caches are to be kept in memory.
254 * This field should be made private, so it is hidden from the SDK.
255 * {@hide}
256 */
257 protected int mPersistentDrawingCache;
258
259 /**
260 * Used to indicate that no drawing cache should be kept in memory.
261 */
262 public static final int PERSISTENT_NO_CACHE = 0x0;
263
264 /**
265 * Used to indicate that the animation drawing cache should be kept in memory.
266 */
267 public static final int PERSISTENT_ANIMATION_CACHE = 0x1;
268
269 /**
270 * Used to indicate that the scrolling drawing cache should be kept in memory.
271 */
272 public static final int PERSISTENT_SCROLLING_CACHE = 0x2;
273
274 /**
275 * Used to indicate that all drawing caches should be kept in memory.
276 */
277 public static final int PERSISTENT_ALL_CACHES = 0x3;
278
279 /**
280 * We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL
281 * are set at the same time.
282 */
283 protected static final int CLIP_TO_PADDING_MASK = FLAG_CLIP_TO_PADDING | FLAG_PADDING_NOT_NULL;
284
285 // Index of the child's left position in the mLocation array
286 private static final int CHILD_LEFT_INDEX = 0;
287 // Index of the child's top position in the mLocation array
288 private static final int CHILD_TOP_INDEX = 1;
289
290 // Child views of this ViewGroup
291 private View[] mChildren;
292 // Number of valid children in the mChildren array, the rest should be null or not
293 // considered as children
294 private int mChildrenCount;
295
296 private static final int ARRAY_INITIAL_CAPACITY = 12;
297 private static final int ARRAY_CAPACITY_INCREMENT = 12;
298
299 // Used to draw cached views
300 private final Paint mCachePaint = new Paint();
301
Chet Haase21cd1382010-09-01 17:42:29 -0700302 // Used to animate add/remove changes in layout
303 private LayoutTransition mTransition;
304
305 // The set of views that are currently being transitioned. This list is used to track views
306 // being removed that should not actually be removed from the parent yet because they are
307 // being animated.
308 private ArrayList<View> mTransitioningViews;
309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 public ViewGroup(Context context) {
311 super(context);
312 initViewGroup();
313 }
314
315 public ViewGroup(Context context, AttributeSet attrs) {
316 super(context, attrs);
317 initViewGroup();
318 initFromAttributes(context, attrs);
319 }
320
321 public ViewGroup(Context context, AttributeSet attrs, int defStyle) {
322 super(context, attrs, defStyle);
323 initViewGroup();
324 initFromAttributes(context, attrs);
325 }
326
327 private void initViewGroup() {
328 // ViewGroup doesn't draw by default
329 setFlags(WILL_NOT_DRAW, DRAW_MASK);
330 mGroupFlags |= FLAG_CLIP_CHILDREN;
331 mGroupFlags |= FLAG_CLIP_TO_PADDING;
332 mGroupFlags |= FLAG_ANIMATION_DONE;
333 mGroupFlags |= FLAG_ANIMATION_CACHE;
334 mGroupFlags |= FLAG_ALWAYS_DRAWN_WITH_CACHE;
335
336 setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS);
337
338 mChildren = new View[ARRAY_INITIAL_CAPACITY];
339 mChildrenCount = 0;
340
341 mCachePaint.setDither(false);
342
343 mPersistentDrawingCache = PERSISTENT_SCROLLING_CACHE;
344 }
345
346 private void initFromAttributes(Context context, AttributeSet attrs) {
347 TypedArray a = context.obtainStyledAttributes(attrs,
348 R.styleable.ViewGroup);
349
350 final int N = a.getIndexCount();
351 for (int i = 0; i < N; i++) {
352 int attr = a.getIndex(i);
353 switch (attr) {
354 case R.styleable.ViewGroup_clipChildren:
355 setClipChildren(a.getBoolean(attr, true));
356 break;
357 case R.styleable.ViewGroup_clipToPadding:
358 setClipToPadding(a.getBoolean(attr, true));
359 break;
360 case R.styleable.ViewGroup_animationCache:
361 setAnimationCacheEnabled(a.getBoolean(attr, true));
362 break;
363 case R.styleable.ViewGroup_persistentDrawingCache:
364 setPersistentDrawingCache(a.getInt(attr, PERSISTENT_SCROLLING_CACHE));
365 break;
366 case R.styleable.ViewGroup_addStatesFromChildren:
367 setAddStatesFromChildren(a.getBoolean(attr, false));
368 break;
369 case R.styleable.ViewGroup_alwaysDrawnWithCache:
370 setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true));
371 break;
372 case R.styleable.ViewGroup_layoutAnimation:
373 int id = a.getResourceId(attr, -1);
374 if (id > 0) {
375 setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id));
376 }
377 break;
378 case R.styleable.ViewGroup_descendantFocusability:
379 setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]);
380 break;
Adam Powell2b342f02010-08-18 18:14:13 -0700381 case R.styleable.ViewGroup_splitMotionEvents:
382 setMotionEventSplittingEnabled(a.getBoolean(attr, false));
383 break;
Chet Haase13cc1202010-09-03 15:39:20 -0700384 case R.styleable.ViewGroup_animateLayoutChanges:
385 boolean animateLayoutChanges = a.getBoolean(attr, false);
386 if (animateLayoutChanges) {
387 setLayoutTransition(new LayoutTransition());
388 }
389 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 }
391 }
392
393 a.recycle();
394 }
395
396 /**
397 * Gets the descendant focusability of this view group. The descendant
398 * focusability defines the relationship between this view group and its
399 * descendants when looking for a view to take focus in
400 * {@link #requestFocus(int, android.graphics.Rect)}.
401 *
402 * @return one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
403 * {@link #FOCUS_BLOCK_DESCENDANTS}.
404 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -0700405 @ViewDebug.ExportedProperty(category = "focus", mapping = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 @ViewDebug.IntToString(from = FOCUS_BEFORE_DESCENDANTS, to = "FOCUS_BEFORE_DESCENDANTS"),
407 @ViewDebug.IntToString(from = FOCUS_AFTER_DESCENDANTS, to = "FOCUS_AFTER_DESCENDANTS"),
408 @ViewDebug.IntToString(from = FOCUS_BLOCK_DESCENDANTS, to = "FOCUS_BLOCK_DESCENDANTS")
409 })
410 public int getDescendantFocusability() {
411 return mGroupFlags & FLAG_MASK_FOCUSABILITY;
412 }
413
414 /**
415 * Set the descendant focusability of this view group. This defines the relationship
416 * between this view group and its descendants when looking for a view to
417 * take focus in {@link #requestFocus(int, android.graphics.Rect)}.
418 *
419 * @param focusability one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS},
420 * {@link #FOCUS_BLOCK_DESCENDANTS}.
421 */
422 public void setDescendantFocusability(int focusability) {
423 switch (focusability) {
424 case FOCUS_BEFORE_DESCENDANTS:
425 case FOCUS_AFTER_DESCENDANTS:
426 case FOCUS_BLOCK_DESCENDANTS:
427 break;
428 default:
429 throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, "
430 + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS");
431 }
432 mGroupFlags &= ~FLAG_MASK_FOCUSABILITY;
433 mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY);
434 }
435
436 /**
437 * {@inheritDoc}
438 */
439 @Override
440 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) {
441 if (mFocused != null) {
442 mFocused.unFocus();
443 mFocused = null;
444 }
445 super.handleFocusGainInternal(direction, previouslyFocusedRect);
446 }
447
448 /**
449 * {@inheritDoc}
450 */
451 public void requestChildFocus(View child, View focused) {
452 if (DBG) {
453 System.out.println(this + " requestChildFocus()");
454 }
455 if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) {
456 return;
457 }
458
459 // Unfocus us, if necessary
460 super.unFocus();
461
462 // We had a previous notion of who had focus. Clear it.
463 if (mFocused != child) {
464 if (mFocused != null) {
465 mFocused.unFocus();
466 }
467
468 mFocused = child;
469 }
470 if (mParent != null) {
471 mParent.requestChildFocus(this, focused);
472 }
473 }
474
475 /**
476 * {@inheritDoc}
477 */
478 public void focusableViewAvailable(View v) {
479 if (mParent != null
480 // shortcut: don't report a new focusable view if we block our descendants from
481 // getting focus
482 && (getDescendantFocusability() != FOCUS_BLOCK_DESCENDANTS)
483 // shortcut: don't report a new focusable view if we already are focused
484 // (and we don't prefer our descendants)
485 //
486 // note: knowing that mFocused is non-null is not a good enough reason
487 // to break the traversal since in that case we'd actually have to find
488 // the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and
489 // an ancestor of v; this will get checked for at ViewRoot
490 && !(isFocused() && getDescendantFocusability() != FOCUS_AFTER_DESCENDANTS)) {
491 mParent.focusableViewAvailable(v);
492 }
493 }
494
495 /**
496 * {@inheritDoc}
497 */
498 public boolean showContextMenuForChild(View originalView) {
499 return mParent != null && mParent.showContextMenuForChild(originalView);
500 }
501
502 /**
Adam Powell6e346362010-07-23 10:18:23 -0700503 * {@inheritDoc}
504 */
505 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) {
506 return mParent != null ? mParent.startActionModeForChild(originalView, callback) : null;
507 }
508
509 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 * Find the nearest view in the specified direction that wants to take
511 * focus.
512 *
513 * @param focused The view that currently has focus
514 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and
515 * FOCUS_RIGHT, or 0 for not applicable.
516 */
517 public View focusSearch(View focused, int direction) {
518 if (isRootNamespace()) {
519 // root namespace means we should consider ourselves the top of the
520 // tree for focus searching; otherwise we could be focus searching
521 // into other tabs. see LocalActivityManager and TabHost for more info
522 return FocusFinder.getInstance().findNextFocus(this, focused, direction);
523 } else if (mParent != null) {
524 return mParent.focusSearch(focused, direction);
525 }
526 return null;
527 }
528
529 /**
530 * {@inheritDoc}
531 */
532 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
533 return false;
534 }
535
536 /**
537 * {@inheritDoc}
538 */
539 @Override
540 public boolean dispatchUnhandledMove(View focused, int direction) {
541 return mFocused != null &&
542 mFocused.dispatchUnhandledMove(focused, direction);
543 }
544
545 /**
546 * {@inheritDoc}
547 */
548 public void clearChildFocus(View child) {
549 if (DBG) {
550 System.out.println(this + " clearChildFocus()");
551 }
552
553 mFocused = null;
554 if (mParent != null) {
555 mParent.clearChildFocus(this);
556 }
557 }
558
559 /**
560 * {@inheritDoc}
561 */
562 @Override
563 public void clearFocus() {
564 super.clearFocus();
565
566 // clear any child focus if it exists
567 if (mFocused != null) {
568 mFocused.clearFocus();
569 }
570 }
571
572 /**
573 * {@inheritDoc}
574 */
575 @Override
576 void unFocus() {
577 if (DBG) {
578 System.out.println(this + " unFocus()");
579 }
580
581 super.unFocus();
582 if (mFocused != null) {
583 mFocused.unFocus();
584 }
585 mFocused = null;
586 }
587
588 /**
589 * Returns the focused child of this view, if any. The child may have focus
590 * or contain focus.
591 *
592 * @return the focused child or null.
593 */
594 public View getFocusedChild() {
595 return mFocused;
596 }
597
598 /**
599 * Returns true if this view has or contains focus
600 *
601 * @return true if this view has or contains focus
602 */
603 @Override
604 public boolean hasFocus() {
605 return (mPrivateFlags & FOCUSED) != 0 || mFocused != null;
606 }
607
608 /*
609 * (non-Javadoc)
610 *
611 * @see android.view.View#findFocus()
612 */
613 @Override
614 public View findFocus() {
615 if (DBG) {
616 System.out.println("Find focus in " + this + ": flags="
617 + isFocused() + ", child=" + mFocused);
618 }
619
620 if (isFocused()) {
621 return this;
622 }
623
624 if (mFocused != null) {
625 return mFocused.findFocus();
626 }
627 return null;
628 }
629
630 /**
631 * {@inheritDoc}
632 */
633 @Override
634 public boolean hasFocusable() {
635 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
636 return false;
637 }
638
639 if (isFocusable()) {
640 return true;
641 }
642
643 final int descendantFocusability = getDescendantFocusability();
644 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
645 final int count = mChildrenCount;
646 final View[] children = mChildren;
647
648 for (int i = 0; i < count; i++) {
649 final View child = children[i];
650 if (child.hasFocusable()) {
651 return true;
652 }
653 }
654 }
655
656 return false;
657 }
658
659 /**
660 * {@inheritDoc}
661 */
662 @Override
663 public void addFocusables(ArrayList<View> views, int direction) {
svetoslavganov75986cf2009-05-14 22:28:01 -0700664 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE);
665 }
666
667 /**
668 * {@inheritDoc}
669 */
670 @Override
671 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 final int focusableCount = views.size();
673
674 final int descendantFocusability = getDescendantFocusability();
675
676 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
677 final int count = mChildrenCount;
678 final View[] children = mChildren;
679
680 for (int i = 0; i < count; i++) {
681 final View child = children[i];
682 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
svetoslavganov75986cf2009-05-14 22:28:01 -0700683 child.addFocusables(views, direction, focusableMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
685 }
686 }
687
688 // we add ourselves (if focusable) in all cases except for when we are
689 // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is
690 // to avoid the focus search finding layouts when a more precise search
691 // among the focusable children would be more interesting.
692 if (
693 descendantFocusability != FOCUS_AFTER_DESCENDANTS ||
694 // No focusable descendants
695 (focusableCount == views.size())) {
svetoslavganov75986cf2009-05-14 22:28:01 -0700696 super.addFocusables(views, direction, focusableMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 }
698 }
699
700 /**
701 * {@inheritDoc}
702 */
703 @Override
704 public void dispatchWindowFocusChanged(boolean hasFocus) {
705 super.dispatchWindowFocusChanged(hasFocus);
706 final int count = mChildrenCount;
707 final View[] children = mChildren;
708 for (int i = 0; i < count; i++) {
709 children[i].dispatchWindowFocusChanged(hasFocus);
710 }
711 }
712
713 /**
714 * {@inheritDoc}
715 */
716 @Override
717 public void addTouchables(ArrayList<View> views) {
718 super.addTouchables(views);
719
720 final int count = mChildrenCount;
721 final View[] children = mChildren;
722
723 for (int i = 0; i < count; i++) {
724 final View child = children[i];
725 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
726 child.addTouchables(views);
727 }
728 }
729 }
Romain Guy43c9cdf2010-01-27 13:53:55 -0800730
731 /**
732 * {@inheritDoc}
733 */
734 @Override
735 public void dispatchDisplayHint(int hint) {
736 super.dispatchDisplayHint(hint);
737 final int count = mChildrenCount;
738 final View[] children = mChildren;
739 for (int i = 0; i < count; i++) {
740 children[i].dispatchDisplayHint(hint);
741 }
742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743
744 /**
745 * {@inheritDoc}
746 */
747 @Override
Adam Powell326d8082009-12-09 15:10:07 -0800748 protected void dispatchVisibilityChanged(View changedView, int visibility) {
749 super.dispatchVisibilityChanged(changedView, visibility);
750 final int count = mChildrenCount;
751 final View[] children = mChildren;
752 for (int i = 0; i < count; i++) {
753 children[i].dispatchVisibilityChanged(changedView, visibility);
754 }
755 }
756
757 /**
758 * {@inheritDoc}
759 */
760 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 public void dispatchWindowVisibilityChanged(int visibility) {
762 super.dispatchWindowVisibilityChanged(visibility);
763 final int count = mChildrenCount;
764 final View[] children = mChildren;
765 for (int i = 0; i < count; i++) {
766 children[i].dispatchWindowVisibilityChanged(visibility);
767 }
768 }
769
770 /**
771 * {@inheritDoc}
772 */
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800773 @Override
774 public void dispatchConfigurationChanged(Configuration newConfig) {
775 super.dispatchConfigurationChanged(newConfig);
776 final int count = mChildrenCount;
777 final View[] children = mChildren;
778 for (int i = 0; i < count; i++) {
779 children[i].dispatchConfigurationChanged(newConfig);
780 }
781 }
782
783 /**
784 * {@inheritDoc}
785 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 public void recomputeViewAttributes(View child) {
787 ViewParent parent = mParent;
788 if (parent != null) parent.recomputeViewAttributes(this);
789 }
Romain Guy8506ab42009-06-11 17:35:47 -0700790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 @Override
792 void dispatchCollectViewAttributes(int visibility) {
793 visibility |= mViewFlags&VISIBILITY_MASK;
794 super.dispatchCollectViewAttributes(visibility);
795 final int count = mChildrenCount;
796 final View[] children = mChildren;
797 for (int i = 0; i < count; i++) {
798 children[i].dispatchCollectViewAttributes(visibility);
799 }
800 }
801
802 /**
803 * {@inheritDoc}
804 */
805 public void bringChildToFront(View child) {
806 int index = indexOfChild(child);
807 if (index >= 0) {
808 removeFromArray(index);
809 addInArray(child, mChildrenCount);
810 child.mParent = this;
811 }
812 }
813
814 /**
815 * {@inheritDoc}
816 */
817 @Override
818 public boolean dispatchKeyEventPreIme(KeyEvent event) {
819 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
820 return super.dispatchKeyEventPreIme(event);
821 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
822 return mFocused.dispatchKeyEventPreIme(event);
823 }
824 return false;
825 }
826
827 /**
828 * {@inheritDoc}
829 */
830 @Override
831 public boolean dispatchKeyEvent(KeyEvent event) {
832 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
833 return super.dispatchKeyEvent(event);
834 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
835 return mFocused.dispatchKeyEvent(event);
836 }
837 return false;
838 }
839
840 /**
841 * {@inheritDoc}
842 */
843 @Override
844 public boolean dispatchKeyShortcutEvent(KeyEvent event) {
845 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
846 return super.dispatchKeyShortcutEvent(event);
847 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
848 return mFocused.dispatchKeyShortcutEvent(event);
849 }
850 return false;
851 }
852
853 /**
854 * {@inheritDoc}
855 */
856 @Override
857 public boolean dispatchTrackballEvent(MotionEvent event) {
858 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) {
859 return super.dispatchTrackballEvent(event);
860 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) {
861 return mFocused.dispatchTrackballEvent(event);
862 }
863 return false;
864 }
865
866 /**
867 * {@inheritDoc}
868 */
869 @Override
870 public boolean dispatchTouchEvent(MotionEvent ev) {
Jeff Brown85a31762010-09-01 17:01:00 -0700871 if (!onFilterTouchEventForSecurity(ev)) {
872 return false;
873 }
874
Adam Powell2b342f02010-08-18 18:14:13 -0700875 if ((mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS) {
Adam Powell816c3be2010-08-23 18:00:05 -0700876 if (mSplitMotionTargets == null) {
877 mSplitMotionTargets = new SplitMotionTargets();
878 }
Adam Powell2b342f02010-08-18 18:14:13 -0700879 return dispatchSplitTouchEvent(ev);
Adam Powell167bc822010-09-13 18:11:08 -0700880 }
Adam Powell2b342f02010-08-18 18:14:13 -0700881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 final int action = ev.getAction();
883 final float xf = ev.getX();
884 final float yf = ev.getY();
885 final float scrolledXFloat = xf + mScrollX;
886 final float scrolledYFloat = yf + mScrollY;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887
888 boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
889
890 if (action == MotionEvent.ACTION_DOWN) {
891 if (mMotionTarget != null) {
892 // this is weird, we got a pen down, but we thought it was
893 // already down!
894 // XXX: We should probably send an ACTION_UP to the current
895 // target.
896 mMotionTarget = null;
897 }
898 // If we're disallowing intercept or if we're allowing and we didn't
899 // intercept
900 if (disallowIntercept || !onInterceptTouchEvent(ev)) {
901 // reset this event's action (just to protect ourselves)
902 ev.setAction(MotionEvent.ACTION_DOWN);
903 // We know we want to dispatch the event down, find a child
904 // who can handle it, start with the front-most child.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 final View[] children = mChildren;
906 final int count = mChildrenCount;
Adam Powellb08013c2010-09-16 16:28:11 -0700907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800908 for (int i = count - 1; i >= 0; i--) {
909 final View child = children[i];
910 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
911 || child.getAnimation() != null) {
Adam Powell2b342f02010-08-18 18:14:13 -0700912 // Single dispatch always picks its target based on the initial down
913 // event's position - index 0
914 if (dispatchTouchEventIfInView(child, ev, 0)) {
Chet Haasec3aa3612010-06-17 08:50:37 -0700915 mMotionTarget = child;
916 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
918 }
919 }
920 }
921 }
Romain Guy8506ab42009-06-11 17:35:47 -0700922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||
Romain Guy8506ab42009-06-11 17:35:47 -0700924 (action == MotionEvent.ACTION_CANCEL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925
926 if (isUpOrCancel) {
927 // Note, we've already copied the previous state to our local
928 // variable, so this takes effect on the next event
929 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
930 }
Romain Guy8506ab42009-06-11 17:35:47 -0700931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 // The event wasn't an ACTION_DOWN, dispatch it to our target if
933 // we have one.
934 final View target = mMotionTarget;
935 if (target == null) {
936 // We don't have a target, this means we're handling the
937 // event as a regular view.
938 ev.setLocation(xf, yf);
Romain Guy8afa5152010-02-26 11:56:30 -0800939 if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
940 ev.setAction(MotionEvent.ACTION_CANCEL);
941 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 return super.dispatchTouchEvent(ev);
944 }
945
Chet Haaseddc8e712010-07-21 13:12:53 -0700946 // Calculate the offset point into the target's local coordinates
Chet Haasefd2b0022010-08-06 13:08:56 -0700947 float xc = scrolledXFloat - (float) target.mLeft;
948 float yc = scrolledYFloat - (float) target.mTop;
949 if (!target.hasIdentityMatrix() && mAttachInfo != null) {
Chet Haaseddc8e712010-07-21 13:12:53 -0700950 // non-identity matrix: transform the point into the view's coordinates
951 final float[] localXY = mAttachInfo.mTmpTransformLocation;
Chet Haasefd2b0022010-08-06 13:08:56 -0700952 localXY[0] = xc;
953 localXY[1] = yc;
Chet Haaseddc8e712010-07-21 13:12:53 -0700954 target.getInverseMatrix().mapPoints(localXY);
Chet Haasefd2b0022010-08-06 13:08:56 -0700955 xc = localXY[0];
956 yc = localXY[1];
Chet Haaseddc8e712010-07-21 13:12:53 -0700957 }
958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 // if have a target, see if we're allowed to and want to intercept its
960 // events
961 if (!disallowIntercept && onInterceptTouchEvent(ev)) {
Romain Guy8afa5152010-02-26 11:56:30 -0800962 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 ev.setAction(MotionEvent.ACTION_CANCEL);
964 ev.setLocation(xc, yc);
965 if (!target.dispatchTouchEvent(ev)) {
966 // target didn't handle ACTION_CANCEL. not much we can do
967 // but they should have.
968 }
969 // clear the target
970 mMotionTarget = null;
971 // Don't dispatch this event to our own view, because we already
972 // saw it when intercepting; we just want to give the following
973 // event to the normal onTouchEvent().
974 return true;
975 }
976
977 if (isUpOrCancel) {
978 mMotionTarget = null;
979 }
980
981 // finally offset the event to the target's coordinate system and
982 // dispatch the event.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 ev.setLocation(xc, yc);
984
Romain Guy8afa5152010-02-26 11:56:30 -0800985 if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
986 ev.setAction(MotionEvent.ACTION_CANCEL);
987 target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
988 mMotionTarget = null;
989 }
990
Adam Cohen9b073942010-08-19 16:49:52 -0700991 if (target.dispatchTouchEvent(ev)) {
992 return true;
993 } else {
994 ev.setLocation(xf, yf);
995 }
996 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
998
999 /**
Adam Powell2b342f02010-08-18 18:14:13 -07001000 * This method detects whether the pointer location at <code>pointerIndex</code> within
1001 * <code>ev</code> is inside the specified view. If so, the transformed event is dispatched to
1002 * <code>child</code>.
1003 *
1004 * @param child View to hit test against
1005 * @param ev MotionEvent to test
1006 * @param pointerIndex Index of the pointer within <code>ev</code> to test
1007 * @return <code>false</code> if the hit test failed, or the result of
1008 * <code>child.dispatchTouchEvent</code>
1009 */
1010 private boolean dispatchTouchEventIfInView(View child, MotionEvent ev, int pointerIndex) {
1011 final float x = ev.getX(pointerIndex);
1012 final float y = ev.getY(pointerIndex);
1013 final float scrolledX = x + mScrollX;
1014 final float scrolledY = y + mScrollY;
1015 float localX = scrolledX - child.mLeft;
1016 float localY = scrolledY - child.mTop;
1017 if (!child.hasIdentityMatrix() && mAttachInfo != null) {
1018 // non-identity matrix: transform the point into the view's coordinates
1019 final float[] localXY = mAttachInfo.mTmpTransformLocation;
1020 localXY[0] = localX;
1021 localXY[1] = localY;
1022 child.getInverseMatrix().mapPoints(localXY);
1023 localX = localXY[0];
1024 localY = localXY[1];
1025 }
1026 if (localX >= 0 && localY >= 0 && localX < (child.mRight - child.mLeft) &&
1027 localY < (child.mBottom - child.mTop)) {
1028 // It would be safer to clone the event here but we don't for performance.
1029 // There are many subtle interactions in touch event dispatch; change at your own risk.
1030 child.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1031 ev.offsetLocation(localX - x, localY - y);
Adam Cohen9b073942010-08-19 16:49:52 -07001032 if (child.dispatchTouchEvent(ev)) {
1033 return true;
1034 } else {
1035 ev.offsetLocation(x - localX, y - localY);
1036 return false;
1037 }
Adam Powell2b342f02010-08-18 18:14:13 -07001038 }
1039 return false;
1040 }
1041
1042 private boolean dispatchSplitTouchEvent(MotionEvent ev) {
1043 final SplitMotionTargets targets = mSplitMotionTargets;
1044 final int action = ev.getAction();
1045 final int maskedAction = ev.getActionMasked();
1046 float xf = ev.getX();
1047 float yf = ev.getY();
1048 float scrolledXFloat = xf + mScrollX;
1049 float scrolledYFloat = yf + mScrollY;
1050
1051 boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
1052
1053 if (maskedAction == MotionEvent.ACTION_DOWN ||
1054 maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
1055 final int actionIndex = ev.getActionIndex();
1056 final int actionId = ev.getPointerId(actionIndex);
1057
1058 // Clear out any current target for this ID.
1059 // XXX: We should probably send an ACTION_UP to the current
1060 // target if present.
1061 targets.removeById(actionId);
1062
1063 // If we're disallowing intercept or if we're allowing and we didn't
1064 // intercept
1065 if (disallowIntercept || !onInterceptTouchEvent(ev)) {
1066 // reset this event's action (just to protect ourselves)
1067 ev.setAction(action);
1068 // We know we want to dispatch the event down, try to find a child
1069 // who can handle it, start with the front-most child.
Adam Powell816c3be2010-08-23 18:00:05 -07001070 final long downTime = ev.getEventTime();
Adam Powell2b342f02010-08-18 18:14:13 -07001071 final View[] children = mChildren;
1072 final int count = mChildrenCount;
1073 for (int i = count - 1; i >= 0; i--) {
1074 final View child = children[i];
1075 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
1076 || child.getAnimation() != null) {
Adam Powell816c3be2010-08-23 18:00:05 -07001077 final MotionEvent childEvent =
1078 targets.filterMotionEventForChild(ev, child, downTime);
Adam Powell2b342f02010-08-18 18:14:13 -07001079 if (childEvent != null) {
1080 try {
1081 final int childActionIndex = childEvent.findPointerIndex(actionId);
1082 if (dispatchTouchEventIfInView(child, childEvent,
1083 childActionIndex)) {
Adam Powell816c3be2010-08-23 18:00:05 -07001084 targets.add(actionId, child, downTime);
Adam Powell2b342f02010-08-18 18:14:13 -07001085
1086 return true;
1087 }
1088 } finally {
1089 childEvent.recycle();
1090 }
1091 }
1092 }
1093 }
1094
1095 // Didn't find a new target. Do we have a "primary" target to send to?
Adam Powell816c3be2010-08-23 18:00:05 -07001096 final SplitMotionTargets.TargetInfo primaryTargetInfo = targets.getPrimaryTarget();
1097 if (primaryTargetInfo != null) {
1098 final View primaryTarget = primaryTargetInfo.view;
1099 final MotionEvent childEvent = targets.filterMotionEventForChild(ev,
1100 primaryTarget, primaryTargetInfo.downTime);
Adam Powell2b342f02010-08-18 18:14:13 -07001101 if (childEvent != null) {
1102 try {
1103 // Calculate the offset point into the target's local coordinates
1104 float xc = scrolledXFloat - (float) primaryTarget.mLeft;
1105 float yc = scrolledYFloat - (float) primaryTarget.mTop;
1106 if (!primaryTarget.hasIdentityMatrix() && mAttachInfo != null) {
1107 // non-identity matrix: transform the point into the view's
1108 // coordinates
1109 final float[] localXY = mAttachInfo.mTmpTransformLocation;
1110 localXY[0] = xc;
1111 localXY[1] = yc;
1112 primaryTarget.getInverseMatrix().mapPoints(localXY);
1113 xc = localXY[0];
1114 yc = localXY[1];
1115 }
1116 childEvent.setLocation(xc, yc);
1117 if (primaryTarget.dispatchTouchEvent(childEvent)) {
Adam Powell816c3be2010-08-23 18:00:05 -07001118 targets.add(actionId, primaryTarget, primaryTargetInfo.downTime);
Adam Powell2b342f02010-08-18 18:14:13 -07001119 return true;
1120 }
1121 } finally {
1122 childEvent.recycle();
1123 }
1124 }
1125 }
1126 }
1127 }
1128
1129 boolean isUpOrCancel = (action == MotionEvent.ACTION_UP) ||
1130 (action == MotionEvent.ACTION_CANCEL);
1131
1132 if (isUpOrCancel) {
1133 // Note, we've already copied the previous state to our local
1134 // variable, so this takes effect on the next event
1135 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
1136 }
1137
1138 if (targets.isEmpty()) {
1139 // We don't have any targets, this means we're handling the
1140 // event as a regular view.
1141 ev.setLocation(xf, yf);
1142 if ((mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
1143 ev.setAction(MotionEvent.ACTION_CANCEL);
1144 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1145 }
1146 return super.dispatchTouchEvent(ev);
1147 }
1148
1149 // if we have targets, see if we're allowed to and want to intercept their
1150 // events
1151 int uniqueTargetCount = targets.getUniqueTargetCount();
1152 if (!disallowIntercept && onInterceptTouchEvent(ev)) {
1153 mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1154
1155 for (int uniqueIndex = 0; uniqueIndex < uniqueTargetCount; uniqueIndex++) {
Adam Powell816c3be2010-08-23 18:00:05 -07001156 final View target = targets.getUniqueTargetAt(uniqueIndex).view;
Adam Powell2b342f02010-08-18 18:14:13 -07001157
1158 // Calculate the offset point into the target's local coordinates
1159 float xc = scrolledXFloat - (float) target.mLeft;
1160 float yc = scrolledYFloat - (float) target.mTop;
1161 if (!target.hasIdentityMatrix() && mAttachInfo != null) {
1162 // non-identity matrix: transform the point into the view's coordinates
1163 final float[] localXY = mAttachInfo.mTmpTransformLocation;
1164 localXY[0] = xc;
1165 localXY[1] = yc;
1166 target.getInverseMatrix().mapPoints(localXY);
1167 xc = localXY[0];
1168 yc = localXY[1];
1169 }
1170
1171 ev.setAction(MotionEvent.ACTION_CANCEL);
1172 ev.setLocation(xc, yc);
1173 if (!target.dispatchTouchEvent(ev)) {
1174 // target didn't handle ACTION_CANCEL. not much we can do
1175 // but they should have.
1176 }
1177 }
1178 targets.clear();
1179 // Don't dispatch this event to our own view, because we already
1180 // saw it when intercepting; we just want to give the following
1181 // event to the normal onTouchEvent().
1182 return true;
1183 }
1184
1185 boolean handled = false;
1186 for (int uniqueIndex = 0; uniqueIndex < uniqueTargetCount; uniqueIndex++) {
Adam Powell816c3be2010-08-23 18:00:05 -07001187 final SplitMotionTargets.TargetInfo targetInfo = targets.getUniqueTargetAt(uniqueIndex);
1188 final View target = targetInfo.view;
Adam Powell2b342f02010-08-18 18:14:13 -07001189
Adam Powell816c3be2010-08-23 18:00:05 -07001190 final MotionEvent targetEvent =
1191 targets.filterMotionEventForChild(ev, target, targetInfo.downTime);
Adam Powell2b342f02010-08-18 18:14:13 -07001192 if (targetEvent == null) {
1193 continue;
1194 }
1195
1196 try {
1197 // Calculate the offset point into the target's local coordinates
1198 xf = targetEvent.getX();
1199 yf = targetEvent.getY();
1200 scrolledXFloat = xf + mScrollX;
1201 scrolledYFloat = yf + mScrollY;
1202 float xc = scrolledXFloat - (float) target.mLeft;
1203 float yc = scrolledYFloat - (float) target.mTop;
1204 if (!target.hasIdentityMatrix() && mAttachInfo != null) {
1205 // non-identity matrix: transform the point into the view's coordinates
1206 final float[] localXY = mAttachInfo.mTmpTransformLocation;
1207 localXY[0] = xc;
1208 localXY[1] = yc;
1209 target.getInverseMatrix().mapPoints(localXY);
1210 xc = localXY[0];
1211 yc = localXY[1];
1212 }
1213
1214 // finally offset the event to the target's coordinate system and
1215 // dispatch the event.
1216 targetEvent.setLocation(xc, yc);
1217
1218 if ((target.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) {
1219 targetEvent.setAction(MotionEvent.ACTION_CANCEL);
1220 target.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT;
1221 targets.removeView(target);
1222 uniqueIndex--;
1223 uniqueTargetCount--;
1224 }
1225
Adam Powell167bc822010-09-13 18:11:08 -07001226 handled |= target.dispatchTouchEvent(targetEvent);
Adam Powell2b342f02010-08-18 18:14:13 -07001227 } finally {
1228 targetEvent.recycle();
1229 }
1230 }
1231
1232 if (maskedAction == MotionEvent.ACTION_POINTER_UP) {
1233 final int removeId = ev.getPointerId(ev.getActionIndex());
1234 targets.removeById(removeId);
1235 }
1236
1237 if (isUpOrCancel) {
1238 targets.clear();
1239 }
1240
1241 return handled;
1242 }
1243
1244 /**
1245 * Enable or disable the splitting of MotionEvents to multiple children during touch event
1246 * dispatch. This behavior is disabled by default.
1247 *
1248 * <p>When this option is enabled MotionEvents may be split and dispatched to different child
1249 * views depending on where each pointer initially went down. This allows for user interactions
1250 * such as scrolling two panes of content independently, chording of buttons, and performing
1251 * independent gestures on different pieces of content.
1252 *
1253 * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple
1254 * child views. <code>false</code> to only allow one child view to be the target of
1255 * any MotionEvent received by this ViewGroup.
1256 */
1257 public void setMotionEventSplittingEnabled(boolean split) {
1258 // TODO Applications really shouldn't change this setting mid-touch event,
1259 // but perhaps this should handle that case and send ACTION_CANCELs to any child views
1260 // with gestures in progress when this is changed.
1261 if (split) {
Adam Powell2b342f02010-08-18 18:14:13 -07001262 mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS;
1263 } else {
1264 mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS;
1265 mSplitMotionTargets = null;
1266 }
1267 }
1268
1269 /**
1270 * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children.
1271 */
1272 public boolean isMotionEventSplittingEnabled() {
1273 return (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS;
1274 }
1275
1276 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 * {@inheritDoc}
1278 */
1279 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
Romain Guy8506ab42009-06-11 17:35:47 -07001280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) {
1282 // We're already in this state, assume our ancestors are too
1283 return;
1284 }
Romain Guy8506ab42009-06-11 17:35:47 -07001285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 if (disallowIntercept) {
1287 mGroupFlags |= FLAG_DISALLOW_INTERCEPT;
1288 } else {
1289 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
1290 }
Romain Guy8506ab42009-06-11 17:35:47 -07001291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 // Pass it up to our parent
1293 if (mParent != null) {
1294 mParent.requestDisallowInterceptTouchEvent(disallowIntercept);
1295 }
1296 }
1297
1298 /**
1299 * Implement this method to intercept all touch screen motion events. This
1300 * allows you to watch events as they are dispatched to your children, and
1301 * take ownership of the current gesture at any point.
1302 *
1303 * <p>Using this function takes some care, as it has a fairly complicated
1304 * interaction with {@link View#onTouchEvent(MotionEvent)
1305 * View.onTouchEvent(MotionEvent)}, and using it requires implementing
1306 * that method as well as this one in the correct way. Events will be
1307 * received in the following order:
1308 *
1309 * <ol>
1310 * <li> You will receive the down event here.
1311 * <li> The down event will be handled either by a child of this view
1312 * group, or given to your own onTouchEvent() method to handle; this means
1313 * you should implement onTouchEvent() to return true, so you will
1314 * continue to see the rest of the gesture (instead of looking for
1315 * a parent view to handle it). Also, by returning true from
1316 * onTouchEvent(), you will not receive any following
1317 * events in onInterceptTouchEvent() and all touch processing must
1318 * happen in onTouchEvent() like normal.
1319 * <li> For as long as you return false from this function, each following
1320 * event (up to and including the final up) will be delivered first here
1321 * and then to the target's onTouchEvent().
1322 * <li> If you return true from here, you will not receive any
1323 * following events: the target view will receive the same event but
1324 * with the action {@link MotionEvent#ACTION_CANCEL}, and all further
1325 * events will be delivered to your onTouchEvent() method and no longer
1326 * appear here.
1327 * </ol>
1328 *
1329 * @param ev The motion event being dispatched down the hierarchy.
1330 * @return Return true to steal motion events from the children and have
1331 * them dispatched to this ViewGroup through onTouchEvent().
1332 * The current target will receive an ACTION_CANCEL event, and no further
1333 * messages will be delivered here.
1334 */
1335 public boolean onInterceptTouchEvent(MotionEvent ev) {
1336 return false;
1337 }
1338
1339 /**
1340 * {@inheritDoc}
1341 *
1342 * Looks for a view to give focus to respecting the setting specified by
1343 * {@link #getDescendantFocusability()}.
1344 *
1345 * Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to
1346 * find focus within the children of this group when appropriate.
1347 *
1348 * @see #FOCUS_BEFORE_DESCENDANTS
1349 * @see #FOCUS_AFTER_DESCENDANTS
1350 * @see #FOCUS_BLOCK_DESCENDANTS
1351 * @see #onRequestFocusInDescendants
1352 */
1353 @Override
1354 public boolean requestFocus(int direction, Rect previouslyFocusedRect) {
1355 if (DBG) {
1356 System.out.println(this + " ViewGroup.requestFocus direction="
1357 + direction);
1358 }
1359 int descendantFocusability = getDescendantFocusability();
1360
1361 switch (descendantFocusability) {
1362 case FOCUS_BLOCK_DESCENDANTS:
1363 return super.requestFocus(direction, previouslyFocusedRect);
1364 case FOCUS_BEFORE_DESCENDANTS: {
1365 final boolean took = super.requestFocus(direction, previouslyFocusedRect);
1366 return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect);
1367 }
1368 case FOCUS_AFTER_DESCENDANTS: {
1369 final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect);
1370 return took ? took : super.requestFocus(direction, previouslyFocusedRect);
1371 }
1372 default:
1373 throw new IllegalStateException("descendant focusability must be "
1374 + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS "
1375 + "but is " + descendantFocusability);
1376 }
1377 }
1378
1379 /**
1380 * Look for a descendant to call {@link View#requestFocus} on.
1381 * Called by {@link ViewGroup#requestFocus(int, android.graphics.Rect)}
1382 * when it wants to request focus within its children. Override this to
1383 * customize how your {@link ViewGroup} requests focus within its children.
1384 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT
1385 * @param previouslyFocusedRect The rectangle (in this View's coordinate system)
1386 * to give a finer grained hint about where focus is coming from. May be null
1387 * if there is no hint.
1388 * @return Whether focus was taken.
1389 */
1390 @SuppressWarnings({"ConstantConditions"})
1391 protected boolean onRequestFocusInDescendants(int direction,
1392 Rect previouslyFocusedRect) {
1393 int index;
1394 int increment;
1395 int end;
1396 int count = mChildrenCount;
1397 if ((direction & FOCUS_FORWARD) != 0) {
1398 index = 0;
1399 increment = 1;
1400 end = count;
1401 } else {
1402 index = count - 1;
1403 increment = -1;
1404 end = -1;
1405 }
1406 final View[] children = mChildren;
1407 for (int i = index; i != end; i += increment) {
1408 View child = children[i];
1409 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1410 if (child.requestFocus(direction, previouslyFocusedRect)) {
1411 return true;
1412 }
1413 }
1414 }
1415 return false;
1416 }
Romain Guya440b002010-02-24 15:57:54 -08001417
1418 /**
1419 * {@inheritDoc}
Romain Guydcc490f2010-02-24 17:59:35 -08001420 *
1421 * @hide
Romain Guya440b002010-02-24 15:57:54 -08001422 */
1423 @Override
1424 public void dispatchStartTemporaryDetach() {
1425 super.dispatchStartTemporaryDetach();
1426 final int count = mChildrenCount;
1427 final View[] children = mChildren;
1428 for (int i = 0; i < count; i++) {
1429 children[i].dispatchStartTemporaryDetach();
1430 }
1431 }
1432
1433 /**
1434 * {@inheritDoc}
Romain Guydcc490f2010-02-24 17:59:35 -08001435 *
1436 * @hide
Romain Guya440b002010-02-24 15:57:54 -08001437 */
1438 @Override
1439 public void dispatchFinishTemporaryDetach() {
1440 super.dispatchFinishTemporaryDetach();
1441 final int count = mChildrenCount;
1442 final View[] children = mChildren;
1443 for (int i = 0; i < count; i++) {
1444 children[i].dispatchFinishTemporaryDetach();
1445 }
1446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447
1448 /**
1449 * {@inheritDoc}
1450 */
1451 @Override
1452 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
1453 super.dispatchAttachedToWindow(info, visibility);
1454 visibility |= mViewFlags & VISIBILITY_MASK;
1455 final int count = mChildrenCount;
1456 final View[] children = mChildren;
1457 for (int i = 0; i < count; i++) {
1458 children[i].dispatchAttachedToWindow(info, visibility);
1459 }
1460 }
1461
svetoslavganov75986cf2009-05-14 22:28:01 -07001462 @Override
1463 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
1464 boolean populated = false;
1465 for (int i = 0, count = getChildCount(); i < count; i++) {
1466 populated |= getChildAt(i).dispatchPopulateAccessibilityEvent(event);
1467 }
1468 return populated;
1469 }
1470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 /**
1472 * {@inheritDoc}
1473 */
1474 @Override
1475 void dispatchDetachedFromWindow() {
1476 // If we still have a motion target, we are still in the process of
1477 // dispatching motion events to a child; we need to get rid of that
1478 // child to avoid dispatching events to it after the window is torn
1479 // down. To make sure we keep the child in a consistent state, we
1480 // first send it an ACTION_CANCEL motion event.
1481 if (mMotionTarget != null) {
1482 final long now = SystemClock.uptimeMillis();
1483 final MotionEvent event = MotionEvent.obtain(now, now,
1484 MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
1485 mMotionTarget.dispatchTouchEvent(event);
1486 event.recycle();
1487 mMotionTarget = null;
1488 }
1489
1490 final int count = mChildrenCount;
1491 final View[] children = mChildren;
1492 for (int i = 0; i < count; i++) {
1493 children[i].dispatchDetachedFromWindow();
1494 }
1495 super.dispatchDetachedFromWindow();
1496 }
1497
1498 /**
1499 * {@inheritDoc}
1500 */
1501 @Override
1502 public void setPadding(int left, int top, int right, int bottom) {
1503 super.setPadding(left, top, right, bottom);
1504
1505 if ((mPaddingLeft | mPaddingTop | mPaddingRight | mPaddingRight) != 0) {
1506 mGroupFlags |= FLAG_PADDING_NOT_NULL;
1507 } else {
1508 mGroupFlags &= ~FLAG_PADDING_NOT_NULL;
1509 }
1510 }
1511
1512 /**
1513 * {@inheritDoc}
1514 */
1515 @Override
1516 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
1517 super.dispatchSaveInstanceState(container);
1518 final int count = mChildrenCount;
1519 final View[] children = mChildren;
1520 for (int i = 0; i < count; i++) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001521 View c = children[i];
1522 if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
1523 c.dispatchSaveInstanceState(container);
1524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
1526 }
1527
1528 /**
1529 * Perform dispatching of a {@link #saveHierarchyState freeze()} to only this view,
1530 * not to its children. For use when overriding
1531 * {@link #dispatchSaveInstanceState dispatchFreeze()} to allow subclasses to freeze
1532 * their own state but not the state of their children.
1533 *
1534 * @param container the container
1535 */
1536 protected void dispatchFreezeSelfOnly(SparseArray<Parcelable> container) {
1537 super.dispatchSaveInstanceState(container);
1538 }
1539
1540 /**
1541 * {@inheritDoc}
1542 */
1543 @Override
1544 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
1545 super.dispatchRestoreInstanceState(container);
1546 final int count = mChildrenCount;
1547 final View[] children = mChildren;
1548 for (int i = 0; i < count; i++) {
Dianne Hackbornb4bc78b2010-05-12 18:59:50 -07001549 View c = children[i];
1550 if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) {
1551 c.dispatchRestoreInstanceState(container);
1552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 }
1554 }
1555
1556 /**
1557 * Perform dispatching of a {@link #restoreHierarchyState thaw()} to only this view,
1558 * not to its children. For use when overriding
1559 * {@link #dispatchRestoreInstanceState dispatchThaw()} to allow subclasses to thaw
1560 * their own state but not the state of their children.
1561 *
1562 * @param container the container
1563 */
1564 protected void dispatchThawSelfOnly(SparseArray<Parcelable> container) {
1565 super.dispatchRestoreInstanceState(container);
1566 }
1567
1568 /**
1569 * Enables or disables the drawing cache for each child of this view group.
1570 *
1571 * @param enabled true to enable the cache, false to dispose of it
1572 */
1573 protected void setChildrenDrawingCacheEnabled(boolean enabled) {
1574 if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) {
1575 final View[] children = mChildren;
1576 final int count = mChildrenCount;
1577 for (int i = 0; i < count; i++) {
1578 children[i].setDrawingCacheEnabled(enabled);
1579 }
1580 }
1581 }
1582
1583 @Override
1584 protected void onAnimationStart() {
1585 super.onAnimationStart();
1586
1587 // When this ViewGroup's animation starts, build the cache for the children
1588 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
1589 final int count = mChildrenCount;
1590 final View[] children = mChildren;
1591
1592 for (int i = 0; i < count; i++) {
1593 final View child = children[i];
1594 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1595 child.setDrawingCacheEnabled(true);
Romain Guyfbd8f692009-06-26 14:51:58 -07001596 child.buildDrawingCache(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 }
1598 }
1599
1600 mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
1601 }
1602 }
1603
1604 @Override
1605 protected void onAnimationEnd() {
1606 super.onAnimationEnd();
1607
1608 // When this ViewGroup's animation ends, destroy the cache of the children
1609 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
1610 mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
1611
1612 if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
1613 setChildrenDrawingCacheEnabled(false);
1614 }
1615 }
1616 }
1617
Romain Guy223ff5c2010-03-02 17:07:47 -08001618 @Override
1619 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) {
Romain Guy65554f22010-03-22 18:58:21 -07001620 int count = mChildrenCount;
1621 int[] visibilities = null;
1622
Romain Guy223ff5c2010-03-02 17:07:47 -08001623 if (skipChildren) {
Romain Guy65554f22010-03-22 18:58:21 -07001624 visibilities = new int[count];
1625 for (int i = 0; i < count; i++) {
1626 View child = getChildAt(i);
1627 visibilities[i] = child.getVisibility();
1628 if (visibilities[i] == View.VISIBLE) {
1629 child.setVisibility(INVISIBLE);
1630 }
1631 }
Romain Guy223ff5c2010-03-02 17:07:47 -08001632 }
1633
1634 Bitmap b = super.createSnapshot(quality, backgroundColor, skipChildren);
Romain Guy65554f22010-03-22 18:58:21 -07001635
1636 if (skipChildren) {
1637 for (int i = 0; i < count; i++) {
1638 getChildAt(i).setVisibility(visibilities[i]);
1639 }
1640 }
Romain Guy223ff5c2010-03-02 17:07:47 -08001641
1642 return b;
1643 }
1644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 /**
1646 * {@inheritDoc}
1647 */
1648 @Override
1649 protected void dispatchDraw(Canvas canvas) {
1650 final int count = mChildrenCount;
1651 final View[] children = mChildren;
1652 int flags = mGroupFlags;
1653
1654 if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
1655 final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
1656
1657 for (int i = 0; i < count; i++) {
1658 final View child = children[i];
1659 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
1660 final LayoutParams params = child.getLayoutParams();
1661 attachLayoutAnimationParameters(child, params, i, count);
1662 bindLayoutAnimation(child);
1663 if (cache) {
1664 child.setDrawingCacheEnabled(true);
Romain Guyfbd8f692009-06-26 14:51:58 -07001665 child.buildDrawingCache(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
1667 }
1668 }
1669
1670 final LayoutAnimationController controller = mLayoutAnimationController;
1671 if (controller.willOverlap()) {
1672 mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
1673 }
1674
1675 controller.start();
1676
1677 mGroupFlags &= ~FLAG_RUN_ANIMATION;
1678 mGroupFlags &= ~FLAG_ANIMATION_DONE;
1679
1680 if (cache) {
1681 mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE;
1682 }
1683
1684 if (mAnimationListener != null) {
1685 mAnimationListener.onAnimationStart(controller.getAnimation());
1686 }
1687 }
1688
1689 int saveCount = 0;
1690 final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
1691 if (clipToPadding) {
1692 saveCount = canvas.save();
Romain Guy8f2d94f2009-03-25 18:04:42 -07001693 canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
1694 mScrollX + mRight - mLeft - mPaddingRight,
1695 mScrollY + mBottom - mTop - mPaddingBottom);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696
1697 }
1698
1699 // We will draw our child's animation, let's reset the flag
1700 mPrivateFlags &= ~DRAW_ANIMATION;
1701 mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED;
1702
1703 boolean more = false;
1704 final long drawingTime = getDrawingTime();
1705
1706 if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) {
1707 for (int i = 0; i < count; i++) {
1708 final View child = children[i];
1709 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
1710 more |= drawChild(canvas, child, drawingTime);
1711 }
1712 }
1713 } else {
1714 for (int i = 0; i < count; i++) {
1715 final View child = children[getChildDrawingOrder(count, i)];
1716 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
1717 more |= drawChild(canvas, child, drawingTime);
1718 }
1719 }
1720 }
1721
1722 // Draw any disappearing views that have animations
1723 if (mDisappearingChildren != null) {
1724 final ArrayList<View> disappearingChildren = mDisappearingChildren;
1725 final int disappearingCount = disappearingChildren.size() - 1;
1726 // Go backwards -- we may delete as animations finish
1727 for (int i = disappearingCount; i >= 0; i--) {
1728 final View child = disappearingChildren.get(i);
1729 more |= drawChild(canvas, child, drawingTime);
1730 }
1731 }
1732
1733 if (clipToPadding) {
1734 canvas.restoreToCount(saveCount);
1735 }
1736
1737 // mGroupFlags might have been updated by drawChild()
1738 flags = mGroupFlags;
1739
1740 if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) {
1741 invalidate();
1742 }
1743
1744 if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 &&
1745 mLayoutAnimationController.isDone() && !more) {
1746 // We want to erase the drawing cache and notify the listener after the
1747 // next frame is drawn because one extra invalidate() is caused by
1748 // drawChild() after the animation is over
1749 mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER;
1750 final Runnable end = new Runnable() {
1751 public void run() {
1752 notifyAnimationListener();
1753 }
1754 };
1755 post(end);
1756 }
1757 }
Romain Guy8506ab42009-06-11 17:35:47 -07001758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 /**
1760 * Returns the index of the child to draw for this iteration. Override this
1761 * if you want to change the drawing order of children. By default, it
1762 * returns i.
1763 * <p>
Romain Guy293451e2009-11-04 13:59:48 -08001764 * NOTE: In order for this method to be called, you must enable child ordering
1765 * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}.
Romain Guy8506ab42009-06-11 17:35:47 -07001766 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 * @param i The current iteration.
1768 * @return The index of the child to draw this iteration.
Romain Guy293451e2009-11-04 13:59:48 -08001769 *
1770 * @see #setChildrenDrawingOrderEnabled(boolean)
1771 * @see #isChildrenDrawingOrderEnabled()
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 */
1773 protected int getChildDrawingOrder(int childCount, int i) {
1774 return i;
1775 }
Romain Guy8506ab42009-06-11 17:35:47 -07001776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 private void notifyAnimationListener() {
1778 mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER;
1779 mGroupFlags |= FLAG_ANIMATION_DONE;
1780
1781 if (mAnimationListener != null) {
1782 final Runnable end = new Runnable() {
1783 public void run() {
1784 mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation());
1785 }
1786 };
1787 post(end);
1788 }
1789
1790 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) {
1791 mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE;
1792 if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) {
1793 setChildrenDrawingCacheEnabled(false);
1794 }
1795 }
1796
1797 invalidate();
1798 }
1799
1800 /**
1801 * Draw one child of this View Group. This method is responsible for getting
1802 * the canvas in the right state. This includes clipping, translating so
1803 * that the child's scrolled origin is at 0, 0, and applying any animation
1804 * transformations.
1805 *
1806 * @param canvas The canvas on which to draw the child
1807 * @param child Who to draw
1808 * @param drawingTime The time at which draw is occuring
1809 * @return True if an invalidate() was issued
1810 */
1811 protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
1812 boolean more = false;
1813
1814 final int cl = child.mLeft;
1815 final int ct = child.mTop;
1816 final int cr = child.mRight;
1817 final int cb = child.mBottom;
1818
1819 final int flags = mGroupFlags;
1820
1821 if ((flags & FLAG_CLEAR_TRANSFORMATION) == FLAG_CLEAR_TRANSFORMATION) {
Chet Haase48460322010-06-11 14:22:25 -07001822 mChildTransformation.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 mGroupFlags &= ~FLAG_CLEAR_TRANSFORMATION;
1824 }
1825
1826 Transformation transformToApply = null;
Chet Haase48460322010-06-11 14:22:25 -07001827 Transformation invalidationTransform;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 final Animation a = child.getAnimation();
1829 boolean concatMatrix = false;
1830
Chet Haase48460322010-06-11 14:22:25 -07001831 boolean scalingRequired = false;
1832 boolean caching = false;
1833 if (!canvas.isHardwareAccelerated() &&
1834 (flags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE ||
1835 (flags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE) {
1836 caching = true;
1837 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired;
1838 }
1839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 if (a != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 final boolean initialized = a.isInitialized();
1842 if (!initialized) {
Romain Guy8f2d94f2009-03-25 18:04:42 -07001843 a.initialize(cr - cl, cb - ct, getWidth(), getHeight());
1844 a.initializeInvalidateRegion(0, 0, cr - cl, cb - ct);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 child.onAnimationStart();
1846 }
1847
Chet Haase48460322010-06-11 14:22:25 -07001848 more = a.getTransformation(drawingTime, mChildTransformation,
1849 scalingRequired ? mAttachInfo.mApplicationScale : 1f);
1850 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) {
1851 if (mInvalidationTransformation == null) {
1852 mInvalidationTransformation = new Transformation();
1853 }
1854 invalidationTransform = mInvalidationTransformation;
1855 a.getTransformation(drawingTime, invalidationTransform, 1f);
1856 } else {
1857 invalidationTransform = mChildTransformation;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001859 transformToApply = mChildTransformation;
1860
1861 concatMatrix = a.willChangeTransformationMatrix();
1862
1863 if (more) {
1864 if (!a.willChangeBounds()) {
1865 if ((flags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) ==
1866 FLAG_OPTIMIZE_INVALIDATE) {
1867 mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
1868 } else if ((flags & FLAG_INVALIDATE_REQUIRED) == 0) {
1869 // The child need to draw an animation, potentially offscreen, so
1870 // make sure we do not cancel invalidate requests
1871 mPrivateFlags |= DRAW_ANIMATION;
1872 invalidate(cl, ct, cr, cb);
1873 }
1874 } else {
Chet Haase48460322010-06-11 14:22:25 -07001875 if (mInvalidateRegion == null) {
1876 mInvalidateRegion = new RectF();
1877 }
1878 final RectF region = mInvalidateRegion;
1879 a.getInvalidateRegion(0, 0, cr - cl, cb - ct, region, invalidationTransform);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880
1881 // The child need to draw an animation, potentially offscreen, so
1882 // make sure we do not cancel invalidate requests
1883 mPrivateFlags |= DRAW_ANIMATION;
The Android Open Source Project4df24232009-03-05 14:34:35 -08001884
1885 final int left = cl + (int) region.left;
1886 final int top = ct + (int) region.top;
1887 invalidate(left, top, left + (int) region.width(), top + (int) region.height());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
1889 }
1890 } else if ((flags & FLAG_SUPPORT_STATIC_TRANSFORMATIONS) ==
1891 FLAG_SUPPORT_STATIC_TRANSFORMATIONS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 final boolean hasTransform = getChildStaticTransformation(child, mChildTransformation);
1893 if (hasTransform) {
1894 final int transformType = mChildTransformation.getTransformationType();
1895 transformToApply = transformType != Transformation.TYPE_IDENTITY ?
1896 mChildTransformation : null;
1897 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0;
1898 }
1899 }
1900
Chet Haasedf030d22010-07-30 17:22:38 -07001901 concatMatrix |= !child.hasIdentityMatrix();
1902
Romain Guy5bcdff42009-05-14 21:27:18 -07001903 // Sets the flag as early as possible to allow draw() implementations
Romain Guy986003d2009-03-25 17:42:35 -07001904 // to call invalidate() successfully when doing animations
Romain Guy5bcdff42009-05-14 21:27:18 -07001905 child.mPrivateFlags |= DRAWN;
Romain Guy986003d2009-03-25 17:42:35 -07001906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW) &&
1908 (child.mPrivateFlags & DRAW_ANIMATION) == 0) {
1909 return more;
1910 }
1911
1912 child.computeScroll();
1913
1914 final int sx = child.mScrollX;
1915 final int sy = child.mScrollY;
1916
1917 Bitmap cache = null;
Chet Haase48460322010-06-11 14:22:25 -07001918 if (caching) {
Romain Guyfbd8f692009-06-26 14:51:58 -07001919 cache = child.getDrawingCache(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
1921
1922 final boolean hasNoCache = cache == null;
1923
1924 final int restoreTo = canvas.save();
1925 if (hasNoCache) {
1926 canvas.translate(cl - sx, ct - sy);
1927 } else {
1928 canvas.translate(cl, ct);
Romain Guy8506ab42009-06-11 17:35:47 -07001929 if (scalingRequired) {
Romain Guycafdea62009-06-12 10:51:36 -07001930 // mAttachInfo cannot be null, otherwise scalingRequired == false
Romain Guy8506ab42009-06-11 17:35:47 -07001931 final float scale = 1.0f / mAttachInfo.mApplicationScale;
1932 canvas.scale(scale, scale);
1933 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 }
1935
Chet Haasec3aa3612010-06-17 08:50:37 -07001936 float alpha = child.getAlpha();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937
Romain Guy33e72ae2010-07-17 12:40:29 -07001938 if (transformToApply != null || alpha < 1.0f || !child.hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07001939 int transX = 0;
1940 int transY = 0;
Romain Guy33e72ae2010-07-17 12:40:29 -07001941
Chet Haasec3aa3612010-06-17 08:50:37 -07001942 if (hasNoCache) {
1943 transX = -sx;
1944 transY = -sy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
Romain Guy33e72ae2010-07-17 12:40:29 -07001946
Chet Haasec3aa3612010-06-17 08:50:37 -07001947 if (transformToApply != null) {
1948 if (concatMatrix) {
1949 // Undo the scroll translation, apply the transformation matrix,
1950 // then redo the scroll translate to get the correct result.
1951 canvas.translate(-transX, -transY);
1952 canvas.concat(transformToApply.getMatrix());
1953 canvas.translate(transX, transY);
1954 mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
1955 }
Romain Guy33e72ae2010-07-17 12:40:29 -07001956
Chet Haasec3aa3612010-06-17 08:50:37 -07001957 float transformAlpha = transformToApply.getAlpha();
1958 if (transformAlpha < 1.0f) {
1959 alpha *= transformToApply.getAlpha();
1960 mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
1961 }
1962 }
Romain Guy33e72ae2010-07-17 12:40:29 -07001963
1964 if (!child.hasIdentityMatrix()) {
Chet Haasec3aa3612010-06-17 08:50:37 -07001965 canvas.translate(-transX, -transY);
1966 canvas.concat(child.getMatrix());
1967 canvas.translate(transX, transY);
1968 }
Romain Guy33e72ae2010-07-17 12:40:29 -07001969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 if (alpha < 1.0f) {
1971 mGroupFlags |= FLAG_CLEAR_TRANSFORMATION;
Romain Guy33e72ae2010-07-17 12:40:29 -07001972
1973 if (hasNoCache) {
1974 final int multipliedAlpha = (int) (255 * alpha);
1975 if (!child.onSetAlpha(multipliedAlpha)) {
Romain Guyfd880422010-09-23 16:16:04 -07001976 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
1977 if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
1978 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
1979 }
Romain Guy33e72ae2010-07-17 12:40:29 -07001980 canvas.saveLayerAlpha(sx, sy, sx + cr - cl, sy + cb - ct, multipliedAlpha,
Romain Guyfd880422010-09-23 16:16:04 -07001981 layerFlags);
Romain Guy33e72ae2010-07-17 12:40:29 -07001982 } else {
1983 child.mPrivateFlags |= ALPHA_SET;
1984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
1986 }
1987 } else if ((child.mPrivateFlags & ALPHA_SET) == ALPHA_SET) {
1988 child.onSetAlpha(255);
Romain Guy9b34d452010-09-02 11:45:04 -07001989 child.mPrivateFlags &= ~ALPHA_SET;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
1991
1992 if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) {
1993 if (hasNoCache) {
Romain Guy8f2d94f2009-03-25 18:04:42 -07001994 canvas.clipRect(sx, sy, sx + (cr - cl), sy + (cb - ct));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 } else {
Romain Guy8506ab42009-06-11 17:35:47 -07001996 if (!scalingRequired) {
1997 canvas.clipRect(0, 0, cr - cl, cb - ct);
1998 } else {
1999 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight());
2000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002 }
2003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 if (hasNoCache) {
2005 // Fast path for layouts with no backgrounds
2006 if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) {
2007 if (ViewDebug.TRACE_HIERARCHY) {
2008 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW);
2009 }
Romain Guy8506ab42009-06-11 17:35:47 -07002010 child.mPrivateFlags &= ~DIRTY_MASK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 child.dispatchDraw(canvas);
2012 } else {
2013 child.draw(canvas);
2014 }
2015 } else {
2016 final Paint cachePaint = mCachePaint;
2017 if (alpha < 1.0f) {
2018 cachePaint.setAlpha((int) (alpha * 255));
2019 mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE;
2020 } else if ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) {
2021 cachePaint.setAlpha(255);
2022 mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE;
2023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint);
2025 }
2026
2027 canvas.restoreToCount(restoreTo);
2028
2029 if (a != null && !more) {
2030 child.onSetAlpha(255);
2031 finishAnimatingView(child, a);
2032 }
2033
2034 return more;
2035 }
2036
2037 /**
2038 * By default, children are clipped to their bounds before drawing. This
2039 * allows view groups to override this behavior for animations, etc.
2040 *
2041 * @param clipChildren true to clip children to their bounds,
2042 * false otherwise
2043 * @attr ref android.R.styleable#ViewGroup_clipChildren
2044 */
2045 public void setClipChildren(boolean clipChildren) {
2046 setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren);
2047 }
2048
2049 /**
2050 * By default, children are clipped to the padding of the ViewGroup. This
2051 * allows view groups to override this behavior
2052 *
2053 * @param clipToPadding true to clip children to the padding of the
2054 * group, false otherwise
2055 * @attr ref android.R.styleable#ViewGroup_clipToPadding
2056 */
2057 public void setClipToPadding(boolean clipToPadding) {
2058 setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding);
2059 }
2060
2061 /**
2062 * {@inheritDoc}
2063 */
2064 @Override
2065 public void dispatchSetSelected(boolean selected) {
2066 final View[] children = mChildren;
2067 final int count = mChildrenCount;
2068 for (int i = 0; i < count; i++) {
Chet Haasedf030d22010-07-30 17:22:38 -07002069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 children[i].setSelected(selected);
2071 }
2072 }
Romain Guy8506ab42009-06-11 17:35:47 -07002073
Dianne Hackbornd0fa3712010-09-14 18:57:14 -07002074 /**
2075 * {@inheritDoc}
2076 */
2077 @Override
2078 public void dispatchSetActivated(boolean activated) {
2079 final View[] children = mChildren;
2080 final int count = mChildrenCount;
2081 for (int i = 0; i < count; i++) {
2082
2083 children[i].setActivated(activated);
2084 }
2085 }
2086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 @Override
2088 protected void dispatchSetPressed(boolean pressed) {
2089 final View[] children = mChildren;
2090 final int count = mChildrenCount;
2091 for (int i = 0; i < count; i++) {
2092 children[i].setPressed(pressed);
2093 }
2094 }
2095
2096 /**
2097 * When this property is set to true, this ViewGroup supports static transformations on
2098 * children; this causes
2099 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be
2100 * invoked when a child is drawn.
2101 *
2102 * Any subclass overriding
2103 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should
2104 * set this property to true.
2105 *
2106 * @param enabled True to enable static transformations on children, false otherwise.
2107 *
2108 * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS
2109 */
2110 protected void setStaticTransformationsEnabled(boolean enabled) {
2111 setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled);
2112 }
2113
2114 /**
2115 * {@inheritDoc}
2116 *
Romain Guy8506ab42009-06-11 17:35:47 -07002117 * @see #setStaticTransformationsEnabled(boolean)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 */
2119 protected boolean getChildStaticTransformation(View child, Transformation t) {
2120 return false;
2121 }
2122
2123 /**
2124 * {@hide}
2125 */
2126 @Override
2127 protected View findViewTraversal(int id) {
2128 if (id == mID) {
2129 return this;
2130 }
2131
2132 final View[] where = mChildren;
2133 final int len = mChildrenCount;
2134
2135 for (int i = 0; i < len; i++) {
2136 View v = where[i];
2137
2138 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
2139 v = v.findViewById(id);
2140
2141 if (v != null) {
2142 return v;
2143 }
2144 }
2145 }
2146
2147 return null;
2148 }
2149
2150 /**
2151 * {@hide}
2152 */
2153 @Override
2154 protected View findViewWithTagTraversal(Object tag) {
2155 if (tag != null && tag.equals(mTag)) {
2156 return this;
2157 }
2158
2159 final View[] where = mChildren;
2160 final int len = mChildrenCount;
2161
2162 for (int i = 0; i < len; i++) {
2163 View v = where[i];
2164
2165 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) {
2166 v = v.findViewWithTag(tag);
2167
2168 if (v != null) {
2169 return v;
2170 }
2171 }
2172 }
2173
2174 return null;
2175 }
2176
2177 /**
2178 * Adds a child view. If no layout parameters are already set on the child, the
2179 * default parameters for this ViewGroup are set on the child.
2180 *
2181 * @param child the child view to add
2182 *
2183 * @see #generateDefaultLayoutParams()
2184 */
2185 public void addView(View child) {
2186 addView(child, -1);
2187 }
2188
2189 /**
2190 * Adds a child view. If no layout parameters are already set on the child, the
2191 * default parameters for this ViewGroup are set on the child.
2192 *
2193 * @param child the child view to add
2194 * @param index the position at which to add the child
2195 *
2196 * @see #generateDefaultLayoutParams()
2197 */
2198 public void addView(View child, int index) {
2199 LayoutParams params = child.getLayoutParams();
2200 if (params == null) {
2201 params = generateDefaultLayoutParams();
2202 if (params == null) {
2203 throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
2204 }
2205 }
2206 addView(child, index, params);
2207 }
2208
2209 /**
2210 * Adds a child view with this ViewGroup's default layout parameters and the
2211 * specified width and height.
2212 *
2213 * @param child the child view to add
2214 */
2215 public void addView(View child, int width, int height) {
2216 final LayoutParams params = generateDefaultLayoutParams();
2217 params.width = width;
2218 params.height = height;
2219 addView(child, -1, params);
2220 }
2221
2222 /**
2223 * Adds a child view with the specified layout parameters.
2224 *
2225 * @param child the child view to add
2226 * @param params the layout parameters to set on the child
2227 */
2228 public void addView(View child, LayoutParams params) {
2229 addView(child, -1, params);
2230 }
2231
2232 /**
2233 * Adds a child view with the specified layout parameters.
2234 *
2235 * @param child the child view to add
2236 * @param index the position at which to add the child
2237 * @param params the layout parameters to set on the child
2238 */
2239 public void addView(View child, int index, LayoutParams params) {
2240 if (DBG) {
2241 System.out.println(this + " addView");
2242 }
2243
2244 // addViewInner() will call child.requestLayout() when setting the new LayoutParams
2245 // therefore, we call requestLayout() on ourselves before, so that the child's request
2246 // will be blocked at our level
2247 requestLayout();
2248 invalidate();
2249 addViewInner(child, index, params, false);
2250 }
2251
2252 /**
2253 * {@inheritDoc}
2254 */
2255 public void updateViewLayout(View view, ViewGroup.LayoutParams params) {
2256 if (!checkLayoutParams(params)) {
2257 throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this);
2258 }
2259 if (view.mParent != this) {
2260 throw new IllegalArgumentException("Given view not a child of " + this);
2261 }
2262 view.setLayoutParams(params);
2263 }
2264
2265 /**
2266 * {@inheritDoc}
2267 */
2268 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
2269 return p != null;
2270 }
2271
2272 /**
2273 * Interface definition for a callback to be invoked when the hierarchy
2274 * within this view changed. The hierarchy changes whenever a child is added
2275 * to or removed from this view.
2276 */
2277 public interface OnHierarchyChangeListener {
2278 /**
2279 * Called when a new child is added to a parent view.
2280 *
2281 * @param parent the view in which a child was added
2282 * @param child the new child view added in the hierarchy
2283 */
2284 void onChildViewAdded(View parent, View child);
2285
2286 /**
2287 * Called when a child is removed from a parent view.
2288 *
2289 * @param parent the view from which the child was removed
2290 * @param child the child removed from the hierarchy
2291 */
2292 void onChildViewRemoved(View parent, View child);
2293 }
2294
2295 /**
2296 * Register a callback to be invoked when a child is added to or removed
2297 * from this view.
2298 *
2299 * @param listener the callback to invoke on hierarchy change
2300 */
2301 public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) {
2302 mOnHierarchyChangeListener = listener;
2303 }
2304
2305 /**
2306 * Adds a view during layout. This is useful if in your onLayout() method,
2307 * you need to add more views (as does the list view for example).
2308 *
2309 * If index is negative, it means put it at the end of the list.
2310 *
2311 * @param child the view to add to the group
2312 * @param index the index at which the child must be added
2313 * @param params the layout parameters to associate with the child
2314 * @return true if the child was added, false otherwise
2315 */
2316 protected boolean addViewInLayout(View child, int index, LayoutParams params) {
2317 return addViewInLayout(child, index, params, false);
2318 }
2319
2320 /**
2321 * Adds a view during layout. This is useful if in your onLayout() method,
2322 * you need to add more views (as does the list view for example).
2323 *
2324 * If index is negative, it means put it at the end of the list.
2325 *
2326 * @param child the view to add to the group
2327 * @param index the index at which the child must be added
2328 * @param params the layout parameters to associate with the child
2329 * @param preventRequestLayout if true, calling this method will not trigger a
2330 * layout request on child
2331 * @return true if the child was added, false otherwise
2332 */
2333 protected boolean addViewInLayout(View child, int index, LayoutParams params,
2334 boolean preventRequestLayout) {
2335 child.mParent = null;
2336 addViewInner(child, index, params, preventRequestLayout);
Romain Guy24443ea2009-05-11 11:56:30 -07002337 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 return true;
2339 }
2340
2341 /**
2342 * Prevents the specified child to be laid out during the next layout pass.
2343 *
2344 * @param child the child on which to perform the cleanup
2345 */
2346 protected void cleanupLayoutState(View child) {
2347 child.mPrivateFlags &= ~View.FORCE_LAYOUT;
2348 }
2349
2350 private void addViewInner(View child, int index, LayoutParams params,
2351 boolean preventRequestLayout) {
2352
2353 if (child.getParent() != null) {
2354 throw new IllegalStateException("The specified child already has a parent. " +
2355 "You must call removeView() on the child's parent first.");
2356 }
2357
Chet Haase21cd1382010-09-01 17:42:29 -07002358 if (mTransition != null) {
2359 mTransition.childAdd(this, child);
2360 }
2361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 if (!checkLayoutParams(params)) {
2363 params = generateLayoutParams(params);
2364 }
2365
2366 if (preventRequestLayout) {
2367 child.mLayoutParams = params;
2368 } else {
2369 child.setLayoutParams(params);
2370 }
2371
2372 if (index < 0) {
2373 index = mChildrenCount;
2374 }
2375
2376 addInArray(child, index);
2377
2378 // tell our children
2379 if (preventRequestLayout) {
2380 child.assignParent(this);
2381 } else {
2382 child.mParent = this;
2383 }
2384
2385 if (child.hasFocus()) {
2386 requestChildFocus(child, child.findFocus());
2387 }
Romain Guy8506ab42009-06-11 17:35:47 -07002388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 AttachInfo ai = mAttachInfo;
2390 if (ai != null) {
Romain Guy8506ab42009-06-11 17:35:47 -07002391 boolean lastKeepOn = ai.mKeepScreenOn;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 ai.mKeepScreenOn = false;
2393 child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK));
2394 if (ai.mKeepScreenOn) {
2395 needGlobalAttributesUpdate(true);
2396 }
2397 ai.mKeepScreenOn = lastKeepOn;
2398 }
2399
2400 if (mOnHierarchyChangeListener != null) {
2401 mOnHierarchyChangeListener.onChildViewAdded(this, child);
2402 }
2403
2404 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) {
2405 mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE;
2406 }
2407 }
2408
2409 private void addInArray(View child, int index) {
2410 View[] children = mChildren;
2411 final int count = mChildrenCount;
2412 final int size = children.length;
2413 if (index == count) {
2414 if (size == count) {
2415 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
2416 System.arraycopy(children, 0, mChildren, 0, size);
2417 children = mChildren;
2418 }
2419 children[mChildrenCount++] = child;
2420 } else if (index < count) {
2421 if (size == count) {
2422 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];
2423 System.arraycopy(children, 0, mChildren, 0, index);
2424 System.arraycopy(children, index, mChildren, index + 1, count - index);
2425 children = mChildren;
2426 } else {
2427 System.arraycopy(children, index, children, index + 1, count - index);
2428 }
2429 children[index] = child;
2430 mChildrenCount++;
2431 } else {
2432 throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
2433 }
2434 }
2435
2436 // This method also sets the child's mParent to null
2437 private void removeFromArray(int index) {
2438 final View[] children = mChildren;
Chet Haase21cd1382010-09-01 17:42:29 -07002439 if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) {
2440 children[index].mParent = null;
2441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 final int count = mChildrenCount;
2443 if (index == count - 1) {
2444 children[--mChildrenCount] = null;
2445 } else if (index >= 0 && index < count) {
2446 System.arraycopy(children, index + 1, children, index, count - index - 1);
2447 children[--mChildrenCount] = null;
2448 } else {
2449 throw new IndexOutOfBoundsException();
2450 }
2451 }
2452
2453 // This method also sets the children's mParent to null
2454 private void removeFromArray(int start, int count) {
2455 final View[] children = mChildren;
2456 final int childrenCount = mChildrenCount;
2457
2458 start = Math.max(0, start);
2459 final int end = Math.min(childrenCount, start + count);
2460
2461 if (start == end) {
2462 return;
2463 }
2464
2465 if (end == childrenCount) {
2466 for (int i = start; i < end; i++) {
2467 children[i].mParent = null;
2468 children[i] = null;
2469 }
2470 } else {
2471 for (int i = start; i < end; i++) {
2472 children[i].mParent = null;
2473 }
2474
2475 // Since we're looping above, we might as well do the copy, but is arraycopy()
2476 // faster than the extra 2 bounds checks we would do in the loop?
2477 System.arraycopy(children, end, children, start, childrenCount - end);
2478
2479 for (int i = childrenCount - (end - start); i < childrenCount; i++) {
2480 children[i] = null;
2481 }
2482 }
2483
2484 mChildrenCount -= (end - start);
2485 }
2486
2487 private void bindLayoutAnimation(View child) {
2488 Animation a = mLayoutAnimationController.getAnimationForView(child);
2489 child.setAnimation(a);
2490 }
2491
2492 /**
2493 * Subclasses should override this method to set layout animation
2494 * parameters on the supplied child.
2495 *
2496 * @param child the child to associate with animation parameters
2497 * @param params the child's layout parameters which hold the animation
2498 * parameters
2499 * @param index the index of the child in the view group
2500 * @param count the number of children in the view group
2501 */
2502 protected void attachLayoutAnimationParameters(View child,
2503 LayoutParams params, int index, int count) {
2504 LayoutAnimationController.AnimationParameters animationParams =
2505 params.layoutAnimationParameters;
2506 if (animationParams == null) {
2507 animationParams = new LayoutAnimationController.AnimationParameters();
2508 params.layoutAnimationParameters = animationParams;
2509 }
2510
2511 animationParams.count = count;
2512 animationParams.index = index;
2513 }
2514
2515 /**
2516 * {@inheritDoc}
2517 */
2518 public void removeView(View view) {
2519 removeViewInternal(view);
2520 requestLayout();
2521 invalidate();
2522 }
2523
2524 /**
2525 * Removes a view during layout. This is useful if in your onLayout() method,
2526 * you need to remove more views.
2527 *
2528 * @param view the view to remove from the group
2529 */
2530 public void removeViewInLayout(View view) {
2531 removeViewInternal(view);
2532 }
2533
2534 /**
2535 * Removes a range of views during layout. This is useful if in your onLayout() method,
2536 * you need to remove more views.
2537 *
2538 * @param start the index of the first view to remove from the group
2539 * @param count the number of views to remove from the group
2540 */
2541 public void removeViewsInLayout(int start, int count) {
2542 removeViewsInternal(start, count);
2543 }
2544
2545 /**
2546 * Removes the view at the specified position in the group.
2547 *
2548 * @param index the position in the group of the view to remove
2549 */
2550 public void removeViewAt(int index) {
2551 removeViewInternal(index, getChildAt(index));
2552 requestLayout();
2553 invalidate();
2554 }
2555
2556 /**
2557 * Removes the specified range of views from the group.
2558 *
2559 * @param start the first position in the group of the range of views to remove
2560 * @param count the number of views to remove
2561 */
2562 public void removeViews(int start, int count) {
2563 removeViewsInternal(start, count);
2564 requestLayout();
2565 invalidate();
2566 }
2567
2568 private void removeViewInternal(View view) {
2569 final int index = indexOfChild(view);
2570 if (index >= 0) {
2571 removeViewInternal(index, view);
2572 }
2573 }
2574
2575 private void removeViewInternal(int index, View view) {
Chet Haase21cd1382010-09-01 17:42:29 -07002576
2577 if (mTransition != null) {
2578 mTransition.childRemove(this, view);
2579 }
2580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 boolean clearChildFocus = false;
2582 if (view == mFocused) {
2583 view.clearFocusForRemoval();
2584 clearChildFocus = true;
2585 }
2586
Chet Haase21cd1382010-09-01 17:42:29 -07002587 if (view.getAnimation() != null ||
2588 (mTransitioningViews != null && mTransitioningViews.contains(view))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 addDisappearingView(view);
2590 } else if (view.mAttachInfo != null) {
2591 view.dispatchDetachedFromWindow();
2592 }
2593
2594 if (mOnHierarchyChangeListener != null) {
2595 mOnHierarchyChangeListener.onChildViewRemoved(this, view);
2596 }
2597
2598 needGlobalAttributesUpdate(false);
Romain Guy8506ab42009-06-11 17:35:47 -07002599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 removeFromArray(index);
2601
2602 if (clearChildFocus) {
2603 clearChildFocus(view);
2604 }
2605 }
2606
Chet Haase21cd1382010-09-01 17:42:29 -07002607 /**
2608 * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
2609 * not null, changes in layout which occur because of children being added to or removed from
2610 * the ViewGroup will be animated according to the animations defined in that LayoutTransition
2611 * object. By default, the transition object is null (so layout changes are not animated).
2612 *
2613 * @param transition The LayoutTransition object that will animated changes in layout. A value
2614 * of <code>null</code> means no transition will run on layout changes.
Chet Haase13cc1202010-09-03 15:39:20 -07002615 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges
Chet Haase21cd1382010-09-01 17:42:29 -07002616 */
2617 public void setLayoutTransition(LayoutTransition transition) {
Chet Haaseb20db3e2010-09-10 13:07:30 -07002618 if (mTransition != null) {
2619 mTransition.removeTransitionListener(mLayoutTransitionListener);
2620 }
Chet Haase21cd1382010-09-01 17:42:29 -07002621 mTransition = transition;
Chet Haase13cc1202010-09-03 15:39:20 -07002622 if (mTransition != null) {
2623 mTransition.addTransitionListener(mLayoutTransitionListener);
2624 }
2625 }
2626
2627 /**
2628 * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is
2629 * not null, changes in layout which occur because of children being added to or removed from
2630 * the ViewGroup will be animated according to the animations defined in that LayoutTransition
2631 * object. By default, the transition object is null (so layout changes are not animated).
2632 *
2633 * @return LayoutTranstion The LayoutTransition object that will animated changes in layout.
2634 * A value of <code>null</code> means no transition will run on layout changes.
2635 */
2636 public LayoutTransition getLayoutTransition() {
2637 return mTransition;
Chet Haase21cd1382010-09-01 17:42:29 -07002638 }
2639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 private void removeViewsInternal(int start, int count) {
2641 final OnHierarchyChangeListener onHierarchyChangeListener = mOnHierarchyChangeListener;
2642 final boolean notifyListener = onHierarchyChangeListener != null;
2643 final View focused = mFocused;
2644 final boolean detach = mAttachInfo != null;
2645 View clearChildFocus = null;
2646
2647 final View[] children = mChildren;
2648 final int end = start + count;
2649
2650 for (int i = start; i < end; i++) {
2651 final View view = children[i];
2652
Chet Haase21cd1382010-09-01 17:42:29 -07002653 if (mTransition != null) {
2654 mTransition.childRemove(this, view);
2655 }
2656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002657 if (view == focused) {
2658 view.clearFocusForRemoval();
2659 clearChildFocus = view;
2660 }
2661
Chet Haase21cd1382010-09-01 17:42:29 -07002662 if (view.getAnimation() != null ||
2663 (mTransitioningViews != null && mTransitioningViews.contains(view))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 addDisappearingView(view);
2665 } else if (detach) {
2666 view.dispatchDetachedFromWindow();
2667 }
2668
2669 needGlobalAttributesUpdate(false);
Romain Guy8506ab42009-06-11 17:35:47 -07002670
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 if (notifyListener) {
2672 onHierarchyChangeListener.onChildViewRemoved(this, view);
2673 }
2674 }
2675
2676 removeFromArray(start, count);
2677
2678 if (clearChildFocus != null) {
2679 clearChildFocus(clearChildFocus);
2680 }
2681 }
2682
2683 /**
2684 * Call this method to remove all child views from the
2685 * ViewGroup.
2686 */
2687 public void removeAllViews() {
2688 removeAllViewsInLayout();
2689 requestLayout();
2690 invalidate();
2691 }
2692
2693 /**
2694 * Called by a ViewGroup subclass to remove child views from itself,
2695 * when it must first know its size on screen before it can calculate how many
2696 * child views it will render. An example is a Gallery or a ListView, which
2697 * may "have" 50 children, but actually only render the number of children
2698 * that can currently fit inside the object on screen. Do not call
2699 * this method unless you are extending ViewGroup and understand the
2700 * view measuring and layout pipeline.
2701 */
2702 public void removeAllViewsInLayout() {
2703 final int count = mChildrenCount;
2704 if (count <= 0) {
2705 return;
2706 }
2707
2708 final View[] children = mChildren;
2709 mChildrenCount = 0;
2710
2711 final OnHierarchyChangeListener listener = mOnHierarchyChangeListener;
2712 final boolean notify = listener != null;
2713 final View focused = mFocused;
2714 final boolean detach = mAttachInfo != null;
2715 View clearChildFocus = null;
2716
2717 needGlobalAttributesUpdate(false);
Romain Guy8506ab42009-06-11 17:35:47 -07002718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 for (int i = count - 1; i >= 0; i--) {
2720 final View view = children[i];
2721
Chet Haase21cd1382010-09-01 17:42:29 -07002722 if (mTransition != null) {
2723 mTransition.childRemove(this, view);
2724 }
2725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002726 if (view == focused) {
2727 view.clearFocusForRemoval();
2728 clearChildFocus = view;
2729 }
2730
Chet Haase21cd1382010-09-01 17:42:29 -07002731 if (view.getAnimation() != null ||
2732 (mTransitioningViews != null && mTransitioningViews.contains(view))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 addDisappearingView(view);
2734 } else if (detach) {
2735 view.dispatchDetachedFromWindow();
2736 }
2737
2738 if (notify) {
2739 listener.onChildViewRemoved(this, view);
2740 }
2741
2742 view.mParent = null;
2743 children[i] = null;
2744 }
2745
2746 if (clearChildFocus != null) {
2747 clearChildFocus(clearChildFocus);
2748 }
2749 }
2750
2751 /**
2752 * Finishes the removal of a detached view. This method will dispatch the detached from
2753 * window event and notify the hierarchy change listener.
2754 *
2755 * @param child the child to be definitely removed from the view hierarchy
2756 * @param animate if true and the view has an animation, the view is placed in the
2757 * disappearing views list, otherwise, it is detached from the window
2758 *
2759 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2760 * @see #detachAllViewsFromParent()
2761 * @see #detachViewFromParent(View)
2762 * @see #detachViewFromParent(int)
2763 */
2764 protected void removeDetachedView(View child, boolean animate) {
Chet Haase21cd1382010-09-01 17:42:29 -07002765 if (mTransition != null) {
2766 mTransition.childRemove(this, child);
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 if (child == mFocused) {
2770 child.clearFocus();
2771 }
Romain Guy8506ab42009-06-11 17:35:47 -07002772
Chet Haase21cd1382010-09-01 17:42:29 -07002773 if ((animate && child.getAnimation() != null) ||
2774 (mTransitioningViews != null && mTransitioningViews.contains(child))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 addDisappearingView(child);
2776 } else if (child.mAttachInfo != null) {
2777 child.dispatchDetachedFromWindow();
2778 }
2779
2780 if (mOnHierarchyChangeListener != null) {
2781 mOnHierarchyChangeListener.onChildViewRemoved(this, child);
2782 }
2783 }
2784
2785 /**
2786 * Attaches a view to this view group. Attaching a view assigns this group as the parent,
2787 * sets the layout parameters and puts the view in the list of children so it can be retrieved
2788 * by calling {@link #getChildAt(int)}.
2789 *
2790 * This method should be called only for view which were detached from their parent.
2791 *
2792 * @param child the child to attach
2793 * @param index the index at which the child should be attached
2794 * @param params the layout parameters of the child
2795 *
2796 * @see #removeDetachedView(View, boolean)
2797 * @see #detachAllViewsFromParent()
2798 * @see #detachViewFromParent(View)
2799 * @see #detachViewFromParent(int)
2800 */
2801 protected void attachViewToParent(View child, int index, LayoutParams params) {
2802 child.mLayoutParams = params;
2803
2804 if (index < 0) {
2805 index = mChildrenCount;
2806 }
2807
2808 addInArray(child, index);
2809
2810 child.mParent = this;
Romain Guybc9fdc92010-01-19 13:27:48 -08002811 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) | DRAWN;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812
2813 if (child.hasFocus()) {
2814 requestChildFocus(child, child.findFocus());
2815 }
2816 }
2817
2818 /**
2819 * Detaches a view from its parent. Detaching a view should be temporary and followed
2820 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2821 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
2822 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2823 *
2824 * @param child the child to detach
2825 *
2826 * @see #detachViewFromParent(int)
2827 * @see #detachViewsFromParent(int, int)
2828 * @see #detachAllViewsFromParent()
2829 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2830 * @see #removeDetachedView(View, boolean)
2831 */
2832 protected void detachViewFromParent(View child) {
2833 removeFromArray(indexOfChild(child));
2834 }
2835
2836 /**
2837 * Detaches a view from its parent. Detaching a view should be temporary and followed
2838 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2839 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
2840 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2841 *
2842 * @param index the index of the child to detach
2843 *
2844 * @see #detachViewFromParent(View)
2845 * @see #detachAllViewsFromParent()
2846 * @see #detachViewsFromParent(int, int)
2847 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2848 * @see #removeDetachedView(View, boolean)
2849 */
2850 protected void detachViewFromParent(int index) {
2851 removeFromArray(index);
2852 }
2853
2854 /**
2855 * Detaches a range of view from their parent. Detaching a view should be temporary and followed
2856 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2857 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its
2858 * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2859 *
2860 * @param start the first index of the childrend range to detach
2861 * @param count the number of children to detach
2862 *
2863 * @see #detachViewFromParent(View)
2864 * @see #detachViewFromParent(int)
2865 * @see #detachAllViewsFromParent()
2866 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2867 * @see #removeDetachedView(View, boolean)
2868 */
2869 protected void detachViewsFromParent(int start, int count) {
2870 removeFromArray(start, count);
2871 }
2872
2873 /**
2874 * Detaches all views from the parent. Detaching a view should be temporary and followed
2875 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)}
2876 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached,
2877 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}.
2878 *
2879 * @see #detachViewFromParent(View)
2880 * @see #detachViewFromParent(int)
2881 * @see #detachViewsFromParent(int, int)
2882 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)
2883 * @see #removeDetachedView(View, boolean)
2884 */
2885 protected void detachAllViewsFromParent() {
2886 final int count = mChildrenCount;
2887 if (count <= 0) {
2888 return;
2889 }
2890
2891 final View[] children = mChildren;
2892 mChildrenCount = 0;
2893
2894 for (int i = count - 1; i >= 0; i--) {
2895 children[i].mParent = null;
2896 children[i] = null;
2897 }
2898 }
2899
2900 /**
2901 * Don't call or override this method. It is used for the implementation of
2902 * the view hierarchy.
2903 */
2904 public final void invalidateChild(View child, final Rect dirty) {
2905 if (ViewDebug.TRACE_HIERARCHY) {
2906 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD);
2907 }
2908
2909 ViewParent parent = this;
2910
2911 final AttachInfo attachInfo = mAttachInfo;
2912 if (attachInfo != null) {
2913 final int[] location = attachInfo.mInvalidateChildLocation;
2914 location[CHILD_LEFT_INDEX] = child.mLeft;
2915 location[CHILD_TOP_INDEX] = child.mTop;
Chet Haasec3aa3612010-06-17 08:50:37 -07002916 Matrix childMatrix = child.getMatrix();
2917 if (!childMatrix.isIdentity()) {
Chet Haase9bc829c2010-07-15 17:09:23 -07002918 RectF boundingRect = attachInfo.mTmpTransformRect;
2919 boundingRect.set(dirty);
2920 childMatrix.mapRect(boundingRect);
2921 dirty.set((int) boundingRect.left, (int) boundingRect.top,
2922 (int) (boundingRect.right + 0.5f),
2923 (int) (boundingRect.bottom + 0.5f));
Chet Haasec3aa3612010-06-17 08:50:37 -07002924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925
2926 // If the child is drawing an animation, we want to copy this flag onto
2927 // ourselves and the parent to make sure the invalidate request goes
2928 // through
2929 final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION;
Romain Guy24443ea2009-05-11 11:56:30 -07002930
2931 // Check whether the child that requests the invalidate is fully opaque
Romain Guyec25df92009-05-25 04:39:37 -07002932 final boolean isOpaque = child.isOpaque() && !drawAnimation &&
2933 child.getAnimation() != null;
Romain Guy24443ea2009-05-11 11:56:30 -07002934 // Mark the child as dirty, using the appropriate flag
2935 // Make sure we do not set both flags at the same time
2936 final int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY;
2937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 do {
Romain Guy24443ea2009-05-11 11:56:30 -07002939 View view = null;
2940 if (parent instanceof View) {
2941 view = (View) parent;
2942 }
2943
Romain Guybb93d552009-03-24 21:04:15 -07002944 if (drawAnimation) {
Romain Guy24443ea2009-05-11 11:56:30 -07002945 if (view != null) {
2946 view.mPrivateFlags |= DRAW_ANIMATION;
Romain Guybb93d552009-03-24 21:04:15 -07002947 } else if (parent instanceof ViewRoot) {
2948 ((ViewRoot) parent).mIsAnimating = true;
2949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
Romain Guy24443ea2009-05-11 11:56:30 -07002951
2952 // If the parent is dirty opaque or not dirty, mark it dirty with the opaque
2953 // flag coming from the child that initiated the invalidate
2954 if (view != null && (view.mPrivateFlags & DIRTY_MASK) != DIRTY) {
2955 view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag;
2956 }
2957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 parent = parent.invalidateChildInParent(location, dirty);
Chet Haase9bc829c2010-07-15 17:09:23 -07002959 if (view != null) {
2960 // Account for transform on current parent
2961 Matrix m = view.getMatrix();
2962 if (!m.isIdentity()) {
2963 RectF boundingRect = attachInfo.mTmpTransformRect;
2964 boundingRect.set(dirty);
2965 m.mapRect(boundingRect);
2966 dirty.set((int) boundingRect.left, (int) boundingRect.top,
2967 (int) (boundingRect.right + 0.5f),
2968 (int) (boundingRect.bottom + 0.5f));
Chet Haasec3aa3612010-06-17 08:50:37 -07002969 }
Chet Haasec3aa3612010-06-17 08:50:37 -07002970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 } while (parent != null);
2972 }
2973 }
2974
2975 /**
2976 * Don't call or override this method. It is used for the implementation of
2977 * the view hierarchy.
2978 *
2979 * This implementation returns null if this ViewGroup does not have a parent,
2980 * if this ViewGroup is already fully invalidated or if the dirty rectangle
2981 * does not intersect with this ViewGroup's bounds.
2982 */
2983 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) {
2984 if (ViewDebug.TRACE_HIERARCHY) {
2985 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD_IN_PARENT);
2986 }
2987
2988 if ((mPrivateFlags & DRAWN) == DRAWN) {
2989 if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) !=
2990 FLAG_OPTIMIZE_INVALIDATE) {
2991 dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX,
2992 location[CHILD_TOP_INDEX] - mScrollY);
2993
2994 final int left = mLeft;
2995 final int top = mTop;
2996
Adam Powell879fb6b2010-09-20 11:23:56 -07002997 if (dirty.intersect(0, 0, mRight - left, mBottom - top) ||
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) {
2999 mPrivateFlags &= ~DRAWING_CACHE_VALID;
3000
3001 location[CHILD_LEFT_INDEX] = left;
3002 location[CHILD_TOP_INDEX] = top;
3003
3004 return mParent;
3005 }
3006 } else {
3007 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID;
3008
3009 location[CHILD_LEFT_INDEX] = mLeft;
3010 location[CHILD_TOP_INDEX] = mTop;
3011
3012 dirty.set(0, 0, mRight - location[CHILD_LEFT_INDEX],
3013 mBottom - location[CHILD_TOP_INDEX]);
3014
3015 return mParent;
3016 }
3017 }
3018
3019 return null;
3020 }
3021
3022 /**
3023 * Offset a rectangle that is in a descendant's coordinate
3024 * space into our coordinate space.
3025 * @param descendant A descendant of this view
3026 * @param rect A rectangle defined in descendant's coordinate space.
3027 */
3028 public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) {
3029 offsetRectBetweenParentAndChild(descendant, rect, true, false);
3030 }
3031
3032 /**
3033 * Offset a rectangle that is in our coordinate space into an ancestor's
3034 * coordinate space.
3035 * @param descendant A descendant of this view
3036 * @param rect A rectangle defined in descendant's coordinate space.
3037 */
3038 public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) {
3039 offsetRectBetweenParentAndChild(descendant, rect, false, false);
3040 }
3041
3042 /**
3043 * Helper method that offsets a rect either from parent to descendant or
3044 * descendant to parent.
3045 */
3046 void offsetRectBetweenParentAndChild(View descendant, Rect rect,
3047 boolean offsetFromChildToParent, boolean clipToBounds) {
3048
3049 // already in the same coord system :)
3050 if (descendant == this) {
3051 return;
3052 }
3053
3054 ViewParent theParent = descendant.mParent;
3055
3056 // search and offset up to the parent
3057 while ((theParent != null)
3058 && (theParent instanceof View)
3059 && (theParent != this)) {
3060
3061 if (offsetFromChildToParent) {
3062 rect.offset(descendant.mLeft - descendant.mScrollX,
3063 descendant.mTop - descendant.mScrollY);
3064 if (clipToBounds) {
3065 View p = (View) theParent;
3066 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
3067 }
3068 } else {
3069 if (clipToBounds) {
3070 View p = (View) theParent;
3071 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop);
3072 }
3073 rect.offset(descendant.mScrollX - descendant.mLeft,
3074 descendant.mScrollY - descendant.mTop);
3075 }
3076
3077 descendant = (View) theParent;
3078 theParent = descendant.mParent;
3079 }
3080
3081 // now that we are up to this view, need to offset one more time
3082 // to get into our coordinate space
3083 if (theParent == this) {
3084 if (offsetFromChildToParent) {
3085 rect.offset(descendant.mLeft - descendant.mScrollX,
3086 descendant.mTop - descendant.mScrollY);
3087 } else {
3088 rect.offset(descendant.mScrollX - descendant.mLeft,
3089 descendant.mScrollY - descendant.mTop);
3090 }
3091 } else {
3092 throw new IllegalArgumentException("parameter must be a descendant of this view");
3093 }
3094 }
3095
3096 /**
3097 * Offset the vertical location of all children of this view by the specified number of pixels.
3098 *
3099 * @param offset the number of pixels to offset
3100 *
3101 * @hide
3102 */
3103 public void offsetChildrenTopAndBottom(int offset) {
3104 final int count = mChildrenCount;
3105 final View[] children = mChildren;
3106
3107 for (int i = 0; i < count; i++) {
3108 final View v = children[i];
3109 v.mTop += offset;
3110 v.mBottom += offset;
3111 }
3112 }
3113
3114 /**
3115 * {@inheritDoc}
3116 */
3117 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) {
3118 int dx = child.mLeft - mScrollX;
3119 int dy = child.mTop - mScrollY;
3120 if (offset != null) {
3121 offset.x += dx;
3122 offset.y += dy;
3123 }
3124 r.offset(dx, dy);
3125 return r.intersect(0, 0, mRight - mLeft, mBottom - mTop) &&
3126 (mParent == null || mParent.getChildVisibleRect(this, r, offset));
3127 }
3128
3129 /**
3130 * {@inheritDoc}
3131 */
3132 @Override
3133 protected abstract void onLayout(boolean changed,
3134 int l, int t, int r, int b);
3135
3136 /**
3137 * Indicates whether the view group has the ability to animate its children
3138 * after the first layout.
3139 *
3140 * @return true if the children can be animated, false otherwise
3141 */
3142 protected boolean canAnimate() {
3143 return mLayoutAnimationController != null;
3144 }
3145
3146 /**
3147 * Runs the layout animation. Calling this method triggers a relayout of
3148 * this view group.
3149 */
3150 public void startLayoutAnimation() {
3151 if (mLayoutAnimationController != null) {
3152 mGroupFlags |= FLAG_RUN_ANIMATION;
3153 requestLayout();
3154 }
3155 }
3156
3157 /**
3158 * Schedules the layout animation to be played after the next layout pass
3159 * of this view group. This can be used to restart the layout animation
3160 * when the content of the view group changes or when the activity is
3161 * paused and resumed.
3162 */
3163 public void scheduleLayoutAnimation() {
3164 mGroupFlags |= FLAG_RUN_ANIMATION;
3165 }
3166
3167 /**
3168 * Sets the layout animation controller used to animate the group's
3169 * children after the first layout.
3170 *
3171 * @param controller the animation controller
3172 */
3173 public void setLayoutAnimation(LayoutAnimationController controller) {
3174 mLayoutAnimationController = controller;
3175 if (mLayoutAnimationController != null) {
3176 mGroupFlags |= FLAG_RUN_ANIMATION;
3177 }
3178 }
3179
3180 /**
3181 * Returns the layout animation controller used to animate the group's
3182 * children.
3183 *
3184 * @return the current animation controller
3185 */
3186 public LayoutAnimationController getLayoutAnimation() {
3187 return mLayoutAnimationController;
3188 }
3189
3190 /**
3191 * Indicates whether the children's drawing cache is used during a layout
3192 * animation. By default, the drawing cache is enabled but this will prevent
3193 * nested layout animations from working. To nest animations, you must disable
3194 * the cache.
3195 *
3196 * @return true if the animation cache is enabled, false otherwise
3197 *
3198 * @see #setAnimationCacheEnabled(boolean)
3199 * @see View#setDrawingCacheEnabled(boolean)
3200 */
3201 @ViewDebug.ExportedProperty
3202 public boolean isAnimationCacheEnabled() {
3203 return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE;
3204 }
3205
3206 /**
3207 * Enables or disables the children's drawing cache during a layout animation.
3208 * By default, the drawing cache is enabled but this will prevent nested
3209 * layout animations from working. To nest animations, you must disable the
3210 * cache.
3211 *
3212 * @param enabled true to enable the animation cache, false otherwise
3213 *
3214 * @see #isAnimationCacheEnabled()
3215 * @see View#setDrawingCacheEnabled(boolean)
3216 */
3217 public void setAnimationCacheEnabled(boolean enabled) {
3218 setBooleanFlag(FLAG_ANIMATION_CACHE, enabled);
3219 }
3220
3221 /**
3222 * Indicates whether this ViewGroup will always try to draw its children using their
3223 * drawing cache. By default this property is enabled.
3224 *
3225 * @return true if the animation cache is enabled, false otherwise
3226 *
3227 * @see #setAlwaysDrawnWithCacheEnabled(boolean)
3228 * @see #setChildrenDrawnWithCacheEnabled(boolean)
3229 * @see View#setDrawingCacheEnabled(boolean)
3230 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003231 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 public boolean isAlwaysDrawnWithCacheEnabled() {
3233 return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE;
3234 }
3235
3236 /**
3237 * Indicates whether this ViewGroup will always try to draw its children using their
3238 * drawing cache. This property can be set to true when the cache rendering is
3239 * slightly different from the children's normal rendering. Renderings can be different,
3240 * for instance, when the cache's quality is set to low.
3241 *
3242 * When this property is disabled, the ViewGroup will use the drawing cache of its
3243 * children only when asked to. It's usually the task of subclasses to tell ViewGroup
3244 * when to start using the drawing cache and when to stop using it.
3245 *
3246 * @param always true to always draw with the drawing cache, false otherwise
3247 *
3248 * @see #isAlwaysDrawnWithCacheEnabled()
3249 * @see #setChildrenDrawnWithCacheEnabled(boolean)
3250 * @see View#setDrawingCacheEnabled(boolean)
3251 * @see View#setDrawingCacheQuality(int)
3252 */
3253 public void setAlwaysDrawnWithCacheEnabled(boolean always) {
3254 setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always);
3255 }
3256
3257 /**
3258 * Indicates whether the ViewGroup is currently drawing its children using
3259 * their drawing cache.
3260 *
3261 * @return true if children should be drawn with their cache, false otherwise
3262 *
3263 * @see #setAlwaysDrawnWithCacheEnabled(boolean)
3264 * @see #setChildrenDrawnWithCacheEnabled(boolean)
3265 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003266 @ViewDebug.ExportedProperty(category = "drawing")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 protected boolean isChildrenDrawnWithCacheEnabled() {
3268 return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE;
3269 }
3270
3271 /**
3272 * Tells the ViewGroup to draw its children using their drawing cache. This property
3273 * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache
3274 * will be used only if it has been enabled.
3275 *
3276 * Subclasses should call this method to start and stop using the drawing cache when
3277 * they perform performance sensitive operations, like scrolling or animating.
3278 *
3279 * @param enabled true if children should be drawn with their cache, false otherwise
3280 *
3281 * @see #setAlwaysDrawnWithCacheEnabled(boolean)
3282 * @see #isChildrenDrawnWithCacheEnabled()
3283 */
3284 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) {
3285 setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled);
3286 }
3287
Romain Guy293451e2009-11-04 13:59:48 -08003288 /**
3289 * Indicates whether the ViewGroup is drawing its children in the order defined by
3290 * {@link #getChildDrawingOrder(int, int)}.
3291 *
3292 * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)},
3293 * false otherwise
3294 *
3295 * @see #setChildrenDrawingOrderEnabled(boolean)
3296 * @see #getChildDrawingOrder(int, int)
3297 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003298 @ViewDebug.ExportedProperty(category = "drawing")
Romain Guy293451e2009-11-04 13:59:48 -08003299 protected boolean isChildrenDrawingOrderEnabled() {
3300 return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER;
3301 }
3302
3303 /**
3304 * Tells the ViewGroup whether to draw its children in the order defined by the method
3305 * {@link #getChildDrawingOrder(int, int)}.
3306 *
3307 * @param enabled true if the order of the children when drawing is determined by
3308 * {@link #getChildDrawingOrder(int, int)}, false otherwise
3309 *
3310 * @see #isChildrenDrawingOrderEnabled()
3311 * @see #getChildDrawingOrder(int, int)
3312 */
3313 protected void setChildrenDrawingOrderEnabled(boolean enabled) {
3314 setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled);
3315 }
3316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 private void setBooleanFlag(int flag, boolean value) {
3318 if (value) {
3319 mGroupFlags |= flag;
3320 } else {
3321 mGroupFlags &= ~flag;
3322 }
3323 }
3324
3325 /**
3326 * Returns an integer indicating what types of drawing caches are kept in memory.
3327 *
3328 * @see #setPersistentDrawingCache(int)
3329 * @see #setAnimationCacheEnabled(boolean)
3330 *
3331 * @return one or a combination of {@link #PERSISTENT_NO_CACHE},
3332 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
3333 * and {@link #PERSISTENT_ALL_CACHES}
3334 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07003335 @ViewDebug.ExportedProperty(category = "drawing", mapping = {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE, to = "NONE"),
Romain Guy203688c2010-05-12 15:41:32 -07003337 @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"),
3339 @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES, to = "ALL")
3340 })
3341 public int getPersistentDrawingCache() {
3342 return mPersistentDrawingCache;
3343 }
3344
3345 /**
3346 * Indicates what types of drawing caches should be kept in memory after
3347 * they have been created.
3348 *
3349 * @see #getPersistentDrawingCache()
3350 * @see #setAnimationCacheEnabled(boolean)
3351 *
3352 * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE},
3353 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE}
3354 * and {@link #PERSISTENT_ALL_CACHES}
3355 */
3356 public void setPersistentDrawingCache(int drawingCacheToKeep) {
3357 mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES;
3358 }
3359
3360 /**
3361 * Returns a new set of layout parameters based on the supplied attributes set.
3362 *
3363 * @param attrs the attributes to build the layout parameters from
3364 *
3365 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
3366 * of its descendants
3367 */
3368 public LayoutParams generateLayoutParams(AttributeSet attrs) {
3369 return new LayoutParams(getContext(), attrs);
3370 }
3371
3372 /**
3373 * Returns a safe set of layout parameters based on the supplied layout params.
3374 * When a ViewGroup is passed a View whose layout params do not pass the test of
3375 * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method
3376 * is invoked. This method should return a new set of layout params suitable for
3377 * this ViewGroup, possibly by copying the appropriate attributes from the
3378 * specified set of layout params.
3379 *
3380 * @param p The layout parameters to convert into a suitable set of layout parameters
3381 * for this ViewGroup.
3382 *
3383 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one
3384 * of its descendants
3385 */
3386 protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
3387 return p;
3388 }
3389
3390 /**
3391 * Returns a set of default layout parameters. These parameters are requested
3392 * when the View passed to {@link #addView(View)} has no layout parameters
3393 * already set. If null is returned, an exception is thrown from addView.
3394 *
3395 * @return a set of default layout parameters or null
3396 */
3397 protected LayoutParams generateDefaultLayoutParams() {
3398 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
3399 }
3400
3401 /**
Romain Guy13922e02009-05-12 17:56:14 -07003402 * @hide
3403 */
3404 @Override
3405 protected boolean dispatchConsistencyCheck(int consistency) {
3406 boolean result = super.dispatchConsistencyCheck(consistency);
3407
3408 final int count = mChildrenCount;
3409 final View[] children = mChildren;
3410 for (int i = 0; i < count; i++) {
3411 if (!children[i].dispatchConsistencyCheck(consistency)) result = false;
3412 }
3413
3414 return result;
3415 }
3416
3417 /**
3418 * @hide
3419 */
3420 @Override
3421 protected boolean onConsistencyCheck(int consistency) {
3422 boolean result = super.onConsistencyCheck(consistency);
3423
3424 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0;
3425 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0;
3426
3427 if (checkLayout) {
3428 final int count = mChildrenCount;
3429 final View[] children = mChildren;
3430 for (int i = 0; i < count; i++) {
3431 if (children[i].getParent() != this) {
3432 result = false;
3433 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
3434 "View " + children[i] + " has no parent/a parent that is not " + this);
3435 }
3436 }
3437 }
3438
3439 if (checkDrawing) {
3440 // If this group is dirty, check that the parent is dirty as well
3441 if ((mPrivateFlags & DIRTY_MASK) != 0) {
3442 final ViewParent parent = getParent();
3443 if (parent != null && !(parent instanceof ViewRoot)) {
3444 if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) {
3445 result = false;
3446 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG,
3447 "ViewGroup " + this + " is dirty but its parent is not: " + this);
3448 }
3449 }
3450 }
3451 }
3452
3453 return result;
3454 }
3455
3456 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 * {@inheritDoc}
3458 */
3459 @Override
3460 protected void debug(int depth) {
3461 super.debug(depth);
3462 String output;
3463
3464 if (mFocused != null) {
3465 output = debugIndent(depth);
3466 output += "mFocused";
3467 Log.d(VIEW_LOG_TAG, output);
3468 }
3469 if (mChildrenCount != 0) {
3470 output = debugIndent(depth);
3471 output += "{";
3472 Log.d(VIEW_LOG_TAG, output);
3473 }
3474 int count = mChildrenCount;
3475 for (int i = 0; i < count; i++) {
3476 View child = mChildren[i];
3477 child.debug(depth + 1);
3478 }
3479
3480 if (mChildrenCount != 0) {
3481 output = debugIndent(depth);
3482 output += "}";
3483 Log.d(VIEW_LOG_TAG, output);
3484 }
3485 }
3486
3487 /**
3488 * Returns the position in the group of the specified child view.
3489 *
3490 * @param child the view for which to get the position
3491 * @return a positive integer representing the position of the view in the
3492 * group, or -1 if the view does not exist in the group
3493 */
3494 public int indexOfChild(View child) {
3495 final int count = mChildrenCount;
3496 final View[] children = mChildren;
3497 for (int i = 0; i < count; i++) {
3498 if (children[i] == child) {
3499 return i;
3500 }
3501 }
3502 return -1;
3503 }
3504
3505 /**
3506 * Returns the number of children in the group.
3507 *
3508 * @return a positive integer representing the number of children in
3509 * the group
3510 */
3511 public int getChildCount() {
3512 return mChildrenCount;
3513 }
3514
3515 /**
3516 * Returns the view at the specified position in the group.
3517 *
3518 * @param index the position at which to get the view from
3519 * @return the view at the specified position or null if the position
3520 * does not exist within the group
3521 */
3522 public View getChildAt(int index) {
3523 try {
3524 return mChildren[index];
3525 } catch (IndexOutOfBoundsException ex) {
3526 return null;
3527 }
3528 }
3529
3530 /**
3531 * Ask all of the children of this view to measure themselves, taking into
3532 * account both the MeasureSpec requirements for this view and its padding.
3533 * We skip children that are in the GONE state The heavy lifting is done in
3534 * getChildMeasureSpec.
3535 *
3536 * @param widthMeasureSpec The width requirements for this view
3537 * @param heightMeasureSpec The height requirements for this view
3538 */
3539 protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
3540 final int size = mChildrenCount;
3541 final View[] children = mChildren;
3542 for (int i = 0; i < size; ++i) {
3543 final View child = children[i];
3544 if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
3545 measureChild(child, widthMeasureSpec, heightMeasureSpec);
3546 }
3547 }
3548 }
3549
3550 /**
3551 * Ask one of the children of this view to measure itself, taking into
3552 * account both the MeasureSpec requirements for this view and its padding.
3553 * The heavy lifting is done in getChildMeasureSpec.
3554 *
3555 * @param child The child to measure
3556 * @param parentWidthMeasureSpec The width requirements for this view
3557 * @param parentHeightMeasureSpec The height requirements for this view
3558 */
3559 protected void measureChild(View child, int parentWidthMeasureSpec,
3560 int parentHeightMeasureSpec) {
3561 final LayoutParams lp = child.getLayoutParams();
3562
3563 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
3564 mPaddingLeft + mPaddingRight, lp.width);
3565 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
3566 mPaddingTop + mPaddingBottom, lp.height);
3567
3568 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
3569 }
3570
3571 /**
3572 * Ask one of the children of this view to measure itself, taking into
3573 * account both the MeasureSpec requirements for this view and its padding
3574 * and margins. The child must have MarginLayoutParams The heavy lifting is
3575 * done in getChildMeasureSpec.
3576 *
3577 * @param child The child to measure
3578 * @param parentWidthMeasureSpec The width requirements for this view
3579 * @param widthUsed Extra space that has been used up by the parent
3580 * horizontally (possibly by other children of the parent)
3581 * @param parentHeightMeasureSpec The height requirements for this view
3582 * @param heightUsed Extra space that has been used up by the parent
3583 * vertically (possibly by other children of the parent)
3584 */
3585 protected void measureChildWithMargins(View child,
3586 int parentWidthMeasureSpec, int widthUsed,
3587 int parentHeightMeasureSpec, int heightUsed) {
3588 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
3589
3590 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
3591 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
3592 + widthUsed, lp.width);
3593 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
3594 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
3595 + heightUsed, lp.height);
3596
3597 child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
3598 }
3599
3600 /**
3601 * Does the hard part of measureChildren: figuring out the MeasureSpec to
3602 * pass to a particular child. This method figures out the right MeasureSpec
3603 * for one dimension (height or width) of one child view.
3604 *
3605 * The goal is to combine information from our MeasureSpec with the
3606 * LayoutParams of the child to get the best possible results. For example,
3607 * if the this view knows its size (because its MeasureSpec has a mode of
3608 * EXACTLY), and the child has indicated in its LayoutParams that it wants
3609 * to be the same size as the parent, the parent should ask the child to
3610 * layout given an exact size.
3611 *
3612 * @param spec The requirements for this view
3613 * @param padding The padding of this view for the current dimension and
3614 * margins, if applicable
3615 * @param childDimension How big the child wants to be in the current
3616 * dimension
3617 * @return a MeasureSpec integer for the child
3618 */
3619 public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
3620 int specMode = MeasureSpec.getMode(spec);
3621 int specSize = MeasureSpec.getSize(spec);
3622
3623 int size = Math.max(0, specSize - padding);
3624
3625 int resultSize = 0;
3626 int resultMode = 0;
3627
3628 switch (specMode) {
3629 // Parent has imposed an exact size on us
3630 case MeasureSpec.EXACTLY:
3631 if (childDimension >= 0) {
3632 resultSize = childDimension;
3633 resultMode = MeasureSpec.EXACTLY;
Romain Guy980a9382010-01-08 15:06:28 -08003634 } else if (childDimension == LayoutParams.MATCH_PARENT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 // Child wants to be our size. So be it.
3636 resultSize = size;
3637 resultMode = MeasureSpec.EXACTLY;
3638 } else if (childDimension == LayoutParams.WRAP_CONTENT) {
3639 // Child wants to determine its own size. It can't be
3640 // bigger than us.
3641 resultSize = size;
3642 resultMode = MeasureSpec.AT_MOST;
3643 }
3644 break;
3645
3646 // Parent has imposed a maximum size on us
3647 case MeasureSpec.AT_MOST:
3648 if (childDimension >= 0) {
3649 // Child wants a specific size... so be it
3650 resultSize = childDimension;
3651 resultMode = MeasureSpec.EXACTLY;
Romain Guy980a9382010-01-08 15:06:28 -08003652 } else if (childDimension == LayoutParams.MATCH_PARENT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 // Child wants to be our size, but our size is not fixed.
3654 // Constrain child to not be bigger than us.
3655 resultSize = size;
3656 resultMode = MeasureSpec.AT_MOST;
3657 } else if (childDimension == LayoutParams.WRAP_CONTENT) {
3658 // Child wants to determine its own size. It can't be
3659 // bigger than us.
3660 resultSize = size;
3661 resultMode = MeasureSpec.AT_MOST;
3662 }
3663 break;
3664
3665 // Parent asked to see how big we want to be
3666 case MeasureSpec.UNSPECIFIED:
3667 if (childDimension >= 0) {
3668 // Child wants a specific size... let him have it
3669 resultSize = childDimension;
3670 resultMode = MeasureSpec.EXACTLY;
Romain Guy980a9382010-01-08 15:06:28 -08003671 } else if (childDimension == LayoutParams.MATCH_PARENT) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 // Child wants to be our size... find out how big it should
3673 // be
3674 resultSize = 0;
3675 resultMode = MeasureSpec.UNSPECIFIED;
3676 } else if (childDimension == LayoutParams.WRAP_CONTENT) {
3677 // Child wants to determine its own size.... find out how
3678 // big it should be
3679 resultSize = 0;
3680 resultMode = MeasureSpec.UNSPECIFIED;
3681 }
3682 break;
3683 }
3684 return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
3685 }
3686
3687
3688 /**
3689 * Removes any pending animations for views that have been removed. Call
3690 * this if you don't want animations for exiting views to stack up.
3691 */
3692 public void clearDisappearingChildren() {
3693 if (mDisappearingChildren != null) {
3694 mDisappearingChildren.clear();
3695 }
3696 }
3697
3698 /**
3699 * Add a view which is removed from mChildren but still needs animation
3700 *
3701 * @param v View to add
3702 */
3703 private void addDisappearingView(View v) {
3704 ArrayList<View> disappearingChildren = mDisappearingChildren;
3705
3706 if (disappearingChildren == null) {
3707 disappearingChildren = mDisappearingChildren = new ArrayList<View>();
3708 }
3709
3710 disappearingChildren.add(v);
3711 }
3712
3713 /**
3714 * Cleanup a view when its animation is done. This may mean removing it from
3715 * the list of disappearing views.
3716 *
3717 * @param view The view whose animation has finished
3718 * @param animation The animation, cannot be null
3719 */
3720 private void finishAnimatingView(final View view, Animation animation) {
3721 final ArrayList<View> disappearingChildren = mDisappearingChildren;
3722 if (disappearingChildren != null) {
3723 if (disappearingChildren.contains(view)) {
3724 disappearingChildren.remove(view);
3725
3726 if (view.mAttachInfo != null) {
3727 view.dispatchDetachedFromWindow();
3728 }
3729
3730 view.clearAnimation();
3731 mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
3732 }
3733 }
3734
3735 if (animation != null && !animation.getFillAfter()) {
3736 view.clearAnimation();
3737 }
3738
3739 if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) {
3740 view.onAnimationEnd();
3741 // Should be performed by onAnimationEnd() but this avoid an infinite loop,
3742 // so we'd rather be safe than sorry
3743 view.mPrivateFlags &= ~ANIMATION_STARTED;
3744 // Draw one more frame after the animation is done
3745 mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
3746 }
3747 }
3748
Chet Haaseb20db3e2010-09-10 13:07:30 -07003749 /**
3750 * This method tells the ViewGroup that the given View object, which should have this
3751 * ViewGroup as its parent,
3752 * should be kept around (re-displayed when the ViewGroup draws its children) even if it
3753 * is removed from its parent. This allows animations, such as those used by
3754 * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate
3755 * the removal of views. A call to this method should always be accompanied by a later call
3756 * to {@link #endViewTransition(View)}, such as after an animation on the View has finished,
3757 * so that the View finally gets removed.
3758 *
3759 * @param view The View object to be kept visible even if it gets removed from its parent.
3760 */
3761 public void startViewTransition(View view) {
3762 if (view.mParent == this) {
3763 if (mTransitioningViews == null) {
3764 mTransitioningViews = new ArrayList<View>();
3765 }
3766 mTransitioningViews.add(view);
3767 }
3768 }
3769
3770 /**
3771 * This method should always be called following an earlier call to
3772 * {@link #startViewTransition(View)}. The given View is finally removed from its parent
3773 * and will no longer be displayed. Note that this method does not perform the functionality
3774 * of removing a view from its parent; it just discontinues the display of a View that
3775 * has previously been removed.
3776 *
3777 * @return view The View object that has been removed but is being kept around in the visible
3778 * hierarchy by an earlier call to {@link #startViewTransition(View)}.
3779 */
3780 public void endViewTransition(View view) {
3781 if (mTransitioningViews != null) {
3782 mTransitioningViews.remove(view);
3783 final ArrayList<View> disappearingChildren = mDisappearingChildren;
3784 if (disappearingChildren != null && disappearingChildren.contains(view)) {
3785 disappearingChildren.remove(view);
3786 if (view.mAttachInfo != null) {
3787 view.dispatchDetachedFromWindow();
3788 }
3789 if (view.mParent != null) {
3790 view.mParent = null;
3791 }
3792 mGroupFlags |= FLAG_INVALIDATE_REQUIRED;
3793 }
3794 }
3795 }
3796
Chet Haase21cd1382010-09-01 17:42:29 -07003797 private LayoutTransition.TransitionListener mLayoutTransitionListener =
3798 new LayoutTransition.TransitionListener() {
3799 @Override
3800 public void startTransition(LayoutTransition transition, ViewGroup container,
3801 View view, int transitionType) {
3802 // We only care about disappearing items, since we need special logic to keep
3803 // those items visible after they've been 'removed'
3804 if (transitionType == LayoutTransition.DISAPPEARING) {
Chet Haaseb20db3e2010-09-10 13:07:30 -07003805 startViewTransition(view);
Chet Haase21cd1382010-09-01 17:42:29 -07003806 }
3807 }
3808
3809 @Override
3810 public void endTransition(LayoutTransition transition, ViewGroup container,
3811 View view, int transitionType) {
3812 if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) {
Chet Haaseb20db3e2010-09-10 13:07:30 -07003813 endViewTransition(view);
Chet Haase21cd1382010-09-01 17:42:29 -07003814 }
3815 }
3816 };
3817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003818 /**
3819 * {@inheritDoc}
3820 */
3821 @Override
3822 public boolean gatherTransparentRegion(Region region) {
3823 // If no transparent regions requested, we are always opaque.
3824 final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0;
3825 if (meOpaque && region == null) {
3826 // The caller doesn't care about the region, so stop now.
3827 return true;
3828 }
3829 super.gatherTransparentRegion(region);
3830 final View[] children = mChildren;
3831 final int count = mChildrenCount;
3832 boolean noneOfTheChildrenAreTransparent = true;
3833 for (int i = 0; i < count; i++) {
3834 final View child = children[i];
3835 if ((child.mViewFlags & VISIBILITY_MASK) != GONE || child.getAnimation() != null) {
3836 if (!child.gatherTransparentRegion(region)) {
3837 noneOfTheChildrenAreTransparent = false;
3838 }
3839 }
3840 }
3841 return meOpaque || noneOfTheChildrenAreTransparent;
3842 }
3843
3844 /**
3845 * {@inheritDoc}
3846 */
3847 public void requestTransparentRegion(View child) {
3848 if (child != null) {
3849 child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS;
3850 if (mParent != null) {
3851 mParent.requestTransparentRegion(this);
3852 }
3853 }
3854 }
Romain Guy8506ab42009-06-11 17:35:47 -07003855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856
3857 @Override
3858 protected boolean fitSystemWindows(Rect insets) {
3859 boolean done = super.fitSystemWindows(insets);
3860 if (!done) {
3861 final int count = mChildrenCount;
3862 final View[] children = mChildren;
3863 for (int i = 0; i < count; i++) {
3864 done = children[i].fitSystemWindows(insets);
3865 if (done) {
3866 break;
3867 }
3868 }
3869 }
3870 return done;
3871 }
3872
3873 /**
3874 * Returns the animation listener to which layout animation events are
3875 * sent.
3876 *
3877 * @return an {@link android.view.animation.Animation.AnimationListener}
3878 */
3879 public Animation.AnimationListener getLayoutAnimationListener() {
3880 return mAnimationListener;
3881 }
3882
3883 @Override
3884 protected void drawableStateChanged() {
3885 super.drawableStateChanged();
3886
3887 if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) {
3888 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
3889 throw new IllegalStateException("addStateFromChildren cannot be enabled if a"
3890 + " child has duplicateParentState set to true");
3891 }
3892
3893 final View[] children = mChildren;
3894 final int count = mChildrenCount;
3895
3896 for (int i = 0; i < count; i++) {
3897 final View child = children[i];
3898 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) {
3899 child.refreshDrawableState();
3900 }
3901 }
3902 }
3903 }
3904
3905 @Override
3906 protected int[] onCreateDrawableState(int extraSpace) {
3907 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) {
3908 return super.onCreateDrawableState(extraSpace);
3909 }
3910
3911 int need = 0;
3912 int n = getChildCount();
3913 for (int i = 0; i < n; i++) {
3914 int[] childState = getChildAt(i).getDrawableState();
3915
3916 if (childState != null) {
3917 need += childState.length;
3918 }
3919 }
3920
3921 int[] state = super.onCreateDrawableState(extraSpace + need);
3922
3923 for (int i = 0; i < n; i++) {
3924 int[] childState = getChildAt(i).getDrawableState();
3925
3926 if (childState != null) {
3927 state = mergeDrawableStates(state, childState);
3928 }
3929 }
3930
3931 return state;
3932 }
3933
3934 /**
3935 * Sets whether this ViewGroup's drawable states also include
3936 * its children's drawable states. This is used, for example, to
3937 * make a group appear to be focused when its child EditText or button
3938 * is focused.
3939 */
3940 public void setAddStatesFromChildren(boolean addsStates) {
3941 if (addsStates) {
3942 mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN;
3943 } else {
3944 mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN;
3945 }
3946
3947 refreshDrawableState();
3948 }
3949
3950 /**
3951 * Returns whether this ViewGroup's drawable states also include
3952 * its children's drawable states. This is used, for example, to
3953 * make a group appear to be focused when its child EditText or button
3954 * is focused.
3955 */
3956 public boolean addStatesFromChildren() {
3957 return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0;
3958 }
3959
3960 /**
3961 * If {link #addStatesFromChildren} is true, refreshes this group's
3962 * drawable state (to include the states from its children).
3963 */
3964 public void childDrawableStateChanged(View child) {
3965 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) {
3966 refreshDrawableState();
3967 }
3968 }
3969
3970 /**
3971 * Specifies the animation listener to which layout animation events must
3972 * be sent. Only
3973 * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)}
3974 * and
3975 * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)}
3976 * are invoked.
3977 *
3978 * @param animationListener the layout animation listener
3979 */
3980 public void setLayoutAnimationListener(Animation.AnimationListener animationListener) {
3981 mAnimationListener = animationListener;
3982 }
3983
3984 /**
3985 * LayoutParams are used by views to tell their parents how they want to be
3986 * laid out. See
3987 * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes}
3988 * for a list of all child view attributes that this class supports.
Romain Guy8506ab42009-06-11 17:35:47 -07003989 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 * <p>
3991 * The base LayoutParams class just describes how big the view wants to be
3992 * for both width and height. For each dimension, it can specify one of:
3993 * <ul>
Dirk Dougherty75c66da2010-03-25 16:33:33 -07003994 * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
3995 * means that the view wants to be as big as its parent (minus padding)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 * <li> WRAP_CONTENT, which means that the view wants to be just big enough
3997 * to enclose its content (plus padding)
Dirk Dougherty75c66da2010-03-25 16:33:33 -07003998 * <li> an exact number
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 * </ul>
4000 * There are subclasses of LayoutParams for different subclasses of
4001 * ViewGroup. For example, AbsoluteLayout has its own subclass of
4002 * LayoutParams which adds an X and Y value.
4003 *
4004 * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
4005 * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
4006 */
4007 public static class LayoutParams {
4008 /**
Dirk Dougherty75c66da2010-03-25 16:33:33 -07004009 * Special value for the height or width requested by a View.
4010 * FILL_PARENT means that the view wants to be as big as its parent,
4011 * minus the parent's padding, if any. This value is deprecated
4012 * starting in API Level 8 and replaced by {@link #MATCH_PARENT}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 */
Romain Guy980a9382010-01-08 15:06:28 -08004014 @SuppressWarnings({"UnusedDeclaration"})
4015 @Deprecated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 public static final int FILL_PARENT = -1;
4017
4018 /**
4019 * Special value for the height or width requested by a View.
Gilles Debunnef5c6eff2010-02-09 19:08:36 -08004020 * MATCH_PARENT means that the view wants to be as big as its parent,
Dirk Dougherty75c66da2010-03-25 16:33:33 -07004021 * minus the parent's padding, if any. Introduced in API Level 8.
Romain Guy980a9382010-01-08 15:06:28 -08004022 */
4023 public static final int MATCH_PARENT = -1;
4024
4025 /**
4026 * Special value for the height or width requested by a View.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 * WRAP_CONTENT means that the view wants to be just large enough to fit
4028 * its own internal content, taking its own padding into account.
4029 */
4030 public static final int WRAP_CONTENT = -2;
4031
4032 /**
Dirk Dougherty75c66da2010-03-25 16:33:33 -07004033 * Information about how wide the view wants to be. Can be one of the
4034 * constants FILL_PARENT (replaced by MATCH_PARENT ,
4035 * in API Level 8) or WRAP_CONTENT. or an exact size.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004037 @ViewDebug.ExportedProperty(category = "layout", mapping = {
Romain Guy980a9382010-01-08 15:06:28 -08004038 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
4040 })
4041 public int width;
4042
4043 /**
Dirk Dougherty75c66da2010-03-25 16:33:33 -07004044 * Information about how tall the view wants to be. Can be one of the
4045 * constants FILL_PARENT (replaced by MATCH_PARENT ,
4046 * in API Level 8) or WRAP_CONTENT. or an exact size.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004047 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004048 @ViewDebug.ExportedProperty(category = "layout", mapping = {
Romain Guy980a9382010-01-08 15:06:28 -08004049 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004050 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT")
4051 })
4052 public int height;
4053
4054 /**
4055 * Used to animate layouts.
4056 */
4057 public LayoutAnimationController.AnimationParameters layoutAnimationParameters;
4058
4059 /**
4060 * Creates a new set of layout parameters. The values are extracted from
4061 * the supplied attributes set and context. The XML attributes mapped
4062 * to this set of layout parameters are:
4063 *
4064 * <ul>
4065 * <li><code>layout_width</code>: the width, either an exact value,
Dirk Dougherty75c66da2010-03-25 16:33:33 -07004066 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
4067 * {@link #MATCH_PARENT} in API Level 8)</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 * <li><code>layout_height</code>: the height, either an exact value,
Dirk Dougherty75c66da2010-03-25 16:33:33 -07004069 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by
4070 * {@link #MATCH_PARENT} in API Level 8)</li>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 * </ul>
4072 *
4073 * @param c the application environment
4074 * @param attrs the set of attributes from which to extract the layout
4075 * parameters' values
4076 */
4077 public LayoutParams(Context c, AttributeSet attrs) {
4078 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
4079 setBaseAttributes(a,
4080 R.styleable.ViewGroup_Layout_layout_width,
4081 R.styleable.ViewGroup_Layout_layout_height);
4082 a.recycle();
4083 }
4084
4085 /**
4086 * Creates a new set of layout parameters with the specified width
4087 * and height.
4088 *
Dirk Dougherty75c66da2010-03-25 16:33:33 -07004089 * @param width the width, either {@link #WRAP_CONTENT},
4090 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
4091 * API Level 8), or a fixed size in pixels
4092 * @param height the height, either {@link #WRAP_CONTENT},
4093 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in
4094 * API Level 8), or a fixed size in pixels
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 */
4096 public LayoutParams(int width, int height) {
4097 this.width = width;
4098 this.height = height;
4099 }
4100
4101 /**
4102 * Copy constructor. Clones the width and height values of the source.
4103 *
4104 * @param source The layout params to copy from.
4105 */
4106 public LayoutParams(LayoutParams source) {
4107 this.width = source.width;
4108 this.height = source.height;
4109 }
4110
4111 /**
4112 * Used internally by MarginLayoutParams.
4113 * @hide
4114 */
4115 LayoutParams() {
4116 }
4117
4118 /**
4119 * Extracts the layout parameters from the supplied attributes.
4120 *
4121 * @param a the style attributes to extract the parameters from
4122 * @param widthAttr the identifier of the width attribute
4123 * @param heightAttr the identifier of the height attribute
4124 */
4125 protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
4126 width = a.getLayoutDimension(widthAttr, "layout_width");
4127 height = a.getLayoutDimension(heightAttr, "layout_height");
4128 }
4129
4130 /**
4131 * Returns a String representation of this set of layout parameters.
4132 *
4133 * @param output the String to prepend to the internal representation
4134 * @return a String with the following format: output +
4135 * "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }"
Romain Guy8506ab42009-06-11 17:35:47 -07004136 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004137 * @hide
4138 */
4139 public String debug(String output) {
4140 return output + "ViewGroup.LayoutParams={ width="
4141 + sizeToString(width) + ", height=" + sizeToString(height) + " }";
4142 }
4143
4144 /**
4145 * Converts the specified size to a readable String.
4146 *
4147 * @param size the size to convert
4148 * @return a String instance representing the supplied size
Romain Guy8506ab42009-06-11 17:35:47 -07004149 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 * @hide
4151 */
4152 protected static String sizeToString(int size) {
4153 if (size == WRAP_CONTENT) {
4154 return "wrap-content";
4155 }
Romain Guy980a9382010-01-08 15:06:28 -08004156 if (size == MATCH_PARENT) {
4157 return "match-parent";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 }
4159 return String.valueOf(size);
4160 }
4161 }
4162
4163 /**
4164 * Per-child layout information for layouts that support margins.
4165 * See
4166 * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes}
4167 * for a list of all child view attributes that this class supports.
4168 */
4169 public static class MarginLayoutParams extends ViewGroup.LayoutParams {
4170 /**
4171 * The left margin in pixels of the child.
4172 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004173 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 public int leftMargin;
4175
4176 /**
4177 * The top margin in pixels of the child.
4178 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004179 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 public int topMargin;
4181
4182 /**
4183 * The right margin in pixels of the child.
4184 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004185 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 public int rightMargin;
4187
4188 /**
4189 * The bottom margin in pixels of the child.
4190 */
Konstantin Lopyrevbea95162010-08-10 17:02:18 -07004191 @ViewDebug.ExportedProperty(category = "layout")
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 public int bottomMargin;
4193
4194 /**
4195 * Creates a new set of layout parameters. The values are extracted from
4196 * the supplied attributes set and context.
4197 *
4198 * @param c the application environment
4199 * @param attrs the set of attributes from which to extract the layout
4200 * parameters' values
4201 */
4202 public MarginLayoutParams(Context c, AttributeSet attrs) {
4203 super();
4204
4205 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout);
4206 setBaseAttributes(a,
4207 R.styleable.ViewGroup_MarginLayout_layout_width,
4208 R.styleable.ViewGroup_MarginLayout_layout_height);
4209
4210 int margin = a.getDimensionPixelSize(
4211 com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1);
4212 if (margin >= 0) {
4213 leftMargin = margin;
4214 topMargin = margin;
4215 rightMargin= margin;
4216 bottomMargin = margin;
4217 } else {
4218 leftMargin = a.getDimensionPixelSize(
4219 R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0);
4220 topMargin = a.getDimensionPixelSize(
4221 R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0);
4222 rightMargin = a.getDimensionPixelSize(
4223 R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0);
4224 bottomMargin = a.getDimensionPixelSize(
4225 R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0);
4226 }
4227
4228 a.recycle();
4229 }
4230
4231 /**
4232 * {@inheritDoc}
4233 */
4234 public MarginLayoutParams(int width, int height) {
4235 super(width, height);
4236 }
4237
4238 /**
4239 * Copy constructor. Clones the width, height and margin values of the source.
4240 *
4241 * @param source The layout params to copy from.
4242 */
4243 public MarginLayoutParams(MarginLayoutParams source) {
4244 this.width = source.width;
4245 this.height = source.height;
4246
4247 this.leftMargin = source.leftMargin;
4248 this.topMargin = source.topMargin;
4249 this.rightMargin = source.rightMargin;
4250 this.bottomMargin = source.bottomMargin;
4251 }
4252
4253 /**
4254 * {@inheritDoc}
4255 */
4256 public MarginLayoutParams(LayoutParams source) {
4257 super(source);
4258 }
4259
4260 /**
4261 * Sets the margins, in pixels.
4262 *
4263 * @param left the left margin size
4264 * @param top the top margin size
4265 * @param right the right margin size
4266 * @param bottom the bottom margin size
4267 *
4268 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft
4269 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop
4270 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight
4271 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom
4272 */
4273 public void setMargins(int left, int top, int right, int bottom) {
4274 leftMargin = left;
4275 topMargin = top;
4276 rightMargin = right;
4277 bottomMargin = bottom;
4278 }
4279 }
Adam Powell2b342f02010-08-18 18:14:13 -07004280
4281 private static class SplitMotionTargets {
4282 private SparseArray<View> mTargets;
Adam Powell816c3be2010-08-23 18:00:05 -07004283 private TargetInfo[] mUniqueTargets;
Adam Powell2b342f02010-08-18 18:14:13 -07004284 private int mUniqueTargetCount;
Adam Powell2b342f02010-08-18 18:14:13 -07004285 private MotionEvent.PointerCoords[] mPointerCoords;
4286 private int[] mPointerIds;
4287
4288 private static final int INITIAL_UNIQUE_MOTION_TARGETS_SIZE = 5;
4289 private static final int INITIAL_BUCKET_SIZE = 5;
4290
4291 public SplitMotionTargets() {
4292 mTargets = new SparseArray<View>();
Adam Powell816c3be2010-08-23 18:00:05 -07004293 mUniqueTargets = new TargetInfo[INITIAL_UNIQUE_MOTION_TARGETS_SIZE];
Adam Powell2b342f02010-08-18 18:14:13 -07004294 mPointerIds = new int[INITIAL_BUCKET_SIZE];
4295 mPointerCoords = new MotionEvent.PointerCoords[INITIAL_BUCKET_SIZE];
4296 for (int i = 0; i < INITIAL_BUCKET_SIZE; i++) {
4297 mPointerCoords[i] = new MotionEvent.PointerCoords();
4298 }
4299 }
4300
4301 public void clear() {
4302 mTargets.clear();
Adam Powell816c3be2010-08-23 18:00:05 -07004303 final int count = mUniqueTargetCount;
4304 for (int i = 0; i < count; i++) {
4305 mUniqueTargets[i].recycle();
4306 mUniqueTargets[i] = null;
4307 }
Adam Powell2b342f02010-08-18 18:14:13 -07004308 mUniqueTargetCount = 0;
4309 }
4310
Adam Powell816c3be2010-08-23 18:00:05 -07004311 public void add(int pointerId, View target, long downTime) {
Adam Powell2b342f02010-08-18 18:14:13 -07004312 mTargets.put(pointerId, target);
4313
4314 final int uniqueCount = mUniqueTargetCount;
4315 boolean addUnique = true;
4316 for (int i = 0; i < uniqueCount; i++) {
Adam Powell816c3be2010-08-23 18:00:05 -07004317 if (mUniqueTargets[i].view == target) {
Adam Powell2b342f02010-08-18 18:14:13 -07004318 addUnique = false;
4319 }
4320 }
4321 if (addUnique) {
Adam Powell2b342f02010-08-18 18:14:13 -07004322 if (mUniqueTargets.length == uniqueCount) {
Adam Powell816c3be2010-08-23 18:00:05 -07004323 TargetInfo[] newTargets =
4324 new TargetInfo[uniqueCount + INITIAL_UNIQUE_MOTION_TARGETS_SIZE];
Adam Powell2b342f02010-08-18 18:14:13 -07004325 System.arraycopy(mUniqueTargets, 0, newTargets, 0, uniqueCount);
4326 mUniqueTargets = newTargets;
4327 }
Adam Powell816c3be2010-08-23 18:00:05 -07004328 mUniqueTargets[uniqueCount] = TargetInfo.obtain(target, downTime);
Adam Powell2b342f02010-08-18 18:14:13 -07004329 mUniqueTargetCount++;
4330 }
4331 }
4332
4333 public int getIdCount() {
4334 return mTargets.size();
4335 }
4336
4337 public int getUniqueTargetCount() {
4338 return mUniqueTargetCount;
4339 }
4340
Adam Powell816c3be2010-08-23 18:00:05 -07004341 public TargetInfo getUniqueTargetAt(int index) {
Adam Powell2b342f02010-08-18 18:14:13 -07004342 return mUniqueTargets[index];
4343 }
4344
4345 public View get(int id) {
4346 return mTargets.get(id);
4347 }
4348
Adam Powell2b342f02010-08-18 18:14:13 -07004349 public int indexOfTarget(View target) {
4350 return mTargets.indexOfValue(target);
4351 }
4352
Adam Powell2b342f02010-08-18 18:14:13 -07004353 public View targetAt(int index) {
4354 return mTargets.valueAt(index);
4355 }
4356
Adam Powell816c3be2010-08-23 18:00:05 -07004357 public TargetInfo getPrimaryTarget() {
Adam Powell2b342f02010-08-18 18:14:13 -07004358 if (!isEmpty()) {
Adam Powell816c3be2010-08-23 18:00:05 -07004359 // Find the longest-lived target
4360 long firstTime = Long.MAX_VALUE;
4361 int firstIndex = 0;
4362 final int uniqueCount = mUniqueTargetCount;
4363 for (int i = 0; i < uniqueCount; i++) {
4364 TargetInfo info = mUniqueTargets[i];
4365 if (info.downTime < firstTime) {
4366 firstTime = info.downTime;
4367 firstIndex = i;
4368 }
4369 }
4370 return mUniqueTargets[firstIndex];
Adam Powell2b342f02010-08-18 18:14:13 -07004371 }
4372 return null;
4373 }
4374
Adam Powell2b342f02010-08-18 18:14:13 -07004375 public boolean isEmpty() {
4376 return mUniqueTargetCount == 0;
4377 }
4378
4379 public void removeById(int id) {
4380 final int index = mTargets.indexOfKey(id);
4381 removeAt(index);
4382 }
4383
4384 public void removeView(View view) {
4385 int i = 0;
4386 while (i < mTargets.size()) {
4387 if (mTargets.valueAt(i) == view) {
4388 mTargets.removeAt(i);
4389 } else {
4390 i++;
4391 }
4392 }
4393 removeUnique(view);
4394 }
4395
4396 public void removeAt(int index) {
4397 if (index < 0 || index >= mTargets.size()) {
4398 return;
4399 }
4400
4401 final View removeView = mTargets.valueAt(index);
4402 mTargets.removeAt(index);
4403 if (mTargets.indexOfValue(removeView) < 0) {
4404 removeUnique(removeView);
4405 }
4406 }
4407
4408 private void removeUnique(View removeView) {
Adam Powell816c3be2010-08-23 18:00:05 -07004409 TargetInfo[] unique = mUniqueTargets;
Adam Powell2b342f02010-08-18 18:14:13 -07004410 int uniqueCount = mUniqueTargetCount;
4411 for (int i = 0; i < uniqueCount; i++) {
Adam Powell816c3be2010-08-23 18:00:05 -07004412 if (unique[i].view == removeView) {
4413 unique[i].recycle();
Adam Powell2b342f02010-08-18 18:14:13 -07004414 unique[i] = unique[--uniqueCount];
4415 unique[uniqueCount] = null;
4416 break;
4417 }
4418 }
4419
4420 mUniqueTargetCount = uniqueCount;
4421 }
4422
4423 /**
4424 * Return a new (obtain()ed) MotionEvent containing only data for pointers that should
4425 * be dispatched to child. Don't forget to recycle it!
4426 */
Adam Powell816c3be2010-08-23 18:00:05 -07004427 public MotionEvent filterMotionEventForChild(MotionEvent ev, View child, long downTime) {
Adam Powell2b342f02010-08-18 18:14:13 -07004428 int action = ev.getAction();
4429 final int maskedAction = action & MotionEvent.ACTION_MASK;
4430
4431 // Only send pointer up events if this child was the target. Drop it otherwise.
4432 if (maskedAction == MotionEvent.ACTION_POINTER_UP &&
4433 get(ev.getPointerId(ev.getActionIndex())) != child) {
4434 return null;
4435 }
4436
4437 int pointerCount = 0;
4438 final int idCount = getIdCount();
4439 for (int i = 0; i < idCount; i++) {
4440 if (targetAt(i) == child) {
4441 pointerCount++;
4442 }
4443 }
4444
4445 int actionId = -1;
4446 boolean needsNewIndex = false; // True if we should fill in the action's masked index
4447
4448 // If we have a down event, it wasn't counted above.
4449 if (maskedAction == MotionEvent.ACTION_DOWN) {
4450 pointerCount++;
4451 actionId = ev.getPointerId(0);
Adam Powell2b342f02010-08-18 18:14:13 -07004452 } else if (maskedAction == MotionEvent.ACTION_POINTER_DOWN) {
4453 pointerCount++;
4454
4455 actionId = ev.getPointerId(ev.getActionIndex());
4456
4457 if (indexOfTarget(child) < 0) {
4458 // The new action should be ACTION_DOWN if this child isn't currently getting
4459 // any events.
4460 action = MotionEvent.ACTION_DOWN;
4461 } else {
4462 // Fill in the index portion of the action later.
4463 needsNewIndex = true;
4464 }
4465 } else if (maskedAction == MotionEvent.ACTION_POINTER_UP) {
4466 actionId = ev.getPointerId(ev.getActionIndex());
4467 if (pointerCount == 1) {
4468 // The new action should be ACTION_UP if there's only one pointer left for
4469 // this target.
4470 action = MotionEvent.ACTION_UP;
4471 } else {
4472 // Fill in the index portion of the action later.
4473 needsNewIndex = true;
4474 }
4475 }
4476
4477 if (pointerCount == 0) {
4478 return null;
4479 }
4480
4481 // Fill the buckets with pointer data!
4482 final int eventPointerCount = ev.getPointerCount();
4483 int bucketIndex = 0;
4484 int newActionIndex = -1;
4485 for (int evp = 0; evp < eventPointerCount; evp++) {
4486 final int id = ev.getPointerId(evp);
4487
4488 // Add this pointer to the bucket if it is new or targeted at child
4489 if (id == actionId || get(id) == child) {
4490 // Expand scratch arrays if needed
4491 if (mPointerCoords.length <= bucketIndex) {
4492 int[] pointerIds = new int[pointerCount];
4493 MotionEvent.PointerCoords[] pointerCoords =
4494 new MotionEvent.PointerCoords[pointerCount];
4495 for (int i = mPointerCoords.length; i < pointerCoords.length; i++) {
4496 pointerCoords[i] = new MotionEvent.PointerCoords();
4497 }
4498
4499 System.arraycopy(mPointerCoords, 0,
4500 pointerCoords, 0, mPointerCoords.length);
4501 System.arraycopy(mPointerIds, 0, pointerIds, 0, mPointerIds.length);
4502
4503 mPointerCoords = pointerCoords;
4504 mPointerIds = pointerIds;
4505 }
4506
4507 mPointerIds[bucketIndex] = id;
4508 ev.getPointerCoords(evp, mPointerCoords[bucketIndex]);
4509
4510 if (needsNewIndex && id == actionId) {
4511 newActionIndex = bucketIndex;
4512 }
4513
4514 bucketIndex++;
4515 }
4516 }
4517
4518 // Encode the new action index if we have one
4519 if (newActionIndex >= 0) {
4520 action = (action & MotionEvent.ACTION_MASK) |
4521 (newActionIndex << MotionEvent.ACTION_POINTER_INDEX_SHIFT);
4522 }
4523
Romain Guy9b34d452010-09-02 11:45:04 -07004524 return MotionEvent.obtain(downTime, ev.getEventTime(),
Adam Powell2b342f02010-08-18 18:14:13 -07004525 action, pointerCount, mPointerIds, mPointerCoords, ev.getMetaState(),
4526 ev.getXPrecision(), ev.getYPrecision(), ev.getDeviceId(), ev.getEdgeFlags(),
Jeff Brownb380c4d2010-09-08 13:02:55 -07004527 ev.getSource(), ev.getFlags());
Adam Powell2b342f02010-08-18 18:14:13 -07004528 }
Adam Powell816c3be2010-08-23 18:00:05 -07004529
4530 static class TargetInfo {
4531 public View view;
4532 public long downTime;
4533
4534 private TargetInfo mNextRecycled;
4535
4536 private static TargetInfo sRecycleBin;
4537 private static int sRecycledCount;
4538
4539 private static int MAX_RECYCLED = 15;
4540
4541 private TargetInfo() {
4542 }
4543
4544 public static TargetInfo obtain(View v, long time) {
4545 TargetInfo info;
4546 if (sRecycleBin == null) {
4547 info = new TargetInfo();
4548 } else {
4549 info = sRecycleBin;
4550 sRecycleBin = info.mNextRecycled;
4551 sRecycledCount--;
4552 }
4553 info.view = v;
4554 info.downTime = time;
4555 return info;
4556 }
4557
4558 public void recycle() {
4559 if (sRecycledCount >= MAX_RECYCLED) {
4560 return;
4561 }
4562 mNextRecycled = sRecycleBin;
4563 sRecycleBin = this;
4564 sRecycledCount++;
4565 }
4566 }
Adam Powell2b342f02010-08-18 18:14:13 -07004567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568}