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