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