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