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