ViewGroup.java revision cb1404e45639d20439d7700b06d57ca1a1aad1fa
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 dispatchGenericMotionEvent(MotionEvent event) { 1128 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1129 return super.dispatchGenericMotionEvent(event); 1130 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1131 return mFocused.dispatchGenericMotionEvent(event); 1132 } 1133 return false; 1134 } 1135 1136 /** 1137 * {@inheritDoc} 1138 */ 1139 @Override 1140 public boolean dispatchTouchEvent(MotionEvent ev) { 1141 if (!onFilterTouchEventForSecurity(ev)) { 1142 return false; 1143 } 1144 1145 final int action = ev.getAction(); 1146 final int actionMasked = action & MotionEvent.ACTION_MASK; 1147 1148 // Handle an initial down. 1149 if (actionMasked == MotionEvent.ACTION_DOWN) { 1150 // Throw away all previous state when starting a new touch gesture. 1151 // The framework may have dropped the up or cancel event for the previous gesture 1152 // due to an app switch, ANR, or some other state change. 1153 cancelAndClearTouchTargets(ev); 1154 resetTouchState(); 1155 } 1156 1157 // Check for interception. 1158 final boolean intercepted; 1159 if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) { 1160 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; 1161 if (!disallowIntercept) { 1162 intercepted = onInterceptTouchEvent(ev); 1163 ev.setAction(action); // restore action in case onInterceptTouchEvent() changed it 1164 } else { 1165 intercepted = false; 1166 } 1167 } else { 1168 intercepted = true; 1169 } 1170 1171 // Check for cancelation. 1172 final boolean canceled = resetCancelNextUpFlag(this) 1173 || actionMasked == MotionEvent.ACTION_CANCEL; 1174 1175 // Update list of touch targets for pointer down, if needed. 1176 final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0; 1177 TouchTarget newTouchTarget = null; 1178 boolean alreadyDispatchedToNewTouchTarget = false; 1179 if (!canceled && !intercepted) { 1180 if (actionMasked == MotionEvent.ACTION_DOWN 1181 || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)) { 1182 final int actionIndex = ev.getActionIndex(); // always 0 for down 1183 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) 1184 : TouchTarget.ALL_POINTER_IDS; 1185 1186 // Clean up earlier touch targets for this pointer id in case they 1187 // have become out of sync. 1188 removePointersFromTouchTargets(idBitsToAssign); 1189 1190 final int childrenCount = mChildrenCount; 1191 if (childrenCount != 0) { 1192 // Find a child that can receive the event. Scan children from front to back. 1193 final View[] children = mChildren; 1194 final float x = ev.getX(actionIndex); 1195 final float y = ev.getY(actionIndex); 1196 1197 for (int i = childrenCount - 1; i >= 0; i--) { 1198 final View child = children[i]; 1199 if ((child.mViewFlags & VISIBILITY_MASK) != VISIBLE 1200 && child.getAnimation() == null) { 1201 // Skip invisible child unless it is animating. 1202 continue; 1203 } 1204 1205 if (!isTransformedTouchPointInView(x, y, child, null)) { 1206 // New pointer is out of child's bounds. 1207 continue; 1208 } 1209 1210 newTouchTarget = getTouchTarget(child); 1211 if (newTouchTarget != null) { 1212 // Child is already receiving touch within its bounds. 1213 // Give it the new pointer in addition to the ones it is handling. 1214 newTouchTarget.pointerIdBits |= idBitsToAssign; 1215 break; 1216 } 1217 1218 resetCancelNextUpFlag(child); 1219 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { 1220 // Child wants to receive touch within its bounds. 1221 mLastTouchDownTime = ev.getDownTime(); 1222 mLastTouchDownIndex = i; 1223 mLastTouchDownX = ev.getX(); 1224 mLastTouchDownY = ev.getY(); 1225 newTouchTarget = addTouchTarget(child, idBitsToAssign); 1226 alreadyDispatchedToNewTouchTarget = true; 1227 break; 1228 } 1229 } 1230 } 1231 1232 if (newTouchTarget == null && mFirstTouchTarget != null) { 1233 // Did not find a child to receive the event. 1234 // Assign the pointer to the least recently added target. 1235 newTouchTarget = mFirstTouchTarget; 1236 while (newTouchTarget.next != null) { 1237 newTouchTarget = newTouchTarget.next; 1238 } 1239 newTouchTarget.pointerIdBits |= idBitsToAssign; 1240 } 1241 } 1242 } 1243 1244 // Dispatch to touch targets. 1245 boolean handled = false; 1246 if (mFirstTouchTarget == null) { 1247 // No touch targets so treat this as an ordinary view. 1248 handled = dispatchTransformedTouchEvent(ev, canceled, null, 1249 TouchTarget.ALL_POINTER_IDS); 1250 } else { 1251 // Dispatch to touch targets, excluding the new touch target if we already 1252 // dispatched to it. Cancel touch targets if necessary. 1253 TouchTarget predecessor = null; 1254 TouchTarget target = mFirstTouchTarget; 1255 while (target != null) { 1256 final TouchTarget next = target.next; 1257 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { 1258 handled = true; 1259 } else { 1260 final boolean cancelChild = resetCancelNextUpFlag(target.child) || intercepted; 1261 if (dispatchTransformedTouchEvent(ev, cancelChild, 1262 target.child, target.pointerIdBits)) { 1263 handled = true; 1264 } 1265 if (cancelChild) { 1266 if (predecessor == null) { 1267 mFirstTouchTarget = next; 1268 } else { 1269 predecessor.next = next; 1270 } 1271 target.recycle(); 1272 target = next; 1273 continue; 1274 } 1275 } 1276 predecessor = target; 1277 target = next; 1278 } 1279 } 1280 1281 // Update list of touch targets for pointer up or cancel, if needed. 1282 if (canceled || actionMasked == MotionEvent.ACTION_UP) { 1283 resetTouchState(); 1284 } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) { 1285 final int actionIndex = ev.getActionIndex(); 1286 final int idBitsToRemove = 1 << ev.getPointerId(actionIndex); 1287 removePointersFromTouchTargets(idBitsToRemove); 1288 } 1289 1290 return handled; 1291 } 1292 1293 /** 1294 * Resets all touch state in preparation for a new cycle. 1295 */ 1296 private void resetTouchState() { 1297 clearTouchTargets(); 1298 resetCancelNextUpFlag(this); 1299 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 1300 } 1301 1302 /** 1303 * Resets the cancel next up flag. 1304 * Returns true if the flag was previously set. 1305 */ 1306 private boolean resetCancelNextUpFlag(View view) { 1307 if ((view.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) { 1308 view.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 1309 return true; 1310 } 1311 return false; 1312 } 1313 1314 /** 1315 * Clears all touch targets. 1316 */ 1317 private void clearTouchTargets() { 1318 TouchTarget target = mFirstTouchTarget; 1319 if (target != null) { 1320 do { 1321 TouchTarget next = target.next; 1322 target.recycle(); 1323 target = next; 1324 } while (target != null); 1325 mFirstTouchTarget = null; 1326 } 1327 } 1328 1329 /** 1330 * Cancels and clears all touch targets. 1331 */ 1332 private void cancelAndClearTouchTargets(MotionEvent event) { 1333 if (mFirstTouchTarget != null) { 1334 boolean syntheticEvent = false; 1335 if (event == null) { 1336 final long now = SystemClock.uptimeMillis(); 1337 event = MotionEvent.obtain(now, now, 1338 MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); 1339 syntheticEvent = true; 1340 } 1341 1342 for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) { 1343 resetCancelNextUpFlag(target.child); 1344 dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits); 1345 } 1346 clearTouchTargets(); 1347 1348 if (syntheticEvent) { 1349 event.recycle(); 1350 } 1351 } 1352 } 1353 1354 /** 1355 * Gets the touch target for specified child view. 1356 * Returns null if not found. 1357 */ 1358 private TouchTarget getTouchTarget(View child) { 1359 for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) { 1360 if (target.child == child) { 1361 return target; 1362 } 1363 } 1364 return null; 1365 } 1366 1367 /** 1368 * Adds a touch target for specified child to the beginning of the list. 1369 * Assumes the target child is not already present. 1370 */ 1371 private TouchTarget addTouchTarget(View child, int pointerIdBits) { 1372 TouchTarget target = TouchTarget.obtain(child, pointerIdBits); 1373 target.next = mFirstTouchTarget; 1374 mFirstTouchTarget = target; 1375 return target; 1376 } 1377 1378 /** 1379 * Removes the pointer ids from consideration. 1380 */ 1381 private void removePointersFromTouchTargets(int pointerIdBits) { 1382 TouchTarget predecessor = null; 1383 TouchTarget target = mFirstTouchTarget; 1384 while (target != null) { 1385 final TouchTarget next = target.next; 1386 if ((target.pointerIdBits & pointerIdBits) != 0) { 1387 target.pointerIdBits &= ~pointerIdBits; 1388 if (target.pointerIdBits == 0) { 1389 if (predecessor == null) { 1390 mFirstTouchTarget = next; 1391 } else { 1392 predecessor.next = next; 1393 } 1394 target.recycle(); 1395 target = next; 1396 continue; 1397 } 1398 } 1399 predecessor = target; 1400 target = next; 1401 } 1402 } 1403 1404 /** 1405 * Returns true if a child view contains the specified point when transformed 1406 * into its coordinate space. 1407 * Child must not be null. 1408 * @hide 1409 */ 1410 protected boolean isTransformedTouchPointInView(float x, float y, View child, 1411 PointF outLocalPoint) { 1412 float localX = x + mScrollX - child.mLeft; 1413 float localY = y + mScrollY - child.mTop; 1414 if (! child.hasIdentityMatrix() && mAttachInfo != null) { 1415 final float[] localXY = mAttachInfo.mTmpTransformLocation; 1416 localXY[0] = localX; 1417 localXY[1] = localY; 1418 child.getInverseMatrix().mapPoints(localXY); 1419 localX = localXY[0]; 1420 localY = localXY[1]; 1421 } 1422 final boolean isInView = child.pointInView(localX, localY); 1423 if (isInView && outLocalPoint != null) { 1424 outLocalPoint.set(localX, localY); 1425 } 1426 return isInView; 1427 } 1428 1429 /** 1430 * Transforms a motion event into the coordinate space of a particular child view, 1431 * filters out irrelevant pointer ids, and overrides its action if necessary. 1432 * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 1433 */ 1434 private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel, 1435 View child, int desiredPointerIdBits) { 1436 final boolean handled; 1437 1438 // Canceling motions is a special case. We don't need to perform any transformations 1439 // or filtering. The important part is the action, not the contents. 1440 final int oldAction = event.getAction(); 1441 if (cancel || oldAction == MotionEvent.ACTION_CANCEL) { 1442 event.setAction(MotionEvent.ACTION_CANCEL); 1443 if (child == null) { 1444 handled = super.dispatchTouchEvent(event); 1445 } else { 1446 handled = child.dispatchTouchEvent(event); 1447 } 1448 event.setAction(oldAction); 1449 return handled; 1450 } 1451 1452 // Calculate the number of pointers to deliver. 1453 final int oldPointerCount = event.getPointerCount(); 1454 int newPointerCount = 0; 1455 if (desiredPointerIdBits == TouchTarget.ALL_POINTER_IDS) { 1456 newPointerCount = oldPointerCount; 1457 } else { 1458 for (int i = 0; i < oldPointerCount; i++) { 1459 final int pointerId = event.getPointerId(i); 1460 final int pointerIdBit = 1 << pointerId; 1461 if ((pointerIdBit & desiredPointerIdBits) != 0) { 1462 newPointerCount += 1; 1463 } 1464 } 1465 } 1466 1467 // If for some reason we ended up in an inconsistent state where it looks like we 1468 // might produce a motion event with no pointers in it, then drop the event. 1469 if (newPointerCount == 0) { 1470 return false; 1471 } 1472 1473 // If the number of pointers is the same and we don't need to perform any fancy 1474 // irreversible transformations, then we can reuse the motion event for this 1475 // dispatch as long as we are careful to revert any changes we make. 1476 final boolean reuse = newPointerCount == oldPointerCount 1477 && (child == null || child.hasIdentityMatrix()); 1478 if (reuse) { 1479 if (child == null) { 1480 handled = super.dispatchTouchEvent(event); 1481 } else { 1482 final float offsetX = mScrollX - child.mLeft; 1483 final float offsetY = mScrollY - child.mTop; 1484 event.offsetLocation(offsetX, offsetY); 1485 1486 handled = child.dispatchTouchEvent(event); 1487 1488 event.offsetLocation(-offsetX, -offsetY); 1489 } 1490 return handled; 1491 } 1492 1493 // Make a copy of the event. 1494 // If the number of pointers is different, then we need to filter out irrelevant pointers 1495 // as we make a copy of the motion event. 1496 MotionEvent transformedEvent; 1497 if (newPointerCount == oldPointerCount) { 1498 transformedEvent = MotionEvent.obtain(event); 1499 } else { 1500 growTmpPointerArrays(newPointerCount); 1501 final int[] newPointerIndexMap = mTmpPointerIndexMap; 1502 final int[] newPointerIds = mTmpPointerIds; 1503 final MotionEvent.PointerCoords[] newPointerCoords = mTmpPointerCoords; 1504 1505 int newPointerIndex = 0; 1506 int oldPointerIndex = 0; 1507 while (newPointerIndex < newPointerCount) { 1508 final int pointerId = event.getPointerId(oldPointerIndex); 1509 final int pointerIdBits = 1 << pointerId; 1510 if ((pointerIdBits & desiredPointerIdBits) != 0) { 1511 newPointerIndexMap[newPointerIndex] = oldPointerIndex; 1512 newPointerIds[newPointerIndex] = pointerId; 1513 if (newPointerCoords[newPointerIndex] == null) { 1514 newPointerCoords[newPointerIndex] = new MotionEvent.PointerCoords(); 1515 } 1516 1517 newPointerIndex += 1; 1518 } 1519 oldPointerIndex += 1; 1520 } 1521 1522 final int newAction; 1523 if (cancel) { 1524 newAction = MotionEvent.ACTION_CANCEL; 1525 } else { 1526 final int oldMaskedAction = oldAction & MotionEvent.ACTION_MASK; 1527 if (oldMaskedAction == MotionEvent.ACTION_POINTER_DOWN 1528 || oldMaskedAction == MotionEvent.ACTION_POINTER_UP) { 1529 final int changedPointerId = event.getPointerId( 1530 (oldAction & MotionEvent.ACTION_POINTER_INDEX_MASK) 1531 >> MotionEvent.ACTION_POINTER_INDEX_SHIFT); 1532 final int changedPointerIdBits = 1 << changedPointerId; 1533 if ((changedPointerIdBits & desiredPointerIdBits) != 0) { 1534 if (newPointerCount == 1) { 1535 // The first/last pointer went down/up. 1536 newAction = oldMaskedAction == MotionEvent.ACTION_POINTER_DOWN 1537 ? MotionEvent.ACTION_DOWN : MotionEvent.ACTION_UP; 1538 } else { 1539 // A secondary pointer went down/up. 1540 int newChangedPointerIndex = 0; 1541 while (newPointerIds[newChangedPointerIndex] != changedPointerId) { 1542 newChangedPointerIndex += 1; 1543 } 1544 newAction = oldMaskedAction | (newChangedPointerIndex 1545 << MotionEvent.ACTION_POINTER_INDEX_SHIFT); 1546 } 1547 } else { 1548 // An unrelated pointer changed. 1549 newAction = MotionEvent.ACTION_MOVE; 1550 } 1551 } else { 1552 // Simple up/down/cancel/move motion action. 1553 newAction = oldMaskedAction; 1554 } 1555 } 1556 1557 transformedEvent = null; 1558 final int historySize = event.getHistorySize(); 1559 for (int historyIndex = 0; historyIndex <= historySize; historyIndex++) { 1560 for (newPointerIndex = 0; newPointerIndex < newPointerCount; newPointerIndex++) { 1561 final MotionEvent.PointerCoords c = newPointerCoords[newPointerIndex]; 1562 oldPointerIndex = newPointerIndexMap[newPointerIndex]; 1563 if (historyIndex != historySize) { 1564 event.getHistoricalPointerCoords(oldPointerIndex, historyIndex, c); 1565 } else { 1566 event.getPointerCoords(oldPointerIndex, c); 1567 } 1568 } 1569 1570 final long eventTime; 1571 if (historyIndex != historySize) { 1572 eventTime = event.getHistoricalEventTime(historyIndex); 1573 } else { 1574 eventTime = event.getEventTime(); 1575 } 1576 1577 if (transformedEvent == null) { 1578 transformedEvent = MotionEvent.obtain( 1579 event.getDownTime(), eventTime, newAction, 1580 newPointerCount, newPointerIds, newPointerCoords, 1581 event.getMetaState(), event.getXPrecision(), event.getYPrecision(), 1582 event.getDeviceId(), event.getEdgeFlags(), event.getSource(), 1583 event.getFlags()); 1584 } else { 1585 transformedEvent.addBatch(eventTime, newPointerCoords, 0); 1586 } 1587 } 1588 } 1589 1590 // Perform any necessary transformations and dispatch. 1591 if (child == null) { 1592 handled = super.dispatchTouchEvent(transformedEvent); 1593 } else { 1594 final float offsetX = mScrollX - child.mLeft; 1595 final float offsetY = mScrollY - child.mTop; 1596 transformedEvent.offsetLocation(offsetX, offsetY); 1597 if (! child.hasIdentityMatrix()) { 1598 transformedEvent.transform(child.getInverseMatrix()); 1599 } 1600 1601 handled = child.dispatchTouchEvent(transformedEvent); 1602 } 1603 1604 // Done. 1605 transformedEvent.recycle(); 1606 return handled; 1607 } 1608 1609 /** 1610 * Enlarge the temporary pointer arrays for splitting pointers. 1611 * May discard contents (but keeps PointerCoords objects to avoid reallocating them). 1612 */ 1613 private void growTmpPointerArrays(int desiredCapacity) { 1614 final MotionEvent.PointerCoords[] oldTmpPointerCoords = mTmpPointerCoords; 1615 int capacity; 1616 if (oldTmpPointerCoords != null) { 1617 capacity = oldTmpPointerCoords.length; 1618 if (desiredCapacity <= capacity) { 1619 return; 1620 } 1621 } else { 1622 capacity = 4; 1623 } 1624 1625 while (capacity < desiredCapacity) { 1626 capacity *= 2; 1627 } 1628 1629 mTmpPointerIndexMap = new int[capacity]; 1630 mTmpPointerIds = new int[capacity]; 1631 mTmpPointerCoords = new MotionEvent.PointerCoords[capacity]; 1632 1633 if (oldTmpPointerCoords != null) { 1634 System.arraycopy(oldTmpPointerCoords, 0, mTmpPointerCoords, 0, 1635 oldTmpPointerCoords.length); 1636 } 1637 } 1638 1639 /** 1640 * Enable or disable the splitting of MotionEvents to multiple children during touch event 1641 * dispatch. This behavior is enabled by default for applications that target an 1642 * SDK version of {@link Build.VERSION_CODES#HONEYCOMB} or newer. 1643 * 1644 * <p>When this option is enabled MotionEvents may be split and dispatched to different child 1645 * views depending on where each pointer initially went down. This allows for user interactions 1646 * such as scrolling two panes of content independently, chording of buttons, and performing 1647 * independent gestures on different pieces of content. 1648 * 1649 * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple 1650 * child views. <code>false</code> to only allow one child view to be the target of 1651 * any MotionEvent received by this ViewGroup. 1652 */ 1653 public void setMotionEventSplittingEnabled(boolean split) { 1654 // TODO Applications really shouldn't change this setting mid-touch event, 1655 // but perhaps this should handle that case and send ACTION_CANCELs to any child views 1656 // with gestures in progress when this is changed. 1657 if (split) { 1658 mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS; 1659 } else { 1660 mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS; 1661 } 1662 } 1663 1664 /** 1665 * Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children. 1666 * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children. 1667 */ 1668 public boolean isMotionEventSplittingEnabled() { 1669 return (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS; 1670 } 1671 1672 /** 1673 * {@inheritDoc} 1674 */ 1675 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 1676 1677 if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) { 1678 // We're already in this state, assume our ancestors are too 1679 return; 1680 } 1681 1682 if (disallowIntercept) { 1683 mGroupFlags |= FLAG_DISALLOW_INTERCEPT; 1684 } else { 1685 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 1686 } 1687 1688 // Pass it up to our parent 1689 if (mParent != null) { 1690 mParent.requestDisallowInterceptTouchEvent(disallowIntercept); 1691 } 1692 } 1693 1694 /** 1695 * Implement this method to intercept all touch screen motion events. This 1696 * allows you to watch events as they are dispatched to your children, and 1697 * take ownership of the current gesture at any point. 1698 * 1699 * <p>Using this function takes some care, as it has a fairly complicated 1700 * interaction with {@link View#onTouchEvent(MotionEvent) 1701 * View.onTouchEvent(MotionEvent)}, and using it requires implementing 1702 * that method as well as this one in the correct way. Events will be 1703 * received in the following order: 1704 * 1705 * <ol> 1706 * <li> You will receive the down event here. 1707 * <li> The down event will be handled either by a child of this view 1708 * group, or given to your own onTouchEvent() method to handle; this means 1709 * you should implement onTouchEvent() to return true, so you will 1710 * continue to see the rest of the gesture (instead of looking for 1711 * a parent view to handle it). Also, by returning true from 1712 * onTouchEvent(), you will not receive any following 1713 * events in onInterceptTouchEvent() and all touch processing must 1714 * happen in onTouchEvent() like normal. 1715 * <li> For as long as you return false from this function, each following 1716 * event (up to and including the final up) will be delivered first here 1717 * and then to the target's onTouchEvent(). 1718 * <li> If you return true from here, you will not receive any 1719 * following events: the target view will receive the same event but 1720 * with the action {@link MotionEvent#ACTION_CANCEL}, and all further 1721 * events will be delivered to your onTouchEvent() method and no longer 1722 * appear here. 1723 * </ol> 1724 * 1725 * @param ev The motion event being dispatched down the hierarchy. 1726 * @return Return true to steal motion events from the children and have 1727 * them dispatched to this ViewGroup through onTouchEvent(). 1728 * The current target will receive an ACTION_CANCEL event, and no further 1729 * messages will be delivered here. 1730 */ 1731 public boolean onInterceptTouchEvent(MotionEvent ev) { 1732 return false; 1733 } 1734 1735 /** 1736 * {@inheritDoc} 1737 * 1738 * Looks for a view to give focus to respecting the setting specified by 1739 * {@link #getDescendantFocusability()}. 1740 * 1741 * Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to 1742 * find focus within the children of this group when appropriate. 1743 * 1744 * @see #FOCUS_BEFORE_DESCENDANTS 1745 * @see #FOCUS_AFTER_DESCENDANTS 1746 * @see #FOCUS_BLOCK_DESCENDANTS 1747 * @see #onRequestFocusInDescendants 1748 */ 1749 @Override 1750 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 1751 if (DBG) { 1752 System.out.println(this + " ViewGroup.requestFocus direction=" 1753 + direction); 1754 } 1755 int descendantFocusability = getDescendantFocusability(); 1756 1757 switch (descendantFocusability) { 1758 case FOCUS_BLOCK_DESCENDANTS: 1759 return super.requestFocus(direction, previouslyFocusedRect); 1760 case FOCUS_BEFORE_DESCENDANTS: { 1761 final boolean took = super.requestFocus(direction, previouslyFocusedRect); 1762 return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect); 1763 } 1764 case FOCUS_AFTER_DESCENDANTS: { 1765 final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect); 1766 return took ? took : super.requestFocus(direction, previouslyFocusedRect); 1767 } 1768 default: 1769 throw new IllegalStateException("descendant focusability must be " 1770 + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS " 1771 + "but is " + descendantFocusability); 1772 } 1773 } 1774 1775 /** 1776 * Look for a descendant to call {@link View#requestFocus} on. 1777 * Called by {@link ViewGroup#requestFocus(int, android.graphics.Rect)} 1778 * when it wants to request focus within its children. Override this to 1779 * customize how your {@link ViewGroup} requests focus within its children. 1780 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 1781 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 1782 * to give a finer grained hint about where focus is coming from. May be null 1783 * if there is no hint. 1784 * @return Whether focus was taken. 1785 */ 1786 @SuppressWarnings({"ConstantConditions"}) 1787 protected boolean onRequestFocusInDescendants(int direction, 1788 Rect previouslyFocusedRect) { 1789 int index; 1790 int increment; 1791 int end; 1792 int count = mChildrenCount; 1793 if ((direction & FOCUS_FORWARD) != 0) { 1794 index = 0; 1795 increment = 1; 1796 end = count; 1797 } else { 1798 index = count - 1; 1799 increment = -1; 1800 end = -1; 1801 } 1802 final View[] children = mChildren; 1803 for (int i = index; i != end; i += increment) { 1804 View child = children[i]; 1805 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 1806 if (child.requestFocus(direction, previouslyFocusedRect)) { 1807 return true; 1808 } 1809 } 1810 } 1811 return false; 1812 } 1813 1814 /** 1815 * {@inheritDoc} 1816 * 1817 * @hide 1818 */ 1819 @Override 1820 public void dispatchStartTemporaryDetach() { 1821 super.dispatchStartTemporaryDetach(); 1822 final int count = mChildrenCount; 1823 final View[] children = mChildren; 1824 for (int i = 0; i < count; i++) { 1825 children[i].dispatchStartTemporaryDetach(); 1826 } 1827 } 1828 1829 /** 1830 * {@inheritDoc} 1831 * 1832 * @hide 1833 */ 1834 @Override 1835 public void dispatchFinishTemporaryDetach() { 1836 super.dispatchFinishTemporaryDetach(); 1837 final int count = mChildrenCount; 1838 final View[] children = mChildren; 1839 for (int i = 0; i < count; i++) { 1840 children[i].dispatchFinishTemporaryDetach(); 1841 } 1842 } 1843 1844 /** 1845 * {@inheritDoc} 1846 */ 1847 @Override 1848 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 1849 super.dispatchAttachedToWindow(info, visibility); 1850 visibility |= mViewFlags & VISIBILITY_MASK; 1851 final int count = mChildrenCount; 1852 final View[] children = mChildren; 1853 for (int i = 0; i < count; i++) { 1854 children[i].dispatchAttachedToWindow(info, visibility); 1855 } 1856 } 1857 1858 @Override 1859 public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) { 1860 boolean populated = false; 1861 for (int i = 0, count = getChildCount(); i < count; i++) { 1862 populated |= getChildAt(i).dispatchPopulateAccessibilityEvent(event); 1863 } 1864 return populated; 1865 } 1866 1867 /** 1868 * {@inheritDoc} 1869 */ 1870 @Override 1871 void dispatchDetachedFromWindow() { 1872 // If we still have a touch target, we are still in the process of 1873 // dispatching motion events to a child; we need to get rid of that 1874 // child to avoid dispatching events to it after the window is torn 1875 // down. To make sure we keep the child in a consistent state, we 1876 // first send it an ACTION_CANCEL motion event. 1877 cancelAndClearTouchTargets(null); 1878 1879 // In case view is detached while transition is running 1880 mLayoutSuppressed = false; 1881 1882 // Tear down our drag tracking 1883 mDragNotifiedChildren = null; 1884 if (mCurrentDrag != null) { 1885 mCurrentDrag.recycle(); 1886 mCurrentDrag = null; 1887 } 1888 1889 final int count = mChildrenCount; 1890 final View[] children = mChildren; 1891 for (int i = 0; i < count; i++) { 1892 children[i].dispatchDetachedFromWindow(); 1893 } 1894 super.dispatchDetachedFromWindow(); 1895 } 1896 1897 /** 1898 * {@inheritDoc} 1899 */ 1900 @Override 1901 public void setPadding(int left, int top, int right, int bottom) { 1902 super.setPadding(left, top, right, bottom); 1903 1904 if ((mPaddingLeft | mPaddingTop | mPaddingRight | mPaddingRight) != 0) { 1905 mGroupFlags |= FLAG_PADDING_NOT_NULL; 1906 } else { 1907 mGroupFlags &= ~FLAG_PADDING_NOT_NULL; 1908 } 1909 } 1910 1911 /** 1912 * {@inheritDoc} 1913 */ 1914 @Override 1915 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 1916 super.dispatchSaveInstanceState(container); 1917 final int count = mChildrenCount; 1918 final View[] children = mChildren; 1919 for (int i = 0; i < count; i++) { 1920 View c = children[i]; 1921 if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) { 1922 c.dispatchSaveInstanceState(container); 1923 } 1924 } 1925 } 1926 1927 /** 1928 * Perform dispatching of a {@link #saveHierarchyState freeze()} to only this view, 1929 * not to its children. For use when overriding 1930 * {@link #dispatchSaveInstanceState dispatchFreeze()} to allow subclasses to freeze 1931 * their own state but not the state of their children. 1932 * 1933 * @param container the container 1934 */ 1935 protected void dispatchFreezeSelfOnly(SparseArray<Parcelable> container) { 1936 super.dispatchSaveInstanceState(container); 1937 } 1938 1939 /** 1940 * {@inheritDoc} 1941 */ 1942 @Override 1943 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 1944 super.dispatchRestoreInstanceState(container); 1945 final int count = mChildrenCount; 1946 final View[] children = mChildren; 1947 for (int i = 0; i < count; i++) { 1948 View c = children[i]; 1949 if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) { 1950 c.dispatchRestoreInstanceState(container); 1951 } 1952 } 1953 } 1954 1955 /** 1956 * Perform dispatching of a {@link #restoreHierarchyState thaw()} to only this view, 1957 * not to its children. For use when overriding 1958 * {@link #dispatchRestoreInstanceState dispatchThaw()} to allow subclasses to thaw 1959 * their own state but not the state of their children. 1960 * 1961 * @param container the container 1962 */ 1963 protected void dispatchThawSelfOnly(SparseArray<Parcelable> container) { 1964 super.dispatchRestoreInstanceState(container); 1965 } 1966 1967 /** 1968 * Enables or disables the drawing cache for each child of this view group. 1969 * 1970 * @param enabled true to enable the cache, false to dispose of it 1971 */ 1972 protected void setChildrenDrawingCacheEnabled(boolean enabled) { 1973 if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) { 1974 final View[] children = mChildren; 1975 final int count = mChildrenCount; 1976 for (int i = 0; i < count; i++) { 1977 children[i].setDrawingCacheEnabled(enabled); 1978 } 1979 } 1980 } 1981 1982 @Override 1983 protected void onAnimationStart() { 1984 super.onAnimationStart(); 1985 1986 // When this ViewGroup's animation starts, build the cache for the children 1987 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) { 1988 final int count = mChildrenCount; 1989 final View[] children = mChildren; 1990 final boolean buildCache = !isHardwareAccelerated(); 1991 1992 for (int i = 0; i < count; i++) { 1993 final View child = children[i]; 1994 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 1995 child.setDrawingCacheEnabled(true); 1996 if (buildCache) { 1997 child.buildDrawingCache(true); 1998 } 1999 } 2000 } 2001 2002 mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE; 2003 } 2004 } 2005 2006 @Override 2007 protected void onAnimationEnd() { 2008 super.onAnimationEnd(); 2009 2010 // When this ViewGroup's animation ends, destroy the cache of the children 2011 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) { 2012 mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE; 2013 2014 if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) { 2015 setChildrenDrawingCacheEnabled(false); 2016 } 2017 } 2018 } 2019 2020 @Override 2021 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 2022 int count = mChildrenCount; 2023 int[] visibilities = null; 2024 2025 if (skipChildren) { 2026 visibilities = new int[count]; 2027 for (int i = 0; i < count; i++) { 2028 View child = getChildAt(i); 2029 visibilities[i] = child.getVisibility(); 2030 if (visibilities[i] == View.VISIBLE) { 2031 child.setVisibility(INVISIBLE); 2032 } 2033 } 2034 } 2035 2036 Bitmap b = super.createSnapshot(quality, backgroundColor, skipChildren); 2037 2038 if (skipChildren) { 2039 for (int i = 0; i < count; i++) { 2040 getChildAt(i).setVisibility(visibilities[i]); 2041 } 2042 } 2043 2044 return b; 2045 } 2046 2047 /** 2048 * {@inheritDoc} 2049 */ 2050 @Override 2051 protected void dispatchDraw(Canvas canvas) { 2052 final int count = mChildrenCount; 2053 final View[] children = mChildren; 2054 int flags = mGroupFlags; 2055 2056 if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) { 2057 final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE; 2058 2059 final boolean buildCache = !isHardwareAccelerated(); 2060 for (int i = 0; i < count; i++) { 2061 final View child = children[i]; 2062 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 2063 final LayoutParams params = child.getLayoutParams(); 2064 attachLayoutAnimationParameters(child, params, i, count); 2065 bindLayoutAnimation(child); 2066 if (cache) { 2067 child.setDrawingCacheEnabled(true); 2068 if (buildCache) { 2069 child.buildDrawingCache(true); 2070 } 2071 } 2072 } 2073 } 2074 2075 final LayoutAnimationController controller = mLayoutAnimationController; 2076 if (controller.willOverlap()) { 2077 mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE; 2078 } 2079 2080 controller.start(); 2081 2082 mGroupFlags &= ~FLAG_RUN_ANIMATION; 2083 mGroupFlags &= ~FLAG_ANIMATION_DONE; 2084 2085 if (cache) { 2086 mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE; 2087 } 2088 2089 if (mAnimationListener != null) { 2090 mAnimationListener.onAnimationStart(controller.getAnimation()); 2091 } 2092 } 2093 2094 int saveCount = 0; 2095 final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK; 2096 if (clipToPadding) { 2097 saveCount = canvas.save(); 2098 canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop, 2099 mScrollX + mRight - mLeft - mPaddingRight, 2100 mScrollY + mBottom - mTop - mPaddingBottom); 2101 2102 } 2103 2104 // We will draw our child's animation, let's reset the flag 2105 mPrivateFlags &= ~DRAW_ANIMATION; 2106 mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED; 2107 2108 boolean more = false; 2109 final long drawingTime = getDrawingTime(); 2110 2111 if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) { 2112 for (int i = 0; i < count; i++) { 2113 final View child = children[i]; 2114 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 2115 more |= drawChild(canvas, child, drawingTime); 2116 } 2117 } 2118 } else { 2119 for (int i = 0; i < count; i++) { 2120 final View child = children[getChildDrawingOrder(count, i)]; 2121 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 2122 more |= drawChild(canvas, child, drawingTime); 2123 } 2124 } 2125 } 2126 2127 // Draw any disappearing views that have animations 2128 if (mDisappearingChildren != null) { 2129 final ArrayList<View> disappearingChildren = mDisappearingChildren; 2130 final int disappearingCount = disappearingChildren.size() - 1; 2131 // Go backwards -- we may delete as animations finish 2132 for (int i = disappearingCount; i >= 0; i--) { 2133 final View child = disappearingChildren.get(i); 2134 more |= drawChild(canvas, child, drawingTime); 2135 } 2136 } 2137 2138 if (clipToPadding) { 2139 canvas.restoreToCount(saveCount); 2140 } 2141 2142 // mGroupFlags might have been updated by drawChild() 2143 flags = mGroupFlags; 2144 2145 if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) { 2146 invalidate(); 2147 } 2148 2149 if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 && 2150 mLayoutAnimationController.isDone() && !more) { 2151 // We want to erase the drawing cache and notify the listener after the 2152 // next frame is drawn because one extra invalidate() is caused by 2153 // drawChild() after the animation is over 2154 mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER; 2155 final Runnable end = new Runnable() { 2156 public void run() { 2157 notifyAnimationListener(); 2158 } 2159 }; 2160 post(end); 2161 } 2162 } 2163 2164 /** 2165 * Returns the index of the child to draw for this iteration. Override this 2166 * if you want to change the drawing order of children. By default, it 2167 * returns i. 2168 * <p> 2169 * NOTE: In order for this method to be called, you must enable child ordering 2170 * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}. 2171 * 2172 * @param i The current iteration. 2173 * @return The index of the child to draw this iteration. 2174 * 2175 * @see #setChildrenDrawingOrderEnabled(boolean) 2176 * @see #isChildrenDrawingOrderEnabled() 2177 */ 2178 protected int getChildDrawingOrder(int childCount, int i) { 2179 return i; 2180 } 2181 2182 private void notifyAnimationListener() { 2183 mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER; 2184 mGroupFlags |= FLAG_ANIMATION_DONE; 2185 2186 if (mAnimationListener != null) { 2187 final Runnable end = new Runnable() { 2188 public void run() { 2189 mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation()); 2190 } 2191 }; 2192 post(end); 2193 } 2194 2195 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) { 2196 mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE; 2197 if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) { 2198 setChildrenDrawingCacheEnabled(false); 2199 } 2200 } 2201 2202 invalidate(); 2203 } 2204 2205 /** 2206 * Draw one child of this View Group. This method is responsible for getting 2207 * the canvas in the right state. This includes clipping, translating so 2208 * that the child's scrolled origin is at 0, 0, and applying any animation 2209 * transformations. 2210 * 2211 * @param canvas The canvas on which to draw the child 2212 * @param child Who to draw 2213 * @param drawingTime The time at which draw is occuring 2214 * @return True if an invalidate() was issued 2215 */ 2216 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 2217 boolean more = false; 2218 2219 final int cl = child.mLeft; 2220 final int ct = child.mTop; 2221 final int cr = child.mRight; 2222 final int cb = child.mBottom; 2223 2224 final boolean childHasIdentityMatrix = child.hasIdentityMatrix(); 2225 2226 final int flags = mGroupFlags; 2227 2228 if ((flags & FLAG_CLEAR_TRANSFORMATION) == FLAG_CLEAR_TRANSFORMATION) { 2229 mChildTransformation.clear(); 2230 mGroupFlags &= ~FLAG_CLEAR_TRANSFORMATION; 2231 } 2232 2233 Transformation transformToApply = null; 2234 Transformation invalidationTransform; 2235 final Animation a = child.getAnimation(); 2236 boolean concatMatrix = false; 2237 2238 boolean scalingRequired = false; 2239 boolean caching; 2240 int layerType = child.getLayerType(); 2241 2242 if ((flags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE || 2243 (flags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE) { 2244 caching = true; 2245 if (mAttachInfo != null) scalingRequired = mAttachInfo.mScalingRequired; 2246 } else { 2247 caching = layerType != LAYER_TYPE_NONE; 2248 } 2249 2250 if (a != null) { 2251 final boolean initialized = a.isInitialized(); 2252 if (!initialized) { 2253 a.initialize(cr - cl, cb - ct, getWidth(), getHeight()); 2254 a.initializeInvalidateRegion(0, 0, cr - cl, cb - ct); 2255 child.onAnimationStart(); 2256 } 2257 2258 more = a.getTransformation(drawingTime, mChildTransformation, 2259 scalingRequired ? mAttachInfo.mApplicationScale : 1f); 2260 if (scalingRequired && mAttachInfo.mApplicationScale != 1f) { 2261 if (mInvalidationTransformation == null) { 2262 mInvalidationTransformation = new Transformation(); 2263 } 2264 invalidationTransform = mInvalidationTransformation; 2265 a.getTransformation(drawingTime, invalidationTransform, 1f); 2266 } else { 2267 invalidationTransform = mChildTransformation; 2268 } 2269 transformToApply = mChildTransformation; 2270 2271 concatMatrix = a.willChangeTransformationMatrix(); 2272 2273 if (more) { 2274 if (!a.willChangeBounds()) { 2275 if ((flags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) == 2276 FLAG_OPTIMIZE_INVALIDATE) { 2277 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 2278 } else if ((flags & FLAG_INVALIDATE_REQUIRED) == 0) { 2279 // The child need to draw an animation, potentially offscreen, so 2280 // make sure we do not cancel invalidate requests 2281 mPrivateFlags |= DRAW_ANIMATION; 2282 invalidate(cl, ct, cr, cb); 2283 } 2284 } else { 2285 if (mInvalidateRegion == null) { 2286 mInvalidateRegion = new RectF(); 2287 } 2288 final RectF region = mInvalidateRegion; 2289 a.getInvalidateRegion(0, 0, cr - cl, cb - ct, region, invalidationTransform); 2290 2291 // The child need to draw an animation, potentially offscreen, so 2292 // make sure we do not cancel invalidate requests 2293 mPrivateFlags |= DRAW_ANIMATION; 2294 2295 final int left = cl + (int) region.left; 2296 final int top = ct + (int) region.top; 2297 invalidate(left, top, left + (int) region.width(), top + (int) region.height()); 2298 } 2299 } 2300 } else if ((flags & FLAG_SUPPORT_STATIC_TRANSFORMATIONS) == 2301 FLAG_SUPPORT_STATIC_TRANSFORMATIONS) { 2302 final boolean hasTransform = getChildStaticTransformation(child, mChildTransformation); 2303 if (hasTransform) { 2304 final int transformType = mChildTransformation.getTransformationType(); 2305 transformToApply = transformType != Transformation.TYPE_IDENTITY ? 2306 mChildTransformation : null; 2307 concatMatrix = (transformType & Transformation.TYPE_MATRIX) != 0; 2308 } 2309 } 2310 2311 concatMatrix |= !childHasIdentityMatrix; 2312 2313 // Sets the flag as early as possible to allow draw() implementations 2314 // to call invalidate() successfully when doing animations 2315 child.mPrivateFlags |= DRAWN; 2316 2317 if (!concatMatrix && canvas.quickReject(cl, ct, cr, cb, Canvas.EdgeType.BW) && 2318 (child.mPrivateFlags & DRAW_ANIMATION) == 0) { 2319 return more; 2320 } 2321 2322 float alpha = child.getAlpha(); 2323 // Bail out early if the view does not need to be drawn 2324 if (alpha <= ViewConfiguration.ALPHA_THRESHOLD && (child.mPrivateFlags & ALPHA_SET) == 0 && 2325 !(child instanceof SurfaceView)) { 2326 return more; 2327 } 2328 2329 child.computeScroll(); 2330 2331 final int sx = child.mScrollX; 2332 final int sy = child.mScrollY; 2333 2334 DisplayList displayList = null; 2335 Bitmap cache = null; 2336 if (caching) { 2337 if (!canvas.isHardwareAccelerated()) { 2338 if (layerType != LAYER_TYPE_NONE) { 2339 layerType = LAYER_TYPE_SOFTWARE; 2340 child.buildDrawingCache(true); 2341 } 2342 cache = child.getDrawingCache(true); 2343 } else { 2344 if (layerType == LAYER_TYPE_SOFTWARE) { 2345 child.buildDrawingCache(true); 2346 cache = child.getDrawingCache(true); 2347 } else { 2348 displayList = child.getDisplayList(); 2349 } 2350 } 2351 } 2352 2353 final boolean hasDisplayList = displayList != null && displayList.isReady(); 2354 final boolean hasNoCache = cache == null || hasDisplayList; 2355 2356 final int restoreTo = canvas.save(); 2357 if (hasNoCache) { 2358 canvas.translate(cl - sx, ct - sy); 2359 } else { 2360 canvas.translate(cl, ct); 2361 if (scalingRequired) { 2362 // mAttachInfo cannot be null, otherwise scalingRequired == false 2363 final float scale = 1.0f / mAttachInfo.mApplicationScale; 2364 canvas.scale(scale, scale); 2365 } 2366 } 2367 2368 boolean layerSaved = false; 2369 2370 if (transformToApply != null || alpha < 1.0f || !child.hasIdentityMatrix()) { 2371 if (transformToApply != null || !childHasIdentityMatrix) { 2372 int transX = 0; 2373 int transY = 0; 2374 2375 if (hasNoCache) { 2376 transX = -sx; 2377 transY = -sy; 2378 } 2379 2380 if (transformToApply != null) { 2381 if (concatMatrix) { 2382 // Undo the scroll translation, apply the transformation matrix, 2383 // then redo the scroll translate to get the correct result. 2384 canvas.translate(-transX, -transY); 2385 canvas.concat(transformToApply.getMatrix()); 2386 canvas.translate(transX, transY); 2387 mGroupFlags |= FLAG_CLEAR_TRANSFORMATION; 2388 } 2389 2390 float transformAlpha = transformToApply.getAlpha(); 2391 if (transformAlpha < 1.0f) { 2392 alpha *= transformToApply.getAlpha(); 2393 mGroupFlags |= FLAG_CLEAR_TRANSFORMATION; 2394 } 2395 } 2396 2397 if (!childHasIdentityMatrix) { 2398 canvas.translate(-transX, -transY); 2399 canvas.concat(child.getMatrix()); 2400 canvas.translate(transX, transY); 2401 } 2402 } 2403 2404 if (alpha < 1.0f) { 2405 mGroupFlags |= FLAG_CLEAR_TRANSFORMATION; 2406 if (hasNoCache) { 2407 final int multipliedAlpha = (int) (255 * alpha); 2408 if (!child.onSetAlpha(multipliedAlpha)) { 2409 int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG; 2410 if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN || 2411 layerType != LAYER_TYPE_NONE) { 2412 layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG; 2413 } 2414 if (layerType != LAYER_TYPE_NONE && child.mLayerPaint != null) { 2415 child.mLayerPaint.setAlpha(multipliedAlpha); 2416 } else { 2417 canvas.saveLayerAlpha(sx, sy, sx + cr - cl, sy + cb - ct, 2418 multipliedAlpha, layerFlags); 2419 layerSaved = true; 2420 } 2421 } else { 2422 // Alpha is handled by the child directly, clobber the layer's alpha 2423 if (layerType != LAYER_TYPE_NONE && child.mLayerPaint != null) { 2424 child.mLayerPaint.setAlpha(255); 2425 } 2426 child.mPrivateFlags |= ALPHA_SET; 2427 } 2428 } 2429 } 2430 } else if ((child.mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 2431 child.onSetAlpha(255); 2432 child.mPrivateFlags &= ~ALPHA_SET; 2433 } 2434 2435 if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) { 2436 if (hasNoCache) { 2437 canvas.clipRect(sx, sy, sx + (cr - cl), sy + (cb - ct)); 2438 } else { 2439 if (!scalingRequired) { 2440 canvas.clipRect(0, 0, cr - cl, cb - ct); 2441 } else { 2442 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 2443 } 2444 } 2445 } 2446 2447 if (hasNoCache) { 2448 boolean layerRendered = false; 2449 if (!layerSaved && layerType == LAYER_TYPE_HARDWARE) { 2450 final HardwareLayer layer = child.getHardwareLayer(canvas); 2451 if (layer != null && layer.isValid()) { 2452 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, child.mLayerPaint); 2453 layerRendered = true; 2454 } else { 2455 canvas.saveLayer(sx, sy, sx + cr - cl, sy + cb - ct, child.mLayerPaint, 2456 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 2457 } 2458 } 2459 2460 if (!layerRendered) { 2461 if (!hasDisplayList) { 2462 // Fast path for layouts with no backgrounds 2463 if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 2464 if (ViewDebug.TRACE_HIERARCHY) { 2465 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 2466 } 2467 child.mPrivateFlags &= ~DIRTY_MASK; 2468 child.dispatchDraw(canvas); 2469 } else { 2470 child.draw(canvas); 2471 } 2472 } else { 2473 child.mPrivateFlags &= ~DIRTY_MASK; 2474 ((HardwareCanvas) canvas).drawDisplayList(displayList); 2475 } 2476 } 2477 } else if (cache != null) { 2478 child.mPrivateFlags &= ~DIRTY_MASK; 2479 Paint cachePaint; 2480 2481 if (layerType == LAYER_TYPE_NONE || child.mLayerPaint == null) { 2482 cachePaint = mCachePaint; 2483 if (alpha < 1.0f) { 2484 cachePaint.setAlpha((int) (alpha * 255)); 2485 mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE; 2486 } else if ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) { 2487 cachePaint.setAlpha(255); 2488 mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE; 2489 } 2490 } else { 2491 cachePaint = child.mLayerPaint; 2492 if (alpha < 1.0f) { 2493 cachePaint.setAlpha((int) (alpha * 255)); 2494 } 2495 } 2496 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 2497 } 2498 2499 canvas.restoreToCount(restoreTo); 2500 2501 if (a != null && !more) { 2502 child.onSetAlpha(255); 2503 finishAnimatingView(child, a); 2504 } 2505 2506 return more; 2507 } 2508 2509 /** 2510 * By default, children are clipped to their bounds before drawing. This 2511 * allows view groups to override this behavior for animations, etc. 2512 * 2513 * @param clipChildren true to clip children to their bounds, 2514 * false otherwise 2515 * @attr ref android.R.styleable#ViewGroup_clipChildren 2516 */ 2517 public void setClipChildren(boolean clipChildren) { 2518 setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren); 2519 } 2520 2521 /** 2522 * By default, children are clipped to the padding of the ViewGroup. This 2523 * allows view groups to override this behavior 2524 * 2525 * @param clipToPadding true to clip children to the padding of the 2526 * group, false otherwise 2527 * @attr ref android.R.styleable#ViewGroup_clipToPadding 2528 */ 2529 public void setClipToPadding(boolean clipToPadding) { 2530 setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding); 2531 } 2532 2533 /** 2534 * {@inheritDoc} 2535 */ 2536 @Override 2537 public void dispatchSetSelected(boolean selected) { 2538 final View[] children = mChildren; 2539 final int count = mChildrenCount; 2540 for (int i = 0; i < count; i++) { 2541 2542 children[i].setSelected(selected); 2543 } 2544 } 2545 2546 /** 2547 * {@inheritDoc} 2548 */ 2549 @Override 2550 public void dispatchSetActivated(boolean activated) { 2551 final View[] children = mChildren; 2552 final int count = mChildrenCount; 2553 for (int i = 0; i < count; i++) { 2554 2555 children[i].setActivated(activated); 2556 } 2557 } 2558 2559 @Override 2560 protected void dispatchSetPressed(boolean pressed) { 2561 final View[] children = mChildren; 2562 final int count = mChildrenCount; 2563 for (int i = 0; i < count; i++) { 2564 children[i].setPressed(pressed); 2565 } 2566 } 2567 2568 /** 2569 * When this property is set to true, this ViewGroup supports static transformations on 2570 * children; this causes 2571 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be 2572 * invoked when a child is drawn. 2573 * 2574 * Any subclass overriding 2575 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should 2576 * set this property to true. 2577 * 2578 * @param enabled True to enable static transformations on children, false otherwise. 2579 * 2580 * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS 2581 */ 2582 protected void setStaticTransformationsEnabled(boolean enabled) { 2583 setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled); 2584 } 2585 2586 /** 2587 * {@inheritDoc} 2588 * 2589 * @see #setStaticTransformationsEnabled(boolean) 2590 */ 2591 protected boolean getChildStaticTransformation(View child, Transformation t) { 2592 return false; 2593 } 2594 2595 /** 2596 * {@hide} 2597 */ 2598 @Override 2599 protected View findViewTraversal(int id) { 2600 if (id == mID) { 2601 return this; 2602 } 2603 2604 final View[] where = mChildren; 2605 final int len = mChildrenCount; 2606 2607 for (int i = 0; i < len; i++) { 2608 View v = where[i]; 2609 2610 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 2611 v = v.findViewById(id); 2612 2613 if (v != null) { 2614 return v; 2615 } 2616 } 2617 } 2618 2619 return null; 2620 } 2621 2622 /** 2623 * {@hide} 2624 */ 2625 @Override 2626 protected View findViewWithTagTraversal(Object tag) { 2627 if (tag != null && tag.equals(mTag)) { 2628 return this; 2629 } 2630 2631 final View[] where = mChildren; 2632 final int len = mChildrenCount; 2633 2634 for (int i = 0; i < len; i++) { 2635 View v = where[i]; 2636 2637 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 2638 v = v.findViewWithTag(tag); 2639 2640 if (v != null) { 2641 return v; 2642 } 2643 } 2644 } 2645 2646 return null; 2647 } 2648 2649 /** 2650 * {@hide} 2651 */ 2652 @Override 2653 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 2654 if (predicate.apply(this)) { 2655 return this; 2656 } 2657 2658 final View[] where = mChildren; 2659 final int len = mChildrenCount; 2660 2661 for (int i = 0; i < len; i++) { 2662 View v = where[i]; 2663 2664 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 2665 v = v.findViewByPredicate(predicate); 2666 2667 if (v != null) { 2668 return v; 2669 } 2670 } 2671 } 2672 2673 return null; 2674 } 2675 2676 /** 2677 * Adds a child view. If no layout parameters are already set on the child, the 2678 * default parameters for this ViewGroup are set on the child. 2679 * 2680 * @param child the child view to add 2681 * 2682 * @see #generateDefaultLayoutParams() 2683 */ 2684 public void addView(View child) { 2685 addView(child, -1); 2686 } 2687 2688 /** 2689 * Adds a child view. If no layout parameters are already set on the child, the 2690 * default parameters for this ViewGroup are set on the child. 2691 * 2692 * @param child the child view to add 2693 * @param index the position at which to add the child 2694 * 2695 * @see #generateDefaultLayoutParams() 2696 */ 2697 public void addView(View child, int index) { 2698 LayoutParams params = child.getLayoutParams(); 2699 if (params == null) { 2700 params = generateDefaultLayoutParams(); 2701 if (params == null) { 2702 throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); 2703 } 2704 } 2705 addView(child, index, params); 2706 } 2707 2708 /** 2709 * Adds a child view with this ViewGroup's default layout parameters and the 2710 * specified width and height. 2711 * 2712 * @param child the child view to add 2713 */ 2714 public void addView(View child, int width, int height) { 2715 final LayoutParams params = generateDefaultLayoutParams(); 2716 params.width = width; 2717 params.height = height; 2718 addView(child, -1, params); 2719 } 2720 2721 /** 2722 * Adds a child view with the specified layout parameters. 2723 * 2724 * @param child the child view to add 2725 * @param params the layout parameters to set on the child 2726 */ 2727 public void addView(View child, LayoutParams params) { 2728 addView(child, -1, params); 2729 } 2730 2731 /** 2732 * Adds a child view with the specified layout parameters. 2733 * 2734 * @param child the child view to add 2735 * @param index the position at which to add the child 2736 * @param params the layout parameters to set on the child 2737 */ 2738 public void addView(View child, int index, LayoutParams params) { 2739 if (DBG) { 2740 System.out.println(this + " addView"); 2741 } 2742 2743 // addViewInner() will call child.requestLayout() when setting the new LayoutParams 2744 // therefore, we call requestLayout() on ourselves before, so that the child's request 2745 // will be blocked at our level 2746 child.mPrivateFlags &= ~DIRTY_MASK; 2747 requestLayout(); 2748 invalidate(); 2749 addViewInner(child, index, params, false); 2750 } 2751 2752 /** 2753 * {@inheritDoc} 2754 */ 2755 public void updateViewLayout(View view, ViewGroup.LayoutParams params) { 2756 if (!checkLayoutParams(params)) { 2757 throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this); 2758 } 2759 if (view.mParent != this) { 2760 throw new IllegalArgumentException("Given view not a child of " + this); 2761 } 2762 view.setLayoutParams(params); 2763 } 2764 2765 /** 2766 * {@inheritDoc} 2767 */ 2768 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 2769 return p != null; 2770 } 2771 2772 /** 2773 * Interface definition for a callback to be invoked when the hierarchy 2774 * within this view changed. The hierarchy changes whenever a child is added 2775 * to or removed from this view. 2776 */ 2777 public interface OnHierarchyChangeListener { 2778 /** 2779 * Called when a new child is added to a parent view. 2780 * 2781 * @param parent the view in which a child was added 2782 * @param child the new child view added in the hierarchy 2783 */ 2784 void onChildViewAdded(View parent, View child); 2785 2786 /** 2787 * Called when a child is removed from a parent view. 2788 * 2789 * @param parent the view from which the child was removed 2790 * @param child the child removed from the hierarchy 2791 */ 2792 void onChildViewRemoved(View parent, View child); 2793 } 2794 2795 /** 2796 * Register a callback to be invoked when a child is added to or removed 2797 * from this view. 2798 * 2799 * @param listener the callback to invoke on hierarchy change 2800 */ 2801 public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) { 2802 mOnHierarchyChangeListener = listener; 2803 } 2804 2805 /** 2806 * Adds a view during layout. This is useful if in your onLayout() method, 2807 * you need to add more views (as does the list view for example). 2808 * 2809 * If index is negative, it means put it at the end of the list. 2810 * 2811 * @param child the view to add to the group 2812 * @param index the index at which the child must be added 2813 * @param params the layout parameters to associate with the child 2814 * @return true if the child was added, false otherwise 2815 */ 2816 protected boolean addViewInLayout(View child, int index, LayoutParams params) { 2817 return addViewInLayout(child, index, params, false); 2818 } 2819 2820 /** 2821 * Adds a view during layout. This is useful if in your onLayout() method, 2822 * you need to add more views (as does the list view for example). 2823 * 2824 * If index is negative, it means put it at the end of the list. 2825 * 2826 * @param child the view to add to the group 2827 * @param index the index at which the child must be added 2828 * @param params the layout parameters to associate with the child 2829 * @param preventRequestLayout if true, calling this method will not trigger a 2830 * layout request on child 2831 * @return true if the child was added, false otherwise 2832 */ 2833 protected boolean addViewInLayout(View child, int index, LayoutParams params, 2834 boolean preventRequestLayout) { 2835 child.mParent = null; 2836 addViewInner(child, index, params, preventRequestLayout); 2837 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN; 2838 return true; 2839 } 2840 2841 /** 2842 * Prevents the specified child to be laid out during the next layout pass. 2843 * 2844 * @param child the child on which to perform the cleanup 2845 */ 2846 protected void cleanupLayoutState(View child) { 2847 child.mPrivateFlags &= ~View.FORCE_LAYOUT; 2848 } 2849 2850 private void addViewInner(View child, int index, LayoutParams params, 2851 boolean preventRequestLayout) { 2852 2853 if (child.getParent() != null) { 2854 throw new IllegalStateException("The specified child already has a parent. " + 2855 "You must call removeView() on the child's parent first."); 2856 } 2857 2858 if (mTransition != null) { 2859 mTransition.addChild(this, child); 2860 } 2861 2862 if (!checkLayoutParams(params)) { 2863 params = generateLayoutParams(params); 2864 } 2865 2866 if (preventRequestLayout) { 2867 child.mLayoutParams = params; 2868 } else { 2869 child.setLayoutParams(params); 2870 } 2871 2872 if (index < 0) { 2873 index = mChildrenCount; 2874 } 2875 2876 addInArray(child, index); 2877 2878 // tell our children 2879 if (preventRequestLayout) { 2880 child.assignParent(this); 2881 } else { 2882 child.mParent = this; 2883 } 2884 2885 if (child.hasFocus()) { 2886 requestChildFocus(child, child.findFocus()); 2887 } 2888 2889 AttachInfo ai = mAttachInfo; 2890 if (ai != null) { 2891 boolean lastKeepOn = ai.mKeepScreenOn; 2892 ai.mKeepScreenOn = false; 2893 child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK)); 2894 if (ai.mKeepScreenOn) { 2895 needGlobalAttributesUpdate(true); 2896 } 2897 ai.mKeepScreenOn = lastKeepOn; 2898 } 2899 2900 if (mOnHierarchyChangeListener != null) { 2901 mOnHierarchyChangeListener.onChildViewAdded(this, child); 2902 } 2903 2904 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) { 2905 mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE; 2906 } 2907 } 2908 2909 private void addInArray(View child, int index) { 2910 View[] children = mChildren; 2911 final int count = mChildrenCount; 2912 final int size = children.length; 2913 if (index == count) { 2914 if (size == count) { 2915 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 2916 System.arraycopy(children, 0, mChildren, 0, size); 2917 children = mChildren; 2918 } 2919 children[mChildrenCount++] = child; 2920 } else if (index < count) { 2921 if (size == count) { 2922 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 2923 System.arraycopy(children, 0, mChildren, 0, index); 2924 System.arraycopy(children, index, mChildren, index + 1, count - index); 2925 children = mChildren; 2926 } else { 2927 System.arraycopy(children, index, children, index + 1, count - index); 2928 } 2929 children[index] = child; 2930 mChildrenCount++; 2931 if (mLastTouchDownIndex >= index) { 2932 mLastTouchDownIndex++; 2933 } 2934 } else { 2935 throw new IndexOutOfBoundsException("index=" + index + " count=" + count); 2936 } 2937 } 2938 2939 // This method also sets the child's mParent to null 2940 private void removeFromArray(int index) { 2941 final View[] children = mChildren; 2942 if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) { 2943 children[index].mParent = null; 2944 } 2945 final int count = mChildrenCount; 2946 if (index == count - 1) { 2947 children[--mChildrenCount] = null; 2948 } else if (index >= 0 && index < count) { 2949 System.arraycopy(children, index + 1, children, index, count - index - 1); 2950 children[--mChildrenCount] = null; 2951 } else { 2952 throw new IndexOutOfBoundsException(); 2953 } 2954 if (mLastTouchDownIndex == index) { 2955 mLastTouchDownTime = 0; 2956 mLastTouchDownIndex = -1; 2957 } else if (mLastTouchDownIndex > index) { 2958 mLastTouchDownIndex--; 2959 } 2960 } 2961 2962 // This method also sets the children's mParent to null 2963 private void removeFromArray(int start, int count) { 2964 final View[] children = mChildren; 2965 final int childrenCount = mChildrenCount; 2966 2967 start = Math.max(0, start); 2968 final int end = Math.min(childrenCount, start + count); 2969 2970 if (start == end) { 2971 return; 2972 } 2973 2974 if (end == childrenCount) { 2975 for (int i = start; i < end; i++) { 2976 children[i].mParent = null; 2977 children[i] = null; 2978 } 2979 } else { 2980 for (int i = start; i < end; i++) { 2981 children[i].mParent = null; 2982 } 2983 2984 // Since we're looping above, we might as well do the copy, but is arraycopy() 2985 // faster than the extra 2 bounds checks we would do in the loop? 2986 System.arraycopy(children, end, children, start, childrenCount - end); 2987 2988 for (int i = childrenCount - (end - start); i < childrenCount; i++) { 2989 children[i] = null; 2990 } 2991 } 2992 2993 mChildrenCount -= (end - start); 2994 } 2995 2996 private void bindLayoutAnimation(View child) { 2997 Animation a = mLayoutAnimationController.getAnimationForView(child); 2998 child.setAnimation(a); 2999 } 3000 3001 /** 3002 * Subclasses should override this method to set layout animation 3003 * parameters on the supplied child. 3004 * 3005 * @param child the child to associate with animation parameters 3006 * @param params the child's layout parameters which hold the animation 3007 * parameters 3008 * @param index the index of the child in the view group 3009 * @param count the number of children in the view group 3010 */ 3011 protected void attachLayoutAnimationParameters(View child, 3012 LayoutParams params, int index, int count) { 3013 LayoutAnimationController.AnimationParameters animationParams = 3014 params.layoutAnimationParameters; 3015 if (animationParams == null) { 3016 animationParams = new LayoutAnimationController.AnimationParameters(); 3017 params.layoutAnimationParameters = animationParams; 3018 } 3019 3020 animationParams.count = count; 3021 animationParams.index = index; 3022 } 3023 3024 /** 3025 * {@inheritDoc} 3026 */ 3027 public void removeView(View view) { 3028 removeViewInternal(view); 3029 requestLayout(); 3030 invalidate(); 3031 } 3032 3033 /** 3034 * Removes a view during layout. This is useful if in your onLayout() method, 3035 * you need to remove more views. 3036 * 3037 * @param view the view to remove from the group 3038 */ 3039 public void removeViewInLayout(View view) { 3040 removeViewInternal(view); 3041 } 3042 3043 /** 3044 * Removes a range of views during layout. This is useful if in your onLayout() method, 3045 * you need to remove more views. 3046 * 3047 * @param start the index of the first view to remove from the group 3048 * @param count the number of views to remove from the group 3049 */ 3050 public void removeViewsInLayout(int start, int count) { 3051 removeViewsInternal(start, count); 3052 } 3053 3054 /** 3055 * Removes the view at the specified position in the group. 3056 * 3057 * @param index the position in the group of the view to remove 3058 */ 3059 public void removeViewAt(int index) { 3060 removeViewInternal(index, getChildAt(index)); 3061 requestLayout(); 3062 invalidate(); 3063 } 3064 3065 /** 3066 * Removes the specified range of views from the group. 3067 * 3068 * @param start the first position in the group of the range of views to remove 3069 * @param count the number of views to remove 3070 */ 3071 public void removeViews(int start, int count) { 3072 removeViewsInternal(start, count); 3073 requestLayout(); 3074 invalidate(); 3075 } 3076 3077 private void removeViewInternal(View view) { 3078 final int index = indexOfChild(view); 3079 if (index >= 0) { 3080 removeViewInternal(index, view); 3081 } 3082 } 3083 3084 private void removeViewInternal(int index, View view) { 3085 3086 if (mTransition != null) { 3087 mTransition.removeChild(this, view); 3088 } 3089 3090 boolean clearChildFocus = false; 3091 if (view == mFocused) { 3092 view.clearFocusForRemoval(); 3093 clearChildFocus = true; 3094 } 3095 3096 if (view.getAnimation() != null || 3097 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3098 addDisappearingView(view); 3099 } else if (view.mAttachInfo != null) { 3100 view.dispatchDetachedFromWindow(); 3101 } 3102 3103 if (mOnHierarchyChangeListener != null) { 3104 mOnHierarchyChangeListener.onChildViewRemoved(this, view); 3105 } 3106 3107 needGlobalAttributesUpdate(false); 3108 3109 removeFromArray(index); 3110 3111 if (clearChildFocus) { 3112 clearChildFocus(view); 3113 } 3114 } 3115 3116 /** 3117 * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3118 * not null, changes in layout which occur because of children being added to or removed from 3119 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3120 * object. By default, the transition object is null (so layout changes are not animated). 3121 * 3122 * @param transition The LayoutTransition object that will animated changes in layout. A value 3123 * of <code>null</code> means no transition will run on layout changes. 3124 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges 3125 */ 3126 public void setLayoutTransition(LayoutTransition transition) { 3127 if (mTransition != null) { 3128 mTransition.removeTransitionListener(mLayoutTransitionListener); 3129 } 3130 mTransition = transition; 3131 if (mTransition != null) { 3132 mTransition.addTransitionListener(mLayoutTransitionListener); 3133 } 3134 } 3135 3136 /** 3137 * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3138 * not null, changes in layout which occur because of children being added to or removed from 3139 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3140 * object. By default, the transition object is null (so layout changes are not animated). 3141 * 3142 * @return LayoutTranstion The LayoutTransition object that will animated changes in layout. 3143 * A value of <code>null</code> means no transition will run on layout changes. 3144 */ 3145 public LayoutTransition getLayoutTransition() { 3146 return mTransition; 3147 } 3148 3149 private void removeViewsInternal(int start, int count) { 3150 final OnHierarchyChangeListener onHierarchyChangeListener = mOnHierarchyChangeListener; 3151 final boolean notifyListener = onHierarchyChangeListener != null; 3152 final View focused = mFocused; 3153 final boolean detach = mAttachInfo != null; 3154 View clearChildFocus = null; 3155 3156 final View[] children = mChildren; 3157 final int end = start + count; 3158 3159 for (int i = start; i < end; i++) { 3160 final View view = children[i]; 3161 3162 if (mTransition != null) { 3163 mTransition.removeChild(this, view); 3164 } 3165 3166 if (view == focused) { 3167 view.clearFocusForRemoval(); 3168 clearChildFocus = view; 3169 } 3170 3171 if (view.getAnimation() != null || 3172 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3173 addDisappearingView(view); 3174 } else if (detach) { 3175 view.dispatchDetachedFromWindow(); 3176 } 3177 3178 needGlobalAttributesUpdate(false); 3179 3180 if (notifyListener) { 3181 onHierarchyChangeListener.onChildViewRemoved(this, view); 3182 } 3183 } 3184 3185 removeFromArray(start, count); 3186 3187 if (clearChildFocus != null) { 3188 clearChildFocus(clearChildFocus); 3189 } 3190 } 3191 3192 /** 3193 * Call this method to remove all child views from the 3194 * ViewGroup. 3195 */ 3196 public void removeAllViews() { 3197 removeAllViewsInLayout(); 3198 requestLayout(); 3199 invalidate(); 3200 } 3201 3202 /** 3203 * Called by a ViewGroup subclass to remove child views from itself, 3204 * when it must first know its size on screen before it can calculate how many 3205 * child views it will render. An example is a Gallery or a ListView, which 3206 * may "have" 50 children, but actually only render the number of children 3207 * that can currently fit inside the object on screen. Do not call 3208 * this method unless you are extending ViewGroup and understand the 3209 * view measuring and layout pipeline. 3210 */ 3211 public void removeAllViewsInLayout() { 3212 final int count = mChildrenCount; 3213 if (count <= 0) { 3214 return; 3215 } 3216 3217 final View[] children = mChildren; 3218 mChildrenCount = 0; 3219 3220 final OnHierarchyChangeListener listener = mOnHierarchyChangeListener; 3221 final boolean notify = listener != null; 3222 final View focused = mFocused; 3223 final boolean detach = mAttachInfo != null; 3224 View clearChildFocus = null; 3225 3226 needGlobalAttributesUpdate(false); 3227 3228 for (int i = count - 1; i >= 0; i--) { 3229 final View view = children[i]; 3230 3231 if (mTransition != null) { 3232 mTransition.removeChild(this, view); 3233 } 3234 3235 if (view == focused) { 3236 view.clearFocusForRemoval(); 3237 clearChildFocus = view; 3238 } 3239 3240 if (view.getAnimation() != null || 3241 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3242 addDisappearingView(view); 3243 } else if (detach) { 3244 view.dispatchDetachedFromWindow(); 3245 } 3246 3247 if (notify) { 3248 listener.onChildViewRemoved(this, view); 3249 } 3250 3251 view.mParent = null; 3252 children[i] = null; 3253 } 3254 3255 if (clearChildFocus != null) { 3256 clearChildFocus(clearChildFocus); 3257 } 3258 } 3259 3260 /** 3261 * Finishes the removal of a detached view. This method will dispatch the detached from 3262 * window event and notify the hierarchy change listener. 3263 * 3264 * @param child the child to be definitely removed from the view hierarchy 3265 * @param animate if true and the view has an animation, the view is placed in the 3266 * disappearing views list, otherwise, it is detached from the window 3267 * 3268 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3269 * @see #detachAllViewsFromParent() 3270 * @see #detachViewFromParent(View) 3271 * @see #detachViewFromParent(int) 3272 */ 3273 protected void removeDetachedView(View child, boolean animate) { 3274 if (mTransition != null) { 3275 mTransition.removeChild(this, child); 3276 } 3277 3278 if (child == mFocused) { 3279 child.clearFocus(); 3280 } 3281 3282 if ((animate && child.getAnimation() != null) || 3283 (mTransitioningViews != null && mTransitioningViews.contains(child))) { 3284 addDisappearingView(child); 3285 } else if (child.mAttachInfo != null) { 3286 child.dispatchDetachedFromWindow(); 3287 } 3288 3289 if (mOnHierarchyChangeListener != null) { 3290 mOnHierarchyChangeListener.onChildViewRemoved(this, child); 3291 } 3292 } 3293 3294 /** 3295 * Attaches a view to this view group. Attaching a view assigns this group as the parent, 3296 * sets the layout parameters and puts the view in the list of children so it can be retrieved 3297 * by calling {@link #getChildAt(int)}. 3298 * 3299 * This method should be called only for view which were detached from their parent. 3300 * 3301 * @param child the child to attach 3302 * @param index the index at which the child should be attached 3303 * @param params the layout parameters of the child 3304 * 3305 * @see #removeDetachedView(View, boolean) 3306 * @see #detachAllViewsFromParent() 3307 * @see #detachViewFromParent(View) 3308 * @see #detachViewFromParent(int) 3309 */ 3310 protected void attachViewToParent(View child, int index, LayoutParams params) { 3311 child.mLayoutParams = params; 3312 3313 if (index < 0) { 3314 index = mChildrenCount; 3315 } 3316 3317 addInArray(child, index); 3318 3319 child.mParent = this; 3320 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) | DRAWN; 3321 3322 if (child.hasFocus()) { 3323 requestChildFocus(child, child.findFocus()); 3324 } 3325 } 3326 3327 /** 3328 * Detaches a view from its parent. Detaching a view should be temporary and followed 3329 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3330 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3331 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3332 * 3333 * @param child the child to detach 3334 * 3335 * @see #detachViewFromParent(int) 3336 * @see #detachViewsFromParent(int, int) 3337 * @see #detachAllViewsFromParent() 3338 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3339 * @see #removeDetachedView(View, boolean) 3340 */ 3341 protected void detachViewFromParent(View child) { 3342 removeFromArray(indexOfChild(child)); 3343 } 3344 3345 /** 3346 * Detaches a view from its parent. Detaching a view should be temporary and followed 3347 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3348 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3349 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3350 * 3351 * @param index the index of the child to detach 3352 * 3353 * @see #detachViewFromParent(View) 3354 * @see #detachAllViewsFromParent() 3355 * @see #detachViewsFromParent(int, int) 3356 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3357 * @see #removeDetachedView(View, boolean) 3358 */ 3359 protected void detachViewFromParent(int index) { 3360 removeFromArray(index); 3361 } 3362 3363 /** 3364 * Detaches a range of view from their parent. Detaching a view should be temporary and followed 3365 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3366 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its 3367 * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3368 * 3369 * @param start the first index of the childrend range to detach 3370 * @param count the number of children to detach 3371 * 3372 * @see #detachViewFromParent(View) 3373 * @see #detachViewFromParent(int) 3374 * @see #detachAllViewsFromParent() 3375 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3376 * @see #removeDetachedView(View, boolean) 3377 */ 3378 protected void detachViewsFromParent(int start, int count) { 3379 removeFromArray(start, count); 3380 } 3381 3382 /** 3383 * Detaches all views from the parent. Detaching a view should be temporary and followed 3384 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3385 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3386 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3387 * 3388 * @see #detachViewFromParent(View) 3389 * @see #detachViewFromParent(int) 3390 * @see #detachViewsFromParent(int, int) 3391 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3392 * @see #removeDetachedView(View, boolean) 3393 */ 3394 protected void detachAllViewsFromParent() { 3395 final int count = mChildrenCount; 3396 if (count <= 0) { 3397 return; 3398 } 3399 3400 final View[] children = mChildren; 3401 mChildrenCount = 0; 3402 3403 for (int i = count - 1; i >= 0; i--) { 3404 children[i].mParent = null; 3405 children[i] = null; 3406 } 3407 } 3408 3409 /** 3410 * Don't call or override this method. It is used for the implementation of 3411 * the view hierarchy. 3412 */ 3413 public final void invalidateChild(View child, final Rect dirty) { 3414 if (ViewDebug.TRACE_HIERARCHY) { 3415 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD); 3416 } 3417 3418 ViewParent parent = this; 3419 3420 final AttachInfo attachInfo = mAttachInfo; 3421 if (attachInfo != null) { 3422 // If the child is drawing an animation, we want to copy this flag onto 3423 // ourselves and the parent to make sure the invalidate request goes 3424 // through 3425 final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION; 3426 3427 if (dirty == null) { 3428 do { 3429 View view = null; 3430 if (parent instanceof View) { 3431 view = (View) parent; 3432 if ((view.mPrivateFlags & DIRTY_MASK) != 0) { 3433 // already marked dirty - we're done 3434 break; 3435 } 3436 } 3437 3438 if (drawAnimation) { 3439 if (view != null) { 3440 view.mPrivateFlags |= DRAW_ANIMATION; 3441 } else if (parent instanceof ViewRoot) { 3442 ((ViewRoot) parent).mIsAnimating = true; 3443 } 3444 } 3445 3446 if (parent instanceof ViewRoot) { 3447 ((ViewRoot) parent).invalidate(); 3448 parent = null; 3449 } else if (view != null) { 3450 if ((mPrivateFlags & DRAWN) == DRAWN) { 3451 view.mPrivateFlags &= ~DRAWING_CACHE_VALID; 3452 view.mPrivateFlags |= DIRTY; 3453 parent = view.mParent; 3454 } else { 3455 parent = null; 3456 } 3457 } 3458 } while (parent != null); 3459 } else { 3460 // Check whether the child that requests the invalidate is fully opaque 3461 final boolean isOpaque = child.isOpaque() && !drawAnimation && 3462 child.getAnimation() == null; 3463 // Mark the child as dirty, using the appropriate flag 3464 // Make sure we do not set both flags at the same time 3465 int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY; 3466 3467 final int[] location = attachInfo.mInvalidateChildLocation; 3468 location[CHILD_LEFT_INDEX] = child.mLeft; 3469 location[CHILD_TOP_INDEX] = child.mTop; 3470 Matrix childMatrix = child.getMatrix(); 3471 if (!childMatrix.isIdentity()) { 3472 RectF boundingRect = attachInfo.mTmpTransformRect; 3473 boundingRect.set(dirty); 3474 childMatrix.mapRect(boundingRect); 3475 dirty.set((int) boundingRect.left, (int) boundingRect.top, 3476 (int) (boundingRect.right + 0.5f), 3477 (int) (boundingRect.bottom + 0.5f)); 3478 } 3479 3480 do { 3481 View view = null; 3482 if (parent instanceof View) { 3483 view = (View) parent; 3484 } 3485 3486 if (drawAnimation) { 3487 if (view != null) { 3488 view.mPrivateFlags |= DRAW_ANIMATION; 3489 } else if (parent instanceof ViewRoot) { 3490 ((ViewRoot) parent).mIsAnimating = true; 3491 } 3492 } 3493 3494 // If the parent is dirty opaque or not dirty, mark it dirty with the opaque 3495 // flag coming from the child that initiated the invalidate 3496 if (view != null) { 3497 if ((view.mViewFlags & FADING_EDGE_MASK) != 0 && 3498 view.getSolidColor() == 0 && !view.isOpaque()) { 3499 opaqueFlag = DIRTY; 3500 } 3501 if ((view.mPrivateFlags & DIRTY_MASK) != DIRTY) { 3502 view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag; 3503 } 3504 } 3505 3506 parent = parent.invalidateChildInParent(location, dirty); 3507 if (view != null) { 3508 // Account for transform on current parent 3509 Matrix m = view.getMatrix(); 3510 if (!m.isIdentity()) { 3511 RectF boundingRect = attachInfo.mTmpTransformRect; 3512 boundingRect.set(dirty); 3513 m.mapRect(boundingRect); 3514 dirty.set((int) boundingRect.left, (int) boundingRect.top, 3515 (int) (boundingRect.right + 0.5f), 3516 (int) (boundingRect.bottom + 0.5f)); 3517 } 3518 } 3519 } while (parent != null); 3520 } 3521 } 3522 } 3523 3524 /** 3525 * Don't call or override this method. It is used for the implementation of 3526 * the view hierarchy. 3527 * 3528 * This implementation returns null if this ViewGroup does not have a parent, 3529 * if this ViewGroup is already fully invalidated or if the dirty rectangle 3530 * does not intersect with this ViewGroup's bounds. 3531 */ 3532 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) { 3533 if (ViewDebug.TRACE_HIERARCHY) { 3534 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD_IN_PARENT); 3535 } 3536 3537 if ((mPrivateFlags & DRAWN) == DRAWN) { 3538 if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) != 3539 FLAG_OPTIMIZE_INVALIDATE) { 3540 dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX, 3541 location[CHILD_TOP_INDEX] - mScrollY); 3542 3543 final int left = mLeft; 3544 final int top = mTop; 3545 3546 if (dirty.intersect(0, 0, mRight - left, mBottom - top) || 3547 (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) { 3548 mPrivateFlags &= ~DRAWING_CACHE_VALID; 3549 3550 location[CHILD_LEFT_INDEX] = left; 3551 location[CHILD_TOP_INDEX] = top; 3552 3553 return mParent; 3554 } 3555 } else { 3556 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID; 3557 3558 location[CHILD_LEFT_INDEX] = mLeft; 3559 location[CHILD_TOP_INDEX] = mTop; 3560 3561 dirty.set(0, 0, mRight - location[CHILD_LEFT_INDEX], 3562 mBottom - location[CHILD_TOP_INDEX]); 3563 3564 return mParent; 3565 } 3566 } 3567 3568 return null; 3569 } 3570 3571 /** 3572 * Offset a rectangle that is in a descendant's coordinate 3573 * space into our coordinate space. 3574 * @param descendant A descendant of this view 3575 * @param rect A rectangle defined in descendant's coordinate space. 3576 */ 3577 public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) { 3578 offsetRectBetweenParentAndChild(descendant, rect, true, false); 3579 } 3580 3581 /** 3582 * Offset a rectangle that is in our coordinate space into an ancestor's 3583 * coordinate space. 3584 * @param descendant A descendant of this view 3585 * @param rect A rectangle defined in descendant's coordinate space. 3586 */ 3587 public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) { 3588 offsetRectBetweenParentAndChild(descendant, rect, false, false); 3589 } 3590 3591 /** 3592 * Helper method that offsets a rect either from parent to descendant or 3593 * descendant to parent. 3594 */ 3595 void offsetRectBetweenParentAndChild(View descendant, Rect rect, 3596 boolean offsetFromChildToParent, boolean clipToBounds) { 3597 3598 // already in the same coord system :) 3599 if (descendant == this) { 3600 return; 3601 } 3602 3603 ViewParent theParent = descendant.mParent; 3604 3605 // search and offset up to the parent 3606 while ((theParent != null) 3607 && (theParent instanceof View) 3608 && (theParent != this)) { 3609 3610 if (offsetFromChildToParent) { 3611 rect.offset(descendant.mLeft - descendant.mScrollX, 3612 descendant.mTop - descendant.mScrollY); 3613 if (clipToBounds) { 3614 View p = (View) theParent; 3615 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 3616 } 3617 } else { 3618 if (clipToBounds) { 3619 View p = (View) theParent; 3620 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 3621 } 3622 rect.offset(descendant.mScrollX - descendant.mLeft, 3623 descendant.mScrollY - descendant.mTop); 3624 } 3625 3626 descendant = (View) theParent; 3627 theParent = descendant.mParent; 3628 } 3629 3630 // now that we are up to this view, need to offset one more time 3631 // to get into our coordinate space 3632 if (theParent == this) { 3633 if (offsetFromChildToParent) { 3634 rect.offset(descendant.mLeft - descendant.mScrollX, 3635 descendant.mTop - descendant.mScrollY); 3636 } else { 3637 rect.offset(descendant.mScrollX - descendant.mLeft, 3638 descendant.mScrollY - descendant.mTop); 3639 } 3640 } else { 3641 throw new IllegalArgumentException("parameter must be a descendant of this view"); 3642 } 3643 } 3644 3645 /** 3646 * Offset the vertical location of all children of this view by the specified number of pixels. 3647 * 3648 * @param offset the number of pixels to offset 3649 * 3650 * @hide 3651 */ 3652 public void offsetChildrenTopAndBottom(int offset) { 3653 final int count = mChildrenCount; 3654 final View[] children = mChildren; 3655 3656 for (int i = 0; i < count; i++) { 3657 final View v = children[i]; 3658 v.mTop += offset; 3659 v.mBottom += offset; 3660 } 3661 } 3662 3663 /** 3664 * {@inheritDoc} 3665 */ 3666 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 3667 int dx = child.mLeft - mScrollX; 3668 int dy = child.mTop - mScrollY; 3669 if (offset != null) { 3670 offset.x += dx; 3671 offset.y += dy; 3672 } 3673 r.offset(dx, dy); 3674 return r.intersect(0, 0, mRight - mLeft, mBottom - mTop) && 3675 (mParent == null || mParent.getChildVisibleRect(this, r, offset)); 3676 } 3677 3678 /** 3679 * {@inheritDoc} 3680 */ 3681 @Override 3682 public final void layout(int l, int t, int r, int b) { 3683 if (mTransition == null || !mTransition.isChangingLayout()) { 3684 super.layout(l, t, r, b); 3685 } else { 3686 // record the fact that we noop'd it; request layout when transition finishes 3687 mLayoutSuppressed = true; 3688 } 3689 } 3690 3691 /** 3692 * {@inheritDoc} 3693 */ 3694 @Override 3695 protected abstract void onLayout(boolean changed, 3696 int l, int t, int r, int b); 3697 3698 /** 3699 * Indicates whether the view group has the ability to animate its children 3700 * after the first layout. 3701 * 3702 * @return true if the children can be animated, false otherwise 3703 */ 3704 protected boolean canAnimate() { 3705 return mLayoutAnimationController != null; 3706 } 3707 3708 /** 3709 * Runs the layout animation. Calling this method triggers a relayout of 3710 * this view group. 3711 */ 3712 public void startLayoutAnimation() { 3713 if (mLayoutAnimationController != null) { 3714 mGroupFlags |= FLAG_RUN_ANIMATION; 3715 requestLayout(); 3716 } 3717 } 3718 3719 /** 3720 * Schedules the layout animation to be played after the next layout pass 3721 * of this view group. This can be used to restart the layout animation 3722 * when the content of the view group changes or when the activity is 3723 * paused and resumed. 3724 */ 3725 public void scheduleLayoutAnimation() { 3726 mGroupFlags |= FLAG_RUN_ANIMATION; 3727 } 3728 3729 /** 3730 * Sets the layout animation controller used to animate the group's 3731 * children after the first layout. 3732 * 3733 * @param controller the animation controller 3734 */ 3735 public void setLayoutAnimation(LayoutAnimationController controller) { 3736 mLayoutAnimationController = controller; 3737 if (mLayoutAnimationController != null) { 3738 mGroupFlags |= FLAG_RUN_ANIMATION; 3739 } 3740 } 3741 3742 /** 3743 * Returns the layout animation controller used to animate the group's 3744 * children. 3745 * 3746 * @return the current animation controller 3747 */ 3748 public LayoutAnimationController getLayoutAnimation() { 3749 return mLayoutAnimationController; 3750 } 3751 3752 /** 3753 * Indicates whether the children's drawing cache is used during a layout 3754 * animation. By default, the drawing cache is enabled but this will prevent 3755 * nested layout animations from working. To nest animations, you must disable 3756 * the cache. 3757 * 3758 * @return true if the animation cache is enabled, false otherwise 3759 * 3760 * @see #setAnimationCacheEnabled(boolean) 3761 * @see View#setDrawingCacheEnabled(boolean) 3762 */ 3763 @ViewDebug.ExportedProperty 3764 public boolean isAnimationCacheEnabled() { 3765 return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE; 3766 } 3767 3768 /** 3769 * Enables or disables the children's drawing cache during a layout animation. 3770 * By default, the drawing cache is enabled but this will prevent nested 3771 * layout animations from working. To nest animations, you must disable the 3772 * cache. 3773 * 3774 * @param enabled true to enable the animation cache, false otherwise 3775 * 3776 * @see #isAnimationCacheEnabled() 3777 * @see View#setDrawingCacheEnabled(boolean) 3778 */ 3779 public void setAnimationCacheEnabled(boolean enabled) { 3780 setBooleanFlag(FLAG_ANIMATION_CACHE, enabled); 3781 } 3782 3783 /** 3784 * Indicates whether this ViewGroup will always try to draw its children using their 3785 * drawing cache. By default this property is enabled. 3786 * 3787 * @return true if the animation cache is enabled, false otherwise 3788 * 3789 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 3790 * @see #setChildrenDrawnWithCacheEnabled(boolean) 3791 * @see View#setDrawingCacheEnabled(boolean) 3792 */ 3793 @ViewDebug.ExportedProperty(category = "drawing") 3794 public boolean isAlwaysDrawnWithCacheEnabled() { 3795 return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE; 3796 } 3797 3798 /** 3799 * Indicates whether this ViewGroup will always try to draw its children using their 3800 * drawing cache. This property can be set to true when the cache rendering is 3801 * slightly different from the children's normal rendering. Renderings can be different, 3802 * for instance, when the cache's quality is set to low. 3803 * 3804 * When this property is disabled, the ViewGroup will use the drawing cache of its 3805 * children only when asked to. It's usually the task of subclasses to tell ViewGroup 3806 * when to start using the drawing cache and when to stop using it. 3807 * 3808 * @param always true to always draw with the drawing cache, false otherwise 3809 * 3810 * @see #isAlwaysDrawnWithCacheEnabled() 3811 * @see #setChildrenDrawnWithCacheEnabled(boolean) 3812 * @see View#setDrawingCacheEnabled(boolean) 3813 * @see View#setDrawingCacheQuality(int) 3814 */ 3815 public void setAlwaysDrawnWithCacheEnabled(boolean always) { 3816 setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always); 3817 } 3818 3819 /** 3820 * Indicates whether the ViewGroup is currently drawing its children using 3821 * their drawing cache. 3822 * 3823 * @return true if children should be drawn with their cache, false otherwise 3824 * 3825 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 3826 * @see #setChildrenDrawnWithCacheEnabled(boolean) 3827 */ 3828 @ViewDebug.ExportedProperty(category = "drawing") 3829 protected boolean isChildrenDrawnWithCacheEnabled() { 3830 return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE; 3831 } 3832 3833 /** 3834 * Tells the ViewGroup to draw its children using their drawing cache. This property 3835 * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache 3836 * will be used only if it has been enabled. 3837 * 3838 * Subclasses should call this method to start and stop using the drawing cache when 3839 * they perform performance sensitive operations, like scrolling or animating. 3840 * 3841 * @param enabled true if children should be drawn with their cache, false otherwise 3842 * 3843 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 3844 * @see #isChildrenDrawnWithCacheEnabled() 3845 */ 3846 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) { 3847 setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled); 3848 } 3849 3850 /** 3851 * Indicates whether the ViewGroup is drawing its children in the order defined by 3852 * {@link #getChildDrawingOrder(int, int)}. 3853 * 3854 * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)}, 3855 * false otherwise 3856 * 3857 * @see #setChildrenDrawingOrderEnabled(boolean) 3858 * @see #getChildDrawingOrder(int, int) 3859 */ 3860 @ViewDebug.ExportedProperty(category = "drawing") 3861 protected boolean isChildrenDrawingOrderEnabled() { 3862 return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER; 3863 } 3864 3865 /** 3866 * Tells the ViewGroup whether to draw its children in the order defined by the method 3867 * {@link #getChildDrawingOrder(int, int)}. 3868 * 3869 * @param enabled true if the order of the children when drawing is determined by 3870 * {@link #getChildDrawingOrder(int, int)}, false otherwise 3871 * 3872 * @see #isChildrenDrawingOrderEnabled() 3873 * @see #getChildDrawingOrder(int, int) 3874 */ 3875 protected void setChildrenDrawingOrderEnabled(boolean enabled) { 3876 setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled); 3877 } 3878 3879 private void setBooleanFlag(int flag, boolean value) { 3880 if (value) { 3881 mGroupFlags |= flag; 3882 } else { 3883 mGroupFlags &= ~flag; 3884 } 3885 } 3886 3887 /** 3888 * Returns an integer indicating what types of drawing caches are kept in memory. 3889 * 3890 * @see #setPersistentDrawingCache(int) 3891 * @see #setAnimationCacheEnabled(boolean) 3892 * 3893 * @return one or a combination of {@link #PERSISTENT_NO_CACHE}, 3894 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 3895 * and {@link #PERSISTENT_ALL_CACHES} 3896 */ 3897 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 3898 @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE, to = "NONE"), 3899 @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"), 3900 @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"), 3901 @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES, to = "ALL") 3902 }) 3903 public int getPersistentDrawingCache() { 3904 return mPersistentDrawingCache; 3905 } 3906 3907 /** 3908 * Indicates what types of drawing caches should be kept in memory after 3909 * they have been created. 3910 * 3911 * @see #getPersistentDrawingCache() 3912 * @see #setAnimationCacheEnabled(boolean) 3913 * 3914 * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE}, 3915 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 3916 * and {@link #PERSISTENT_ALL_CACHES} 3917 */ 3918 public void setPersistentDrawingCache(int drawingCacheToKeep) { 3919 mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES; 3920 } 3921 3922 /** 3923 * Returns a new set of layout parameters based on the supplied attributes set. 3924 * 3925 * @param attrs the attributes to build the layout parameters from 3926 * 3927 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 3928 * of its descendants 3929 */ 3930 public LayoutParams generateLayoutParams(AttributeSet attrs) { 3931 return new LayoutParams(getContext(), attrs); 3932 } 3933 3934 /** 3935 * Returns a safe set of layout parameters based on the supplied layout params. 3936 * When a ViewGroup is passed a View whose layout params do not pass the test of 3937 * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method 3938 * is invoked. This method should return a new set of layout params suitable for 3939 * this ViewGroup, possibly by copying the appropriate attributes from the 3940 * specified set of layout params. 3941 * 3942 * @param p The layout parameters to convert into a suitable set of layout parameters 3943 * for this ViewGroup. 3944 * 3945 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 3946 * of its descendants 3947 */ 3948 protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 3949 return p; 3950 } 3951 3952 /** 3953 * Returns a set of default layout parameters. These parameters are requested 3954 * when the View passed to {@link #addView(View)} has no layout parameters 3955 * already set. If null is returned, an exception is thrown from addView. 3956 * 3957 * @return a set of default layout parameters or null 3958 */ 3959 protected LayoutParams generateDefaultLayoutParams() { 3960 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 3961 } 3962 3963 /** 3964 * @hide 3965 */ 3966 @Override 3967 protected boolean dispatchConsistencyCheck(int consistency) { 3968 boolean result = super.dispatchConsistencyCheck(consistency); 3969 3970 final int count = mChildrenCount; 3971 final View[] children = mChildren; 3972 for (int i = 0; i < count; i++) { 3973 if (!children[i].dispatchConsistencyCheck(consistency)) result = false; 3974 } 3975 3976 return result; 3977 } 3978 3979 /** 3980 * @hide 3981 */ 3982 @Override 3983 protected boolean onConsistencyCheck(int consistency) { 3984 boolean result = super.onConsistencyCheck(consistency); 3985 3986 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 3987 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 3988 3989 if (checkLayout) { 3990 final int count = mChildrenCount; 3991 final View[] children = mChildren; 3992 for (int i = 0; i < count; i++) { 3993 if (children[i].getParent() != this) { 3994 result = false; 3995 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 3996 "View " + children[i] + " has no parent/a parent that is not " + this); 3997 } 3998 } 3999 } 4000 4001 if (checkDrawing) { 4002 // If this group is dirty, check that the parent is dirty as well 4003 if ((mPrivateFlags & DIRTY_MASK) != 0) { 4004 final ViewParent parent = getParent(); 4005 if (parent != null && !(parent instanceof ViewRoot)) { 4006 if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) { 4007 result = false; 4008 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 4009 "ViewGroup " + this + " is dirty but its parent is not: " + this); 4010 } 4011 } 4012 } 4013 } 4014 4015 return result; 4016 } 4017 4018 /** 4019 * {@inheritDoc} 4020 */ 4021 @Override 4022 protected void debug(int depth) { 4023 super.debug(depth); 4024 String output; 4025 4026 if (mFocused != null) { 4027 output = debugIndent(depth); 4028 output += "mFocused"; 4029 Log.d(VIEW_LOG_TAG, output); 4030 } 4031 if (mChildrenCount != 0) { 4032 output = debugIndent(depth); 4033 output += "{"; 4034 Log.d(VIEW_LOG_TAG, output); 4035 } 4036 int count = mChildrenCount; 4037 for (int i = 0; i < count; i++) { 4038 View child = mChildren[i]; 4039 child.debug(depth + 1); 4040 } 4041 4042 if (mChildrenCount != 0) { 4043 output = debugIndent(depth); 4044 output += "}"; 4045 Log.d(VIEW_LOG_TAG, output); 4046 } 4047 } 4048 4049 /** 4050 * Returns the position in the group of the specified child view. 4051 * 4052 * @param child the view for which to get the position 4053 * @return a positive integer representing the position of the view in the 4054 * group, or -1 if the view does not exist in the group 4055 */ 4056 public int indexOfChild(View child) { 4057 final int count = mChildrenCount; 4058 final View[] children = mChildren; 4059 for (int i = 0; i < count; i++) { 4060 if (children[i] == child) { 4061 return i; 4062 } 4063 } 4064 return -1; 4065 } 4066 4067 /** 4068 * Returns the number of children in the group. 4069 * 4070 * @return a positive integer representing the number of children in 4071 * the group 4072 */ 4073 public int getChildCount() { 4074 return mChildrenCount; 4075 } 4076 4077 /** 4078 * Returns the view at the specified position in the group. 4079 * 4080 * @param index the position at which to get the view from 4081 * @return the view at the specified position or null if the position 4082 * does not exist within the group 4083 */ 4084 public View getChildAt(int index) { 4085 try { 4086 return mChildren[index]; 4087 } catch (IndexOutOfBoundsException ex) { 4088 return null; 4089 } 4090 } 4091 4092 /** 4093 * Ask all of the children of this view to measure themselves, taking into 4094 * account both the MeasureSpec requirements for this view and its padding. 4095 * We skip children that are in the GONE state The heavy lifting is done in 4096 * getChildMeasureSpec. 4097 * 4098 * @param widthMeasureSpec The width requirements for this view 4099 * @param heightMeasureSpec The height requirements for this view 4100 */ 4101 protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) { 4102 final int size = mChildrenCount; 4103 final View[] children = mChildren; 4104 for (int i = 0; i < size; ++i) { 4105 final View child = children[i]; 4106 if ((child.mViewFlags & VISIBILITY_MASK) != GONE) { 4107 measureChild(child, widthMeasureSpec, heightMeasureSpec); 4108 } 4109 } 4110 } 4111 4112 /** 4113 * Ask one of the children of this view to measure itself, taking into 4114 * account both the MeasureSpec requirements for this view and its padding. 4115 * The heavy lifting is done in getChildMeasureSpec. 4116 * 4117 * @param child The child to measure 4118 * @param parentWidthMeasureSpec The width requirements for this view 4119 * @param parentHeightMeasureSpec The height requirements for this view 4120 */ 4121 protected void measureChild(View child, int parentWidthMeasureSpec, 4122 int parentHeightMeasureSpec) { 4123 final LayoutParams lp = child.getLayoutParams(); 4124 4125 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4126 mPaddingLeft + mPaddingRight, lp.width); 4127 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4128 mPaddingTop + mPaddingBottom, lp.height); 4129 4130 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4131 } 4132 4133 /** 4134 * Ask one of the children of this view to measure itself, taking into 4135 * account both the MeasureSpec requirements for this view and its padding 4136 * and margins. The child must have MarginLayoutParams The heavy lifting is 4137 * done in getChildMeasureSpec. 4138 * 4139 * @param child The child to measure 4140 * @param parentWidthMeasureSpec The width requirements for this view 4141 * @param widthUsed Extra space that has been used up by the parent 4142 * horizontally (possibly by other children of the parent) 4143 * @param parentHeightMeasureSpec The height requirements for this view 4144 * @param heightUsed Extra space that has been used up by the parent 4145 * vertically (possibly by other children of the parent) 4146 */ 4147 protected void measureChildWithMargins(View child, 4148 int parentWidthMeasureSpec, int widthUsed, 4149 int parentHeightMeasureSpec, int heightUsed) { 4150 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 4151 4152 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4153 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 4154 + widthUsed, lp.width); 4155 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4156 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin 4157 + heightUsed, lp.height); 4158 4159 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4160 } 4161 4162 /** 4163 * Does the hard part of measureChildren: figuring out the MeasureSpec to 4164 * pass to a particular child. This method figures out the right MeasureSpec 4165 * for one dimension (height or width) of one child view. 4166 * 4167 * The goal is to combine information from our MeasureSpec with the 4168 * LayoutParams of the child to get the best possible results. For example, 4169 * if the this view knows its size (because its MeasureSpec has a mode of 4170 * EXACTLY), and the child has indicated in its LayoutParams that it wants 4171 * to be the same size as the parent, the parent should ask the child to 4172 * layout given an exact size. 4173 * 4174 * @param spec The requirements for this view 4175 * @param padding The padding of this view for the current dimension and 4176 * margins, if applicable 4177 * @param childDimension How big the child wants to be in the current 4178 * dimension 4179 * @return a MeasureSpec integer for the child 4180 */ 4181 public static int getChildMeasureSpec(int spec, int padding, int childDimension) { 4182 int specMode = MeasureSpec.getMode(spec); 4183 int specSize = MeasureSpec.getSize(spec); 4184 4185 int size = Math.max(0, specSize - padding); 4186 4187 int resultSize = 0; 4188 int resultMode = 0; 4189 4190 switch (specMode) { 4191 // Parent has imposed an exact size on us 4192 case MeasureSpec.EXACTLY: 4193 if (childDimension >= 0) { 4194 resultSize = childDimension; 4195 resultMode = MeasureSpec.EXACTLY; 4196 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4197 // Child wants to be our size. So be it. 4198 resultSize = size; 4199 resultMode = MeasureSpec.EXACTLY; 4200 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4201 // Child wants to determine its own size. It can't be 4202 // bigger than us. 4203 resultSize = size; 4204 resultMode = MeasureSpec.AT_MOST; 4205 } 4206 break; 4207 4208 // Parent has imposed a maximum size on us 4209 case MeasureSpec.AT_MOST: 4210 if (childDimension >= 0) { 4211 // Child wants a specific size... so be it 4212 resultSize = childDimension; 4213 resultMode = MeasureSpec.EXACTLY; 4214 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4215 // Child wants to be our size, but our size is not fixed. 4216 // Constrain child to not be bigger than us. 4217 resultSize = size; 4218 resultMode = MeasureSpec.AT_MOST; 4219 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4220 // Child wants to determine its own size. It can't be 4221 // bigger than us. 4222 resultSize = size; 4223 resultMode = MeasureSpec.AT_MOST; 4224 } 4225 break; 4226 4227 // Parent asked to see how big we want to be 4228 case MeasureSpec.UNSPECIFIED: 4229 if (childDimension >= 0) { 4230 // Child wants a specific size... let him have it 4231 resultSize = childDimension; 4232 resultMode = MeasureSpec.EXACTLY; 4233 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4234 // Child wants to be our size... find out how big it should 4235 // be 4236 resultSize = 0; 4237 resultMode = MeasureSpec.UNSPECIFIED; 4238 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4239 // Child wants to determine its own size.... find out how 4240 // big it should be 4241 resultSize = 0; 4242 resultMode = MeasureSpec.UNSPECIFIED; 4243 } 4244 break; 4245 } 4246 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 4247 } 4248 4249 4250 /** 4251 * Removes any pending animations for views that have been removed. Call 4252 * this if you don't want animations for exiting views to stack up. 4253 */ 4254 public void clearDisappearingChildren() { 4255 if (mDisappearingChildren != null) { 4256 mDisappearingChildren.clear(); 4257 } 4258 } 4259 4260 /** 4261 * Add a view which is removed from mChildren but still needs animation 4262 * 4263 * @param v View to add 4264 */ 4265 private void addDisappearingView(View v) { 4266 ArrayList<View> disappearingChildren = mDisappearingChildren; 4267 4268 if (disappearingChildren == null) { 4269 disappearingChildren = mDisappearingChildren = new ArrayList<View>(); 4270 } 4271 4272 disappearingChildren.add(v); 4273 } 4274 4275 /** 4276 * Cleanup a view when its animation is done. This may mean removing it from 4277 * the list of disappearing views. 4278 * 4279 * @param view The view whose animation has finished 4280 * @param animation The animation, cannot be null 4281 */ 4282 private void finishAnimatingView(final View view, Animation animation) { 4283 final ArrayList<View> disappearingChildren = mDisappearingChildren; 4284 if (disappearingChildren != null) { 4285 if (disappearingChildren.contains(view)) { 4286 disappearingChildren.remove(view); 4287 4288 if (view.mAttachInfo != null) { 4289 view.dispatchDetachedFromWindow(); 4290 } 4291 4292 view.clearAnimation(); 4293 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4294 } 4295 } 4296 4297 if (animation != null && !animation.getFillAfter()) { 4298 view.clearAnimation(); 4299 } 4300 4301 if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) { 4302 view.onAnimationEnd(); 4303 // Should be performed by onAnimationEnd() but this avoid an infinite loop, 4304 // so we'd rather be safe than sorry 4305 view.mPrivateFlags &= ~ANIMATION_STARTED; 4306 // Draw one more frame after the animation is done 4307 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4308 } 4309 } 4310 4311 /** 4312 * This method tells the ViewGroup that the given View object, which should have this 4313 * ViewGroup as its parent, 4314 * should be kept around (re-displayed when the ViewGroup draws its children) even if it 4315 * is removed from its parent. This allows animations, such as those used by 4316 * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate 4317 * the removal of views. A call to this method should always be accompanied by a later call 4318 * to {@link #endViewTransition(View)}, such as after an animation on the View has finished, 4319 * so that the View finally gets removed. 4320 * 4321 * @param view The View object to be kept visible even if it gets removed from its parent. 4322 */ 4323 public void startViewTransition(View view) { 4324 if (view.mParent == this) { 4325 if (mTransitioningViews == null) { 4326 mTransitioningViews = new ArrayList<View>(); 4327 } 4328 mTransitioningViews.add(view); 4329 } 4330 } 4331 4332 /** 4333 * This method should always be called following an earlier call to 4334 * {@link #startViewTransition(View)}. The given View is finally removed from its parent 4335 * and will no longer be displayed. Note that this method does not perform the functionality 4336 * of removing a view from its parent; it just discontinues the display of a View that 4337 * has previously been removed. 4338 * 4339 * @return view The View object that has been removed but is being kept around in the visible 4340 * hierarchy by an earlier call to {@link #startViewTransition(View)}. 4341 */ 4342 public void endViewTransition(View view) { 4343 if (mTransitioningViews != null) { 4344 mTransitioningViews.remove(view); 4345 final ArrayList<View> disappearingChildren = mDisappearingChildren; 4346 if (disappearingChildren != null && disappearingChildren.contains(view)) { 4347 disappearingChildren.remove(view); 4348 if (mVisibilityChangingChildren != null && 4349 mVisibilityChangingChildren.contains(view)) { 4350 mVisibilityChangingChildren.remove(view); 4351 } else { 4352 if (view.mAttachInfo != null) { 4353 view.dispatchDetachedFromWindow(); 4354 } 4355 if (view.mParent != null) { 4356 view.mParent = null; 4357 } 4358 } 4359 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4360 } 4361 } 4362 } 4363 4364 private LayoutTransition.TransitionListener mLayoutTransitionListener = 4365 new LayoutTransition.TransitionListener() { 4366 @Override 4367 public void startTransition(LayoutTransition transition, ViewGroup container, 4368 View view, int transitionType) { 4369 // We only care about disappearing items, since we need special logic to keep 4370 // those items visible after they've been 'removed' 4371 if (transitionType == LayoutTransition.DISAPPEARING) { 4372 startViewTransition(view); 4373 } 4374 } 4375 4376 @Override 4377 public void endTransition(LayoutTransition transition, ViewGroup container, 4378 View view, int transitionType) { 4379 if (mLayoutSuppressed && !transition.isChangingLayout()) { 4380 requestLayout(); 4381 mLayoutSuppressed = false; 4382 } 4383 if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) { 4384 endViewTransition(view); 4385 } 4386 } 4387 }; 4388 4389 /** 4390 * {@inheritDoc} 4391 */ 4392 @Override 4393 public boolean gatherTransparentRegion(Region region) { 4394 // If no transparent regions requested, we are always opaque. 4395 final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0; 4396 if (meOpaque && region == null) { 4397 // The caller doesn't care about the region, so stop now. 4398 return true; 4399 } 4400 super.gatherTransparentRegion(region); 4401 final View[] children = mChildren; 4402 final int count = mChildrenCount; 4403 boolean noneOfTheChildrenAreTransparent = true; 4404 for (int i = 0; i < count; i++) { 4405 final View child = children[i]; 4406 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 4407 if (!child.gatherTransparentRegion(region)) { 4408 noneOfTheChildrenAreTransparent = false; 4409 } 4410 } 4411 } 4412 return meOpaque || noneOfTheChildrenAreTransparent; 4413 } 4414 4415 /** 4416 * {@inheritDoc} 4417 */ 4418 public void requestTransparentRegion(View child) { 4419 if (child != null) { 4420 child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS; 4421 if (mParent != null) { 4422 mParent.requestTransparentRegion(this); 4423 } 4424 } 4425 } 4426 4427 4428 @Override 4429 protected boolean fitSystemWindows(Rect insets) { 4430 boolean done = super.fitSystemWindows(insets); 4431 if (!done) { 4432 final int count = mChildrenCount; 4433 final View[] children = mChildren; 4434 for (int i = 0; i < count; i++) { 4435 done = children[i].fitSystemWindows(insets); 4436 if (done) { 4437 break; 4438 } 4439 } 4440 } 4441 return done; 4442 } 4443 4444 /** 4445 * Returns the animation listener to which layout animation events are 4446 * sent. 4447 * 4448 * @return an {@link android.view.animation.Animation.AnimationListener} 4449 */ 4450 public Animation.AnimationListener getLayoutAnimationListener() { 4451 return mAnimationListener; 4452 } 4453 4454 @Override 4455 protected void drawableStateChanged() { 4456 super.drawableStateChanged(); 4457 4458 if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) { 4459 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 4460 throw new IllegalStateException("addStateFromChildren cannot be enabled if a" 4461 + " child has duplicateParentState set to true"); 4462 } 4463 4464 final View[] children = mChildren; 4465 final int count = mChildrenCount; 4466 4467 for (int i = 0; i < count; i++) { 4468 final View child = children[i]; 4469 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) { 4470 child.refreshDrawableState(); 4471 } 4472 } 4473 } 4474 } 4475 4476 @Override 4477 public void jumpDrawablesToCurrentState() { 4478 super.jumpDrawablesToCurrentState(); 4479 final View[] children = mChildren; 4480 final int count = mChildrenCount; 4481 for (int i = 0; i < count; i++) { 4482 children[i].jumpDrawablesToCurrentState(); 4483 } 4484 } 4485 4486 @Override 4487 protected int[] onCreateDrawableState(int extraSpace) { 4488 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) { 4489 return super.onCreateDrawableState(extraSpace); 4490 } 4491 4492 int need = 0; 4493 int n = getChildCount(); 4494 for (int i = 0; i < n; i++) { 4495 int[] childState = getChildAt(i).getDrawableState(); 4496 4497 if (childState != null) { 4498 need += childState.length; 4499 } 4500 } 4501 4502 int[] state = super.onCreateDrawableState(extraSpace + need); 4503 4504 for (int i = 0; i < n; i++) { 4505 int[] childState = getChildAt(i).getDrawableState(); 4506 4507 if (childState != null) { 4508 state = mergeDrawableStates(state, childState); 4509 } 4510 } 4511 4512 return state; 4513 } 4514 4515 /** 4516 * Sets 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 void setAddStatesFromChildren(boolean addsStates) { 4522 if (addsStates) { 4523 mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN; 4524 } else { 4525 mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN; 4526 } 4527 4528 refreshDrawableState(); 4529 } 4530 4531 /** 4532 * Returns whether this ViewGroup's drawable states also include 4533 * its children's drawable states. This is used, for example, to 4534 * make a group appear to be focused when its child EditText or button 4535 * is focused. 4536 */ 4537 public boolean addStatesFromChildren() { 4538 return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0; 4539 } 4540 4541 /** 4542 * If {link #addStatesFromChildren} is true, refreshes this group's 4543 * drawable state (to include the states from its children). 4544 */ 4545 public void childDrawableStateChanged(View child) { 4546 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 4547 refreshDrawableState(); 4548 } 4549 } 4550 4551 /** 4552 * Specifies the animation listener to which layout animation events must 4553 * be sent. Only 4554 * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)} 4555 * and 4556 * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)} 4557 * are invoked. 4558 * 4559 * @param animationListener the layout animation listener 4560 */ 4561 public void setLayoutAnimationListener(Animation.AnimationListener animationListener) { 4562 mAnimationListener = animationListener; 4563 } 4564 4565 /** 4566 * LayoutParams are used by views to tell their parents how they want to be 4567 * laid out. See 4568 * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes} 4569 * for a list of all child view attributes that this class supports. 4570 * 4571 * <p> 4572 * The base LayoutParams class just describes how big the view wants to be 4573 * for both width and height. For each dimension, it can specify one of: 4574 * <ul> 4575 * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which 4576 * means that the view wants to be as big as its parent (minus padding) 4577 * <li> WRAP_CONTENT, which means that the view wants to be just big enough 4578 * to enclose its content (plus padding) 4579 * <li> an exact number 4580 * </ul> 4581 * There are subclasses of LayoutParams for different subclasses of 4582 * ViewGroup. For example, AbsoluteLayout has its own subclass of 4583 * LayoutParams which adds an X and Y value. 4584 * 4585 * @attr ref android.R.styleable#ViewGroup_Layout_layout_height 4586 * @attr ref android.R.styleable#ViewGroup_Layout_layout_width 4587 */ 4588 public static class LayoutParams { 4589 /** 4590 * Special value for the height or width requested by a View. 4591 * FILL_PARENT means that the view wants to be as big as its parent, 4592 * minus the parent's padding, if any. This value is deprecated 4593 * starting in API Level 8 and replaced by {@link #MATCH_PARENT}. 4594 */ 4595 @SuppressWarnings({"UnusedDeclaration"}) 4596 @Deprecated 4597 public static final int FILL_PARENT = -1; 4598 4599 /** 4600 * Special value for the height or width requested by a View. 4601 * MATCH_PARENT means that the view wants to be as big as its parent, 4602 * minus the parent's padding, if any. Introduced in API Level 8. 4603 */ 4604 public static final int MATCH_PARENT = -1; 4605 4606 /** 4607 * Special value for the height or width requested by a View. 4608 * WRAP_CONTENT means that the view wants to be just large enough to fit 4609 * its own internal content, taking its own padding into account. 4610 */ 4611 public static final int WRAP_CONTENT = -2; 4612 4613 /** 4614 * Information about how wide the view wants to be. Can be one of the 4615 * constants FILL_PARENT (replaced by MATCH_PARENT , 4616 * in API Level 8) or WRAP_CONTENT. or an exact size. 4617 */ 4618 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4619 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 4620 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 4621 }) 4622 public int width; 4623 4624 /** 4625 * Information about how tall the view wants to be. Can be one of the 4626 * constants FILL_PARENT (replaced by MATCH_PARENT , 4627 * in API Level 8) or WRAP_CONTENT. or an exact size. 4628 */ 4629 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4630 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 4631 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 4632 }) 4633 public int height; 4634 4635 /** 4636 * Used to animate layouts. 4637 */ 4638 public LayoutAnimationController.AnimationParameters layoutAnimationParameters; 4639 4640 /** 4641 * Creates a new set of layout parameters. The values are extracted from 4642 * the supplied attributes set and context. The XML attributes mapped 4643 * to this set of layout parameters are: 4644 * 4645 * <ul> 4646 * <li><code>layout_width</code>: the width, either an exact value, 4647 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 4648 * {@link #MATCH_PARENT} in API Level 8)</li> 4649 * <li><code>layout_height</code>: the height, either an exact value, 4650 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 4651 * {@link #MATCH_PARENT} in API Level 8)</li> 4652 * </ul> 4653 * 4654 * @param c the application environment 4655 * @param attrs the set of attributes from which to extract the layout 4656 * parameters' values 4657 */ 4658 public LayoutParams(Context c, AttributeSet attrs) { 4659 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout); 4660 setBaseAttributes(a, 4661 R.styleable.ViewGroup_Layout_layout_width, 4662 R.styleable.ViewGroup_Layout_layout_height); 4663 a.recycle(); 4664 } 4665 4666 /** 4667 * Creates a new set of layout parameters with the specified width 4668 * and height. 4669 * 4670 * @param width the width, either {@link #WRAP_CONTENT}, 4671 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 4672 * API Level 8), or a fixed size in pixels 4673 * @param height the height, either {@link #WRAP_CONTENT}, 4674 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 4675 * API Level 8), or a fixed size in pixels 4676 */ 4677 public LayoutParams(int width, int height) { 4678 this.width = width; 4679 this.height = height; 4680 } 4681 4682 /** 4683 * Copy constructor. Clones the width and height values of the source. 4684 * 4685 * @param source The layout params to copy from. 4686 */ 4687 public LayoutParams(LayoutParams source) { 4688 this.width = source.width; 4689 this.height = source.height; 4690 } 4691 4692 /** 4693 * Used internally by MarginLayoutParams. 4694 * @hide 4695 */ 4696 LayoutParams() { 4697 } 4698 4699 /** 4700 * Extracts the layout parameters from the supplied attributes. 4701 * 4702 * @param a the style attributes to extract the parameters from 4703 * @param widthAttr the identifier of the width attribute 4704 * @param heightAttr the identifier of the height attribute 4705 */ 4706 protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { 4707 width = a.getLayoutDimension(widthAttr, "layout_width"); 4708 height = a.getLayoutDimension(heightAttr, "layout_height"); 4709 } 4710 4711 /** 4712 * Returns a String representation of this set of layout parameters. 4713 * 4714 * @param output the String to prepend to the internal representation 4715 * @return a String with the following format: output + 4716 * "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }" 4717 * 4718 * @hide 4719 */ 4720 public String debug(String output) { 4721 return output + "ViewGroup.LayoutParams={ width=" 4722 + sizeToString(width) + ", height=" + sizeToString(height) + " }"; 4723 } 4724 4725 /** 4726 * Converts the specified size to a readable String. 4727 * 4728 * @param size the size to convert 4729 * @return a String instance representing the supplied size 4730 * 4731 * @hide 4732 */ 4733 protected static String sizeToString(int size) { 4734 if (size == WRAP_CONTENT) { 4735 return "wrap-content"; 4736 } 4737 if (size == MATCH_PARENT) { 4738 return "match-parent"; 4739 } 4740 return String.valueOf(size); 4741 } 4742 } 4743 4744 /** 4745 * Per-child layout information for layouts that support margins. 4746 * See 4747 * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes} 4748 * for a list of all child view attributes that this class supports. 4749 */ 4750 public static class MarginLayoutParams extends ViewGroup.LayoutParams { 4751 /** 4752 * The left margin in pixels of the child. 4753 */ 4754 @ViewDebug.ExportedProperty(category = "layout") 4755 public int leftMargin; 4756 4757 /** 4758 * The top margin in pixels of the child. 4759 */ 4760 @ViewDebug.ExportedProperty(category = "layout") 4761 public int topMargin; 4762 4763 /** 4764 * The right margin in pixels of the child. 4765 */ 4766 @ViewDebug.ExportedProperty(category = "layout") 4767 public int rightMargin; 4768 4769 /** 4770 * The bottom margin in pixels of the child. 4771 */ 4772 @ViewDebug.ExportedProperty(category = "layout") 4773 public int bottomMargin; 4774 4775 /** 4776 * Creates a new set of layout parameters. The values are extracted from 4777 * the supplied attributes set and context. 4778 * 4779 * @param c the application environment 4780 * @param attrs the set of attributes from which to extract the layout 4781 * parameters' values 4782 */ 4783 public MarginLayoutParams(Context c, AttributeSet attrs) { 4784 super(); 4785 4786 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout); 4787 setBaseAttributes(a, 4788 R.styleable.ViewGroup_MarginLayout_layout_width, 4789 R.styleable.ViewGroup_MarginLayout_layout_height); 4790 4791 int margin = a.getDimensionPixelSize( 4792 com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1); 4793 if (margin >= 0) { 4794 leftMargin = margin; 4795 topMargin = margin; 4796 rightMargin= margin; 4797 bottomMargin = margin; 4798 } else { 4799 leftMargin = a.getDimensionPixelSize( 4800 R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0); 4801 topMargin = a.getDimensionPixelSize( 4802 R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0); 4803 rightMargin = a.getDimensionPixelSize( 4804 R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0); 4805 bottomMargin = a.getDimensionPixelSize( 4806 R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0); 4807 } 4808 4809 a.recycle(); 4810 } 4811 4812 /** 4813 * {@inheritDoc} 4814 */ 4815 public MarginLayoutParams(int width, int height) { 4816 super(width, height); 4817 } 4818 4819 /** 4820 * Copy constructor. Clones the width, height and margin values of the source. 4821 * 4822 * @param source The layout params to copy from. 4823 */ 4824 public MarginLayoutParams(MarginLayoutParams source) { 4825 this.width = source.width; 4826 this.height = source.height; 4827 4828 this.leftMargin = source.leftMargin; 4829 this.topMargin = source.topMargin; 4830 this.rightMargin = source.rightMargin; 4831 this.bottomMargin = source.bottomMargin; 4832 } 4833 4834 /** 4835 * {@inheritDoc} 4836 */ 4837 public MarginLayoutParams(LayoutParams source) { 4838 super(source); 4839 } 4840 4841 /** 4842 * Sets the margins, in pixels. 4843 * 4844 * @param left the left margin size 4845 * @param top the top margin size 4846 * @param right the right margin size 4847 * @param bottom the bottom margin size 4848 * 4849 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft 4850 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 4851 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight 4852 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 4853 */ 4854 public void setMargins(int left, int top, int right, int bottom) { 4855 leftMargin = left; 4856 topMargin = top; 4857 rightMargin = right; 4858 bottomMargin = bottom; 4859 } 4860 } 4861 4862 /* Describes a touched view and the ids of the pointers that it has captured. 4863 * 4864 * This code assumes that pointer ids are always in the range 0..31 such that 4865 * it can use a bitfield to track which pointer ids are present. 4866 * As it happens, the lower layers of the input dispatch pipeline also use the 4867 * same trick so the assumption should be safe here... 4868 */ 4869 private static final class TouchTarget { 4870 private static final int MAX_RECYCLED = 32; 4871 private static final Object sRecycleLock = new Object(); 4872 private static TouchTarget sRecycleBin; 4873 private static int sRecycledCount; 4874 4875 public static final int ALL_POINTER_IDS = -1; // all ones 4876 4877 // The touched child view. 4878 public View child; 4879 4880 // The combined bit mask of pointer ids for all pointers captured by the target. 4881 public int pointerIdBits; 4882 4883 // The next target in the target list. 4884 public TouchTarget next; 4885 4886 private TouchTarget() { 4887 } 4888 4889 public static TouchTarget obtain(View child, int pointerIdBits) { 4890 final TouchTarget target; 4891 synchronized (sRecycleLock) { 4892 if (sRecycleBin == null) { 4893 target = new TouchTarget(); 4894 } else { 4895 target = sRecycleBin; 4896 sRecycleBin = target.next; 4897 sRecycledCount--; 4898 target.next = null; 4899 } 4900 } 4901 target.child = child; 4902 target.pointerIdBits = pointerIdBits; 4903 return target; 4904 } 4905 4906 public void recycle() { 4907 synchronized (sRecycleLock) { 4908 if (sRecycledCount < MAX_RECYCLED) { 4909 next = sRecycleBin; 4910 sRecycleBin = this; 4911 sRecycledCount += 1; 4912 } else { 4913 next = null; 4914 } 4915 child = null; 4916 } 4917 } 4918 } 4919} 4920