ViewGroup.java revision d7910dd42a24705172f2794de940f715bbc41410
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 android.content.Context; 21import android.content.res.Configuration; 22import android.content.res.TypedArray; 23import android.graphics.Bitmap; 24import android.graphics.Canvas; 25import android.graphics.Color; 26import android.graphics.Insets; 27import android.graphics.Matrix; 28import android.graphics.Paint; 29import android.graphics.PointF; 30import android.graphics.Rect; 31import android.graphics.RectF; 32import android.graphics.Region; 33import android.os.Build; 34import android.os.Parcelable; 35import android.os.SystemClock; 36import android.util.AttributeSet; 37import android.util.Log; 38import android.util.SparseArray; 39import android.view.accessibility.AccessibilityEvent; 40import android.view.accessibility.AccessibilityNodeInfo; 41import android.view.animation.Animation; 42import android.view.animation.AnimationUtils; 43import android.view.animation.LayoutAnimationController; 44import android.view.animation.Transformation; 45 46import com.android.internal.R; 47import com.android.internal.util.Predicate; 48 49import java.util.ArrayList; 50import java.util.Collections; 51import java.util.HashSet; 52 53/** 54 * <p> 55 * A <code>ViewGroup</code> is a special view that can contain other views 56 * (called children.) The view group is the base class for layouts and views 57 * containers. This class also defines the 58 * {@link android.view.ViewGroup.LayoutParams} class which serves as the base 59 * class for layouts parameters. 60 * </p> 61 * 62 * <p> 63 * Also see {@link LayoutParams} for layout attributes. 64 * </p> 65 * 66 * <div class="special reference"> 67 * <h3>Developer Guides</h3> 68 * <p>For more information about creating user interface layouts, read the 69 * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer 70 * guide.</p></div> 71 * 72 * @attr ref android.R.styleable#ViewGroup_clipChildren 73 * @attr ref android.R.styleable#ViewGroup_clipToPadding 74 * @attr ref android.R.styleable#ViewGroup_layoutAnimation 75 * @attr ref android.R.styleable#ViewGroup_animationCache 76 * @attr ref android.R.styleable#ViewGroup_persistentDrawingCache 77 * @attr ref android.R.styleable#ViewGroup_alwaysDrawnWithCache 78 * @attr ref android.R.styleable#ViewGroup_addStatesFromChildren 79 * @attr ref android.R.styleable#ViewGroup_descendantFocusability 80 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges 81 */ 82public abstract class ViewGroup extends View implements ViewParent, ViewManager { 83 private static final String TAG = "ViewGroup"; 84 85 private static final boolean DBG = false; 86 87 /** 88 * Views which have been hidden or removed which need to be animated on 89 * their way out. 90 * This field should be made private, so it is hidden from the SDK. 91 * {@hide} 92 */ 93 protected ArrayList<View> mDisappearingChildren; 94 95 /** 96 * Listener used to propagate events indicating when children are added 97 * and/or removed from a view group. 98 * This field should be made private, so it is hidden from the SDK. 99 * {@hide} 100 */ 101 protected OnHierarchyChangeListener mOnHierarchyChangeListener; 102 103 // The view contained within this ViewGroup that has or contains focus. 104 private View mFocused; 105 106 /** 107 * A Transformation used when drawing children, to 108 * apply on the child being drawn. 109 */ 110 final Transformation mChildTransformation = new Transformation(); 111 112 /** 113 * Used to track the current invalidation region. 114 */ 115 RectF mInvalidateRegion; 116 117 /** 118 * A Transformation used to calculate a correct 119 * invalidation area when the application is autoscaled. 120 */ 121 Transformation mInvalidationTransformation; 122 123 // View currently under an ongoing drag 124 private View mCurrentDragView; 125 126 // Metadata about the ongoing drag 127 private DragEvent mCurrentDrag; 128 private HashSet<View> mDragNotifiedChildren; 129 130 // Does this group have a child that can accept the current drag payload? 131 private boolean mChildAcceptsDrag; 132 133 // Used during drag dispatch 134 private final PointF mLocalPoint = new PointF(); 135 136 // Layout animation 137 private LayoutAnimationController mLayoutAnimationController; 138 private Animation.AnimationListener mAnimationListener; 139 140 // First touch target in the linked list of touch targets. 141 private TouchTarget mFirstTouchTarget; 142 143 // For debugging only. You can see these in hierarchyviewer. 144 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 145 @ViewDebug.ExportedProperty(category = "events") 146 private long mLastTouchDownTime; 147 @ViewDebug.ExportedProperty(category = "events") 148 private int mLastTouchDownIndex = -1; 149 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 150 @ViewDebug.ExportedProperty(category = "events") 151 private float mLastTouchDownX; 152 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 153 @ViewDebug.ExportedProperty(category = "events") 154 private float mLastTouchDownY; 155 156 // First hover target in the linked list of hover targets. 157 // The hover targets are children which have received ACTION_HOVER_ENTER. 158 // They might not have actually handled the hover event, but we will 159 // continue sending hover events to them as long as the pointer remains over 160 // their bounds and the view group does not intercept hover. 161 private HoverTarget mFirstHoverTarget; 162 163 // True if the view group itself received a hover event. 164 // It might not have actually handled the hover event. 165 private boolean mHoveredSelf; 166 167 /** 168 * Internal flags. 169 * 170 * This field should be made private, so it is hidden from the SDK. 171 * {@hide} 172 */ 173 protected int mGroupFlags; 174 175 /* 176 * The layout mode: either {@link #CLIP_BOUNDS} or {@link #OPTICAL_BOUNDS} 177 */ 178 private int mLayoutMode = CLIP_BOUNDS; 179 180 /** 181 * NOTE: If you change the flags below make sure to reflect the changes 182 * the DisplayList class 183 */ 184 185 // When set, ViewGroup invalidates only the child's rectangle 186 // Set by default 187 static final int FLAG_CLIP_CHILDREN = 0x1; 188 189 // When set, ViewGroup excludes the padding area from the invalidate rectangle 190 // Set by default 191 private static final int FLAG_CLIP_TO_PADDING = 0x2; 192 193 // When set, dispatchDraw() will invoke invalidate(); this is set by drawChild() when 194 // a child needs to be invalidated and FLAG_OPTIMIZE_INVALIDATE is set 195 static final int FLAG_INVALIDATE_REQUIRED = 0x4; 196 197 // When set, dispatchDraw() will run the layout animation and unset the flag 198 private static final int FLAG_RUN_ANIMATION = 0x8; 199 200 // When set, there is either no layout animation on the ViewGroup or the layout 201 // animation is over 202 // Set by default 203 static final int FLAG_ANIMATION_DONE = 0x10; 204 205 // If set, this ViewGroup has padding; if unset there is no padding and we don't need 206 // to clip it, even if FLAG_CLIP_TO_PADDING is set 207 private static final int FLAG_PADDING_NOT_NULL = 0x20; 208 209 // When set, this ViewGroup caches its children in a Bitmap before starting a layout animation 210 // Set by default 211 private static final int FLAG_ANIMATION_CACHE = 0x40; 212 213 // When set, this ViewGroup converts calls to invalidate(Rect) to invalidate() during a 214 // layout animation; this avoid clobbering the hierarchy 215 // Automatically set when the layout animation starts, depending on the animation's 216 // characteristics 217 static final int FLAG_OPTIMIZE_INVALIDATE = 0x80; 218 219 // When set, the next call to drawChild() will clear mChildTransformation's matrix 220 static final int FLAG_CLEAR_TRANSFORMATION = 0x100; 221 222 // When set, this ViewGroup invokes mAnimationListener.onAnimationEnd() and removes 223 // the children's Bitmap caches if necessary 224 // This flag is set when the layout animation is over (after FLAG_ANIMATION_DONE is set) 225 private static final int FLAG_NOTIFY_ANIMATION_LISTENER = 0x200; 226 227 /** 228 * When set, the drawing method will call {@link #getChildDrawingOrder(int, int)} 229 * to get the index of the child to draw for that iteration. 230 * 231 * @hide 232 */ 233 protected static final int FLAG_USE_CHILD_DRAWING_ORDER = 0x400; 234 235 /** 236 * When set, this ViewGroup supports static transformations on children; this causes 237 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be 238 * invoked when a child is drawn. 239 * 240 * Any subclass overriding 241 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should 242 * set this flags in {@link #mGroupFlags}. 243 * 244 * {@hide} 245 */ 246 protected static final int FLAG_SUPPORT_STATIC_TRANSFORMATIONS = 0x800; 247 248 // When the previous drawChild() invocation used an alpha value that was lower than 249 // 1.0 and set it in mCachePaint 250 static final int FLAG_ALPHA_LOWER_THAN_ONE = 0x1000; 251 252 /** 253 * When set, this ViewGroup's drawable states also include those 254 * of its children. 255 */ 256 private static final int FLAG_ADD_STATES_FROM_CHILDREN = 0x2000; 257 258 /** 259 * When set, this ViewGroup tries to always draw its children using their drawing cache. 260 */ 261 static final int FLAG_ALWAYS_DRAWN_WITH_CACHE = 0x4000; 262 263 /** 264 * When set, and if FLAG_ALWAYS_DRAWN_WITH_CACHE is not set, this ViewGroup will try to 265 * draw its children with their drawing cache. 266 */ 267 static final int FLAG_CHILDREN_DRAWN_WITH_CACHE = 0x8000; 268 269 /** 270 * When set, this group will go through its list of children to notify them of 271 * any drawable state change. 272 */ 273 private static final int FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE = 0x10000; 274 275 private static final int FLAG_MASK_FOCUSABILITY = 0x60000; 276 277 /** 278 * This view will get focus before any of its descendants. 279 */ 280 public static final int FOCUS_BEFORE_DESCENDANTS = 0x20000; 281 282 /** 283 * This view will get focus only if none of its descendants want it. 284 */ 285 public static final int FOCUS_AFTER_DESCENDANTS = 0x40000; 286 287 /** 288 * This view will block any of its descendants from getting focus, even 289 * if they are focusable. 290 */ 291 public static final int FOCUS_BLOCK_DESCENDANTS = 0x60000; 292 293 /** 294 * Used to map between enum in attrubutes and flag values. 295 */ 296 private static final int[] DESCENDANT_FOCUSABILITY_FLAGS = 297 {FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, 298 FOCUS_BLOCK_DESCENDANTS}; 299 300 /** 301 * When set, this ViewGroup should not intercept touch events. 302 * {@hide} 303 */ 304 protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000; 305 306 /** 307 * When set, this ViewGroup will split MotionEvents to multiple child Views when appropriate. 308 */ 309 private static final int FLAG_SPLIT_MOTION_EVENTS = 0x200000; 310 311 /** 312 * When set, this ViewGroup will not dispatch onAttachedToWindow calls 313 * to children when adding new views. This is used to prevent multiple 314 * onAttached calls when a ViewGroup adds children in its own onAttached method. 315 */ 316 private static final int FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW = 0x400000; 317 318 /** 319 * Indicates which types of drawing caches are to be kept in memory. 320 * This field should be made private, so it is hidden from the SDK. 321 * {@hide} 322 */ 323 protected int mPersistentDrawingCache; 324 325 /** 326 * Used to indicate that no drawing cache should be kept in memory. 327 */ 328 public static final int PERSISTENT_NO_CACHE = 0x0; 329 330 /** 331 * Used to indicate that the animation drawing cache should be kept in memory. 332 */ 333 public static final int PERSISTENT_ANIMATION_CACHE = 0x1; 334 335 /** 336 * Used to indicate that the scrolling drawing cache should be kept in memory. 337 */ 338 public static final int PERSISTENT_SCROLLING_CACHE = 0x2; 339 340 /** 341 * Used to indicate that all drawing caches should be kept in memory. 342 */ 343 public static final int PERSISTENT_ALL_CACHES = 0x3; 344 345 // Layout Modes 346 347 /** 348 * This constant is a {@link #setLayoutMode(int) layoutMode}. 349 * Clip bounds are the raw values of {@link #getLeft() left}, {@link #getTop() top}, 350 * {@link #getRight() right} and {@link #getBottom() bottom}. 351 */ 352 public static final int CLIP_BOUNDS = 0; 353 354 /** 355 * This constant is a {@link #setLayoutMode(int) layoutMode}. 356 * Optical bounds describe where a widget appears to be. They sit inside the clip 357 * bounds which need to cover a larger area to allow other effects, 358 * such as shadows and glows, to be drawn. 359 */ 360 public static final int OPTICAL_BOUNDS = 1; 361 362 /** 363 * We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL 364 * are set at the same time. 365 */ 366 protected static final int CLIP_TO_PADDING_MASK = FLAG_CLIP_TO_PADDING | FLAG_PADDING_NOT_NULL; 367 368 // Index of the child's left position in the mLocation array 369 private static final int CHILD_LEFT_INDEX = 0; 370 // Index of the child's top position in the mLocation array 371 private static final int CHILD_TOP_INDEX = 1; 372 373 // Child views of this ViewGroup 374 private View[] mChildren; 375 // Number of valid children in the mChildren array, the rest should be null or not 376 // considered as children 377 378 private boolean mLayoutSuppressed = false; 379 380 private int mChildrenCount; 381 382 private static final int ARRAY_INITIAL_CAPACITY = 12; 383 private static final int ARRAY_CAPACITY_INCREMENT = 12; 384 385 private static Paint sDebugPaint; 386 private static float[] sDebugLines; 387 388 // Used to draw cached views 389 Paint mCachePaint; 390 391 // Used to animate add/remove changes in layout 392 private LayoutTransition mTransition; 393 394 // The set of views that are currently being transitioned. This list is used to track views 395 // being removed that should not actually be removed from the parent yet because they are 396 // being animated. 397 private ArrayList<View> mTransitioningViews; 398 399 // List of children changing visibility. This is used to potentially keep rendering 400 // views during a transition when they otherwise would have become gone/invisible 401 private ArrayList<View> mVisibilityChangingChildren; 402 403 // Indicates whether this container will use its children layers to draw 404 @ViewDebug.ExportedProperty(category = "drawing") 405 boolean mDrawLayers = true; 406 407 // Indicates how many of this container's child subtrees contain transient state 408 @ViewDebug.ExportedProperty(category = "layout") 409 private int mChildCountWithTransientState = 0; 410 411 public ViewGroup(Context context) { 412 super(context); 413 initViewGroup(); 414 } 415 416 public ViewGroup(Context context, AttributeSet attrs) { 417 super(context, attrs); 418 initViewGroup(); 419 initFromAttributes(context, attrs); 420 } 421 422 public ViewGroup(Context context, AttributeSet attrs, int defStyle) { 423 super(context, attrs, defStyle); 424 initViewGroup(); 425 initFromAttributes(context, attrs); 426 } 427 428 private boolean debugDraw() { 429 return mAttachInfo != null && mAttachInfo.mDebugLayout; 430 } 431 432 private void initViewGroup() { 433 // ViewGroup doesn't draw by default 434 if (!debugDraw()) { 435 setFlags(WILL_NOT_DRAW, DRAW_MASK); 436 } 437 mGroupFlags |= FLAG_CLIP_CHILDREN; 438 mGroupFlags |= FLAG_CLIP_TO_PADDING; 439 mGroupFlags |= FLAG_ANIMATION_DONE; 440 mGroupFlags |= FLAG_ANIMATION_CACHE; 441 mGroupFlags |= FLAG_ALWAYS_DRAWN_WITH_CACHE; 442 443 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) { 444 mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS; 445 } 446 447 setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS); 448 449 mChildren = new View[ARRAY_INITIAL_CAPACITY]; 450 mChildrenCount = 0; 451 452 mPersistentDrawingCache = PERSISTENT_SCROLLING_CACHE; 453 } 454 455 private void initFromAttributes(Context context, AttributeSet attrs) { 456 TypedArray a = context.obtainStyledAttributes(attrs, 457 R.styleable.ViewGroup); 458 459 final int N = a.getIndexCount(); 460 for (int i = 0; i < N; i++) { 461 int attr = a.getIndex(i); 462 switch (attr) { 463 case R.styleable.ViewGroup_clipChildren: 464 setClipChildren(a.getBoolean(attr, true)); 465 break; 466 case R.styleable.ViewGroup_clipToPadding: 467 setClipToPadding(a.getBoolean(attr, true)); 468 break; 469 case R.styleable.ViewGroup_animationCache: 470 setAnimationCacheEnabled(a.getBoolean(attr, true)); 471 break; 472 case R.styleable.ViewGroup_persistentDrawingCache: 473 setPersistentDrawingCache(a.getInt(attr, PERSISTENT_SCROLLING_CACHE)); 474 break; 475 case R.styleable.ViewGroup_addStatesFromChildren: 476 setAddStatesFromChildren(a.getBoolean(attr, false)); 477 break; 478 case R.styleable.ViewGroup_alwaysDrawnWithCache: 479 setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true)); 480 break; 481 case R.styleable.ViewGroup_layoutAnimation: 482 int id = a.getResourceId(attr, -1); 483 if (id > 0) { 484 setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id)); 485 } 486 break; 487 case R.styleable.ViewGroup_descendantFocusability: 488 setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]); 489 break; 490 case R.styleable.ViewGroup_splitMotionEvents: 491 setMotionEventSplittingEnabled(a.getBoolean(attr, false)); 492 break; 493 case R.styleable.ViewGroup_animateLayoutChanges: 494 boolean animateLayoutChanges = a.getBoolean(attr, false); 495 if (animateLayoutChanges) { 496 setLayoutTransition(new LayoutTransition()); 497 } 498 break; 499 } 500 } 501 502 a.recycle(); 503 } 504 505 /** 506 * Gets the descendant focusability of this view group. The descendant 507 * focusability defines the relationship between this view group and its 508 * descendants when looking for a view to take focus in 509 * {@link #requestFocus(int, android.graphics.Rect)}. 510 * 511 * @return one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS}, 512 * {@link #FOCUS_BLOCK_DESCENDANTS}. 513 */ 514 @ViewDebug.ExportedProperty(category = "focus", mapping = { 515 @ViewDebug.IntToString(from = FOCUS_BEFORE_DESCENDANTS, to = "FOCUS_BEFORE_DESCENDANTS"), 516 @ViewDebug.IntToString(from = FOCUS_AFTER_DESCENDANTS, to = "FOCUS_AFTER_DESCENDANTS"), 517 @ViewDebug.IntToString(from = FOCUS_BLOCK_DESCENDANTS, to = "FOCUS_BLOCK_DESCENDANTS") 518 }) 519 public int getDescendantFocusability() { 520 return mGroupFlags & FLAG_MASK_FOCUSABILITY; 521 } 522 523 /** 524 * Set the descendant focusability of this view group. This defines the relationship 525 * between this view group and its descendants when looking for a view to 526 * take focus in {@link #requestFocus(int, android.graphics.Rect)}. 527 * 528 * @param focusability one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS}, 529 * {@link #FOCUS_BLOCK_DESCENDANTS}. 530 */ 531 public void setDescendantFocusability(int focusability) { 532 switch (focusability) { 533 case FOCUS_BEFORE_DESCENDANTS: 534 case FOCUS_AFTER_DESCENDANTS: 535 case FOCUS_BLOCK_DESCENDANTS: 536 break; 537 default: 538 throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, " 539 + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS"); 540 } 541 mGroupFlags &= ~FLAG_MASK_FOCUSABILITY; 542 mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY); 543 } 544 545 /** 546 * {@inheritDoc} 547 */ 548 @Override 549 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 550 if (mFocused != null) { 551 mFocused.unFocus(); 552 mFocused = null; 553 } 554 super.handleFocusGainInternal(direction, previouslyFocusedRect); 555 } 556 557 /** 558 * {@inheritDoc} 559 */ 560 public void requestChildFocus(View child, View focused) { 561 if (DBG) { 562 System.out.println(this + " requestChildFocus()"); 563 } 564 if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) { 565 return; 566 } 567 568 // Unfocus us, if necessary 569 super.unFocus(); 570 571 // We had a previous notion of who had focus. Clear it. 572 if (mFocused != child) { 573 if (mFocused != null) { 574 mFocused.unFocus(); 575 } 576 577 mFocused = child; 578 } 579 if (mParent != null) { 580 mParent.requestChildFocus(this, focused); 581 } 582 } 583 584 /** 585 * {@inheritDoc} 586 */ 587 public void focusableViewAvailable(View v) { 588 if (mParent != null 589 // shortcut: don't report a new focusable view if we block our descendants from 590 // getting focus 591 && (getDescendantFocusability() != FOCUS_BLOCK_DESCENDANTS) 592 // shortcut: don't report a new focusable view if we already are focused 593 // (and we don't prefer our descendants) 594 // 595 // note: knowing that mFocused is non-null is not a good enough reason 596 // to break the traversal since in that case we'd actually have to find 597 // the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and 598 // an ancestor of v; this will get checked for at ViewAncestor 599 && !(isFocused() && getDescendantFocusability() != FOCUS_AFTER_DESCENDANTS)) { 600 mParent.focusableViewAvailable(v); 601 } 602 } 603 604 /** 605 * {@inheritDoc} 606 */ 607 public boolean showContextMenuForChild(View originalView) { 608 return mParent != null && mParent.showContextMenuForChild(originalView); 609 } 610 611 /** 612 * {@inheritDoc} 613 */ 614 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 615 return mParent != null ? mParent.startActionModeForChild(originalView, callback) : null; 616 } 617 618 /** 619 * Find the nearest view in the specified direction that wants to take 620 * focus. 621 * 622 * @param focused The view that currently has focus 623 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and 624 * FOCUS_RIGHT, or 0 for not applicable. 625 */ 626 public View focusSearch(View focused, int direction) { 627 if (isRootNamespace()) { 628 // root namespace means we should consider ourselves the top of the 629 // tree for focus searching; otherwise we could be focus searching 630 // into other tabs. see LocalActivityManager and TabHost for more info 631 return FocusFinder.getInstance().findNextFocus(this, focused, direction); 632 } else if (mParent != null) { 633 return mParent.focusSearch(focused, direction); 634 } 635 return null; 636 } 637 638 /** 639 * {@inheritDoc} 640 */ 641 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 642 return false; 643 } 644 645 /** 646 * {@inheritDoc} 647 */ 648 @Override 649 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 650 ViewParent parent = mParent; 651 if (parent == null) { 652 return false; 653 } 654 final boolean propagate = onRequestSendAccessibilityEvent(child, event); 655 if (!propagate) { 656 return false; 657 } 658 return parent.requestSendAccessibilityEvent(this, event); 659 } 660 661 /** 662 * Called when a child has requested sending an {@link AccessibilityEvent} and 663 * gives an opportunity to its parent to augment the event. 664 * <p> 665 * If an {@link android.view.View.AccessibilityDelegate} has been specified via calling 666 * {@link android.view.View#setAccessibilityDelegate(android.view.View.AccessibilityDelegate)} its 667 * {@link android.view.View.AccessibilityDelegate#onRequestSendAccessibilityEvent(ViewGroup, View, AccessibilityEvent)} 668 * is responsible for handling this call. 669 * </p> 670 * 671 * @param child The child which requests sending the event. 672 * @param event The event to be sent. 673 * @return True if the event should be sent. 674 * 675 * @see #requestSendAccessibilityEvent(View, AccessibilityEvent) 676 */ 677 public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { 678 if (mAccessibilityDelegate != null) { 679 return mAccessibilityDelegate.onRequestSendAccessibilityEvent(this, child, event); 680 } else { 681 return onRequestSendAccessibilityEventInternal(child, event); 682 } 683 } 684 685 /** 686 * @see #onRequestSendAccessibilityEvent(View, AccessibilityEvent) 687 * 688 * Note: Called from the default {@link View.AccessibilityDelegate}. 689 */ 690 boolean onRequestSendAccessibilityEventInternal(View child, AccessibilityEvent event) { 691 return true; 692 } 693 694 /** 695 * Called when a child view has changed whether or not it is tracking transient state. 696 * 697 * @hide 698 */ 699 public void childHasTransientStateChanged(View child, boolean childHasTransientState) { 700 final boolean oldHasTransientState = hasTransientState(); 701 if (childHasTransientState) { 702 mChildCountWithTransientState++; 703 } else { 704 mChildCountWithTransientState--; 705 } 706 707 final boolean newHasTransientState = hasTransientState(); 708 if (mParent != null && oldHasTransientState != newHasTransientState) { 709 try { 710 mParent.childHasTransientStateChanged(this, newHasTransientState); 711 } catch (AbstractMethodError e) { 712 Log.e(TAG, mParent.getClass().getSimpleName() + 713 " does not fully implement ViewParent", e); 714 } 715 } 716 } 717 718 /** 719 * @hide 720 */ 721 @Override 722 public boolean hasTransientState() { 723 return mChildCountWithTransientState > 0 || super.hasTransientState(); 724 } 725 726 /** 727 * {@inheritDoc} 728 */ 729 @Override 730 public boolean dispatchUnhandledMove(View focused, int direction) { 731 return mFocused != null && 732 mFocused.dispatchUnhandledMove(focused, direction); 733 } 734 735 /** 736 * {@inheritDoc} 737 */ 738 public void clearChildFocus(View child) { 739 if (DBG) { 740 System.out.println(this + " clearChildFocus()"); 741 } 742 743 mFocused = null; 744 if (mParent != null) { 745 mParent.clearChildFocus(this); 746 } 747 } 748 749 /** 750 * {@inheritDoc} 751 */ 752 @Override 753 public void clearFocus() { 754 if (DBG) { 755 System.out.println(this + " clearFocus()"); 756 } 757 if (mFocused == null) { 758 super.clearFocus(); 759 } else { 760 mFocused.clearFocus(); 761 mFocused = null; 762 } 763 } 764 765 /** 766 * {@inheritDoc} 767 */ 768 @Override 769 void unFocus() { 770 if (DBG) { 771 System.out.println(this + " unFocus()"); 772 } 773 if (mFocused == null) { 774 super.unFocus(); 775 } else { 776 mFocused.unFocus(); 777 mFocused = null; 778 } 779 } 780 781 /** 782 * Returns the focused child of this view, if any. The child may have focus 783 * or contain focus. 784 * 785 * @return the focused child or null. 786 */ 787 public View getFocusedChild() { 788 return mFocused; 789 } 790 791 /** 792 * Returns true if this view has or contains focus 793 * 794 * @return true if this view has or contains focus 795 */ 796 @Override 797 public boolean hasFocus() { 798 return (mPrivateFlags & FOCUSED) != 0 || mFocused != null; 799 } 800 801 /* 802 * (non-Javadoc) 803 * 804 * @see android.view.View#findFocus() 805 */ 806 @Override 807 public View findFocus() { 808 if (DBG) { 809 System.out.println("Find focus in " + this + ": flags=" 810 + isFocused() + ", child=" + mFocused); 811 } 812 813 if (isFocused()) { 814 return this; 815 } 816 817 if (mFocused != null) { 818 return mFocused.findFocus(); 819 } 820 return null; 821 } 822 823 /** 824 * {@inheritDoc} 825 */ 826 @Override 827 public boolean hasFocusable() { 828 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 829 return false; 830 } 831 832 if (isFocusable()) { 833 return true; 834 } 835 836 final int descendantFocusability = getDescendantFocusability(); 837 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { 838 final int count = mChildrenCount; 839 final View[] children = mChildren; 840 841 for (int i = 0; i < count; i++) { 842 final View child = children[i]; 843 if (child.hasFocusable()) { 844 return true; 845 } 846 } 847 } 848 849 return false; 850 } 851 852 /** 853 * {@inheritDoc} 854 */ 855 @Override 856 public void addFocusables(ArrayList<View> views, int direction) { 857 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 858 } 859 860 /** 861 * {@inheritDoc} 862 */ 863 @Override 864 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 865 final int focusableCount = views.size(); 866 867 final int descendantFocusability = getDescendantFocusability(); 868 869 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { 870 final int count = mChildrenCount; 871 final View[] children = mChildren; 872 873 for (int i = 0; i < count; i++) { 874 final View child = children[i]; 875 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 876 child.addFocusables(views, direction, focusableMode); 877 } 878 } 879 } 880 881 // we add ourselves (if focusable) in all cases except for when we are 882 // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is 883 // to avoid the focus search finding layouts when a more precise search 884 // among the focusable children would be more interesting. 885 if ( 886 descendantFocusability != FOCUS_AFTER_DESCENDANTS || 887 // No focusable descendants 888 (focusableCount == views.size())) { 889 super.addFocusables(views, direction, focusableMode); 890 } 891 } 892 893 @Override 894 public void findViewsWithText(ArrayList<View> outViews, CharSequence text, int flags) { 895 super.findViewsWithText(outViews, text, flags); 896 final int childrenCount = mChildrenCount; 897 final View[] children = mChildren; 898 for (int i = 0; i < childrenCount; i++) { 899 View child = children[i]; 900 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE 901 && (child.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 902 child.findViewsWithText(outViews, text, flags); 903 } 904 } 905 } 906 907 @Override 908 View findViewByAccessibilityIdTraversal(int accessibilityId) { 909 View foundView = super.findViewByAccessibilityIdTraversal(accessibilityId); 910 if (foundView != null) { 911 return foundView; 912 } 913 final int childrenCount = mChildrenCount; 914 final View[] children = mChildren; 915 for (int i = 0; i < childrenCount; i++) { 916 View child = children[i]; 917 foundView = child.findViewByAccessibilityIdTraversal(accessibilityId); 918 if (foundView != null) { 919 return foundView; 920 } 921 } 922 return null; 923 } 924 925 /** 926 * {@inheritDoc} 927 */ 928 @Override 929 public void dispatchWindowFocusChanged(boolean hasFocus) { 930 super.dispatchWindowFocusChanged(hasFocus); 931 final int count = mChildrenCount; 932 final View[] children = mChildren; 933 for (int i = 0; i < count; i++) { 934 children[i].dispatchWindowFocusChanged(hasFocus); 935 } 936 } 937 938 /** 939 * {@inheritDoc} 940 */ 941 @Override 942 public void addTouchables(ArrayList<View> views) { 943 super.addTouchables(views); 944 945 final int count = mChildrenCount; 946 final View[] children = mChildren; 947 948 for (int i = 0; i < count; i++) { 949 final View child = children[i]; 950 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 951 child.addTouchables(views); 952 } 953 } 954 } 955 956 /** 957 * @hide 958 */ 959 @Override 960 public void makeOptionalFitsSystemWindows() { 961 super.makeOptionalFitsSystemWindows(); 962 final int count = mChildrenCount; 963 final View[] children = mChildren; 964 for (int i = 0; i < count; i++) { 965 children[i].makeOptionalFitsSystemWindows(); 966 } 967 } 968 969 /** 970 * {@inheritDoc} 971 */ 972 @Override 973 public void dispatchDisplayHint(int hint) { 974 super.dispatchDisplayHint(hint); 975 final int count = mChildrenCount; 976 final View[] children = mChildren; 977 for (int i = 0; i < count; i++) { 978 children[i].dispatchDisplayHint(hint); 979 } 980 } 981 982 /** 983 * Called when a view's visibility has changed. Notify the parent to take any appropriate 984 * action. 985 * 986 * @param child The view whose visibility has changed 987 * @param oldVisibility The previous visibility value (GONE, INVISIBLE, or VISIBLE). 988 * @param newVisibility The new visibility value (GONE, INVISIBLE, or VISIBLE). 989 * @hide 990 */ 991 protected void onChildVisibilityChanged(View child, int oldVisibility, int newVisibility) { 992 if (mTransition != null) { 993 if (newVisibility == VISIBLE) { 994 mTransition.showChild(this, child, oldVisibility); 995 } else { 996 mTransition.hideChild(this, child, newVisibility); 997 // Only track this on disappearing views - appearing views are already visible 998 // and don't need special handling during drawChild() 999 if (mVisibilityChangingChildren == null) { 1000 mVisibilityChangingChildren = new ArrayList<View>(); 1001 } 1002 mVisibilityChangingChildren.add(child); 1003 if (mTransitioningViews != null && mTransitioningViews.contains(child)) { 1004 addDisappearingView(child); 1005 } 1006 } 1007 } 1008 1009 // in all cases, for drags 1010 if (mCurrentDrag != null) { 1011 if (newVisibility == VISIBLE) { 1012 notifyChildOfDrag(child); 1013 } 1014 } 1015 } 1016 1017 /** 1018 * {@inheritDoc} 1019 */ 1020 @Override 1021 protected void dispatchVisibilityChanged(View changedView, int visibility) { 1022 super.dispatchVisibilityChanged(changedView, visibility); 1023 final int count = mChildrenCount; 1024 final View[] children = mChildren; 1025 for (int i = 0; i < count; i++) { 1026 children[i].dispatchVisibilityChanged(changedView, visibility); 1027 } 1028 } 1029 1030 /** 1031 * {@inheritDoc} 1032 */ 1033 @Override 1034 public void dispatchWindowVisibilityChanged(int visibility) { 1035 super.dispatchWindowVisibilityChanged(visibility); 1036 final int count = mChildrenCount; 1037 final View[] children = mChildren; 1038 for (int i = 0; i < count; i++) { 1039 children[i].dispatchWindowVisibilityChanged(visibility); 1040 } 1041 } 1042 1043 /** 1044 * {@inheritDoc} 1045 */ 1046 @Override 1047 public void dispatchConfigurationChanged(Configuration newConfig) { 1048 super.dispatchConfigurationChanged(newConfig); 1049 final int count = mChildrenCount; 1050 final View[] children = mChildren; 1051 for (int i = 0; i < count; i++) { 1052 children[i].dispatchConfigurationChanged(newConfig); 1053 } 1054 } 1055 1056 /** 1057 * {@inheritDoc} 1058 */ 1059 public void recomputeViewAttributes(View child) { 1060 if (mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 1061 ViewParent parent = mParent; 1062 if (parent != null) parent.recomputeViewAttributes(this); 1063 } 1064 } 1065 1066 @Override 1067 void dispatchCollectViewAttributes(AttachInfo attachInfo, int visibility) { 1068 if ((visibility & VISIBILITY_MASK) == VISIBLE) { 1069 super.dispatchCollectViewAttributes(attachInfo, visibility); 1070 final int count = mChildrenCount; 1071 final View[] children = mChildren; 1072 for (int i = 0; i < count; i++) { 1073 final View child = children[i]; 1074 child.dispatchCollectViewAttributes(attachInfo, 1075 visibility | (child.mViewFlags&VISIBILITY_MASK)); 1076 } 1077 } 1078 } 1079 1080 /** 1081 * {@inheritDoc} 1082 */ 1083 public void bringChildToFront(View child) { 1084 int index = indexOfChild(child); 1085 if (index >= 0) { 1086 removeFromArray(index); 1087 addInArray(child, mChildrenCount); 1088 child.mParent = this; 1089 } 1090 } 1091 1092 /** 1093 * {@inheritDoc} 1094 */ 1095 // TODO: Write real docs 1096 @Override 1097 public boolean dispatchDragEvent(DragEvent event) { 1098 boolean retval = false; 1099 final float tx = event.mX; 1100 final float ty = event.mY; 1101 1102 ViewRootImpl root = getViewRootImpl(); 1103 1104 // Dispatch down the view hierarchy 1105 switch (event.mAction) { 1106 case DragEvent.ACTION_DRAG_STARTED: { 1107 // clear state to recalculate which views we drag over 1108 mCurrentDragView = null; 1109 1110 // Set up our tracking of drag-started notifications 1111 mCurrentDrag = DragEvent.obtain(event); 1112 if (mDragNotifiedChildren == null) { 1113 mDragNotifiedChildren = new HashSet<View>(); 1114 } else { 1115 mDragNotifiedChildren.clear(); 1116 } 1117 1118 // Now dispatch down to our children, caching the responses 1119 mChildAcceptsDrag = false; 1120 final int count = mChildrenCount; 1121 final View[] children = mChildren; 1122 for (int i = 0; i < count; i++) { 1123 final View child = children[i]; 1124 child.mPrivateFlags2 &= ~View.DRAG_MASK; 1125 if (child.getVisibility() == VISIBLE) { 1126 final boolean handled = notifyChildOfDrag(children[i]); 1127 if (handled) { 1128 mChildAcceptsDrag = true; 1129 } 1130 } 1131 } 1132 1133 // Return HANDLED if one of our children can accept the drag 1134 if (mChildAcceptsDrag) { 1135 retval = true; 1136 } 1137 } break; 1138 1139 case DragEvent.ACTION_DRAG_ENDED: { 1140 // Release the bookkeeping now that the drag lifecycle has ended 1141 if (mDragNotifiedChildren != null) { 1142 for (View child : mDragNotifiedChildren) { 1143 // If a child was notified about an ongoing drag, it's told that it's over 1144 child.dispatchDragEvent(event); 1145 child.mPrivateFlags2 &= ~View.DRAG_MASK; 1146 child.refreshDrawableState(); 1147 } 1148 1149 mDragNotifiedChildren.clear(); 1150 mCurrentDrag.recycle(); 1151 mCurrentDrag = null; 1152 } 1153 1154 // We consider drag-ended to have been handled if one of our children 1155 // had offered to handle the drag. 1156 if (mChildAcceptsDrag) { 1157 retval = true; 1158 } 1159 } break; 1160 1161 case DragEvent.ACTION_DRAG_LOCATION: { 1162 // Find the [possibly new] drag target 1163 final View target = findFrontmostDroppableChildAt(event.mX, event.mY, mLocalPoint); 1164 1165 // If we've changed apparent drag target, tell the view root which view 1166 // we're over now [for purposes of the eventual drag-recipient-changed 1167 // notifications to the framework] and tell the new target that the drag 1168 // has entered its bounds. The root will see setDragFocus() calls all 1169 // the way down to the final leaf view that is handling the LOCATION event 1170 // before reporting the new potential recipient to the framework. 1171 if (mCurrentDragView != target) { 1172 root.setDragFocus(target); 1173 1174 final int action = event.mAction; 1175 // If we've dragged off of a child view, send it the EXITED message 1176 if (mCurrentDragView != null) { 1177 final View view = mCurrentDragView; 1178 event.mAction = DragEvent.ACTION_DRAG_EXITED; 1179 view.dispatchDragEvent(event); 1180 view.mPrivateFlags2 &= ~View.DRAG_HOVERED; 1181 view.refreshDrawableState(); 1182 } 1183 mCurrentDragView = target; 1184 1185 // If we've dragged over a new child view, send it the ENTERED message 1186 if (target != null) { 1187 event.mAction = DragEvent.ACTION_DRAG_ENTERED; 1188 target.dispatchDragEvent(event); 1189 target.mPrivateFlags2 |= View.DRAG_HOVERED; 1190 target.refreshDrawableState(); 1191 } 1192 event.mAction = action; // restore the event's original state 1193 } 1194 1195 // Dispatch the actual drag location notice, localized into its coordinates 1196 if (target != null) { 1197 event.mX = mLocalPoint.x; 1198 event.mY = mLocalPoint.y; 1199 1200 retval = target.dispatchDragEvent(event); 1201 1202 event.mX = tx; 1203 event.mY = ty; 1204 } 1205 } break; 1206 1207 /* Entered / exited dispatch 1208 * 1209 * DRAG_ENTERED is not dispatched downwards from ViewGroup. The reason for this is 1210 * that we're about to get the corresponding LOCATION event, which we will use to 1211 * determine which of our children is the new target; at that point we will 1212 * push a DRAG_ENTERED down to the new target child [which may itself be a ViewGroup]. 1213 * 1214 * DRAG_EXITED *is* dispatched all the way down immediately: once we know the 1215 * drag has left this ViewGroup, we know by definition that every contained subview 1216 * is also no longer under the drag point. 1217 */ 1218 1219 case DragEvent.ACTION_DRAG_EXITED: { 1220 if (mCurrentDragView != null) { 1221 final View view = mCurrentDragView; 1222 view.dispatchDragEvent(event); 1223 view.mPrivateFlags2 &= ~View.DRAG_HOVERED; 1224 view.refreshDrawableState(); 1225 1226 mCurrentDragView = null; 1227 } 1228 } break; 1229 1230 case DragEvent.ACTION_DROP: { 1231 if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, "Drop event: " + event); 1232 View target = findFrontmostDroppableChildAt(event.mX, event.mY, mLocalPoint); 1233 if (target != null) { 1234 if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, " dispatch drop to " + target); 1235 event.mX = mLocalPoint.x; 1236 event.mY = mLocalPoint.y; 1237 retval = target.dispatchDragEvent(event); 1238 event.mX = tx; 1239 event.mY = ty; 1240 } else { 1241 if (ViewDebug.DEBUG_DRAG) { 1242 Log.d(View.VIEW_LOG_TAG, " not dropped on an accepting view"); 1243 } 1244 } 1245 } break; 1246 } 1247 1248 // If none of our children could handle the event, try here 1249 if (!retval) { 1250 // Call up to the View implementation that dispatches to installed listeners 1251 retval = super.dispatchDragEvent(event); 1252 } 1253 return retval; 1254 } 1255 1256 // Find the frontmost child view that lies under the given point, and calculate 1257 // the position within its own local coordinate system. 1258 View findFrontmostDroppableChildAt(float x, float y, PointF outLocalPoint) { 1259 final int count = mChildrenCount; 1260 final View[] children = mChildren; 1261 for (int i = count - 1; i >= 0; i--) { 1262 final View child = children[i]; 1263 if (!child.canAcceptDrag()) { 1264 continue; 1265 } 1266 1267 if (isTransformedTouchPointInView(x, y, child, outLocalPoint)) { 1268 return child; 1269 } 1270 } 1271 return null; 1272 } 1273 1274 boolean notifyChildOfDrag(View child) { 1275 if (ViewDebug.DEBUG_DRAG) { 1276 Log.d(View.VIEW_LOG_TAG, "Sending drag-started to view: " + child); 1277 } 1278 1279 boolean canAccept = false; 1280 if (! mDragNotifiedChildren.contains(child)) { 1281 mDragNotifiedChildren.add(child); 1282 canAccept = child.dispatchDragEvent(mCurrentDrag); 1283 if (canAccept && !child.canAcceptDrag()) { 1284 child.mPrivateFlags2 |= View.DRAG_CAN_ACCEPT; 1285 child.refreshDrawableState(); 1286 } 1287 } 1288 return canAccept; 1289 } 1290 1291 @Override 1292 public void dispatchWindowSystemUiVisiblityChanged(int visible) { 1293 super.dispatchWindowSystemUiVisiblityChanged(visible); 1294 1295 final int count = mChildrenCount; 1296 final View[] children = mChildren; 1297 for (int i=0; i <count; i++) { 1298 final View child = children[i]; 1299 child.dispatchWindowSystemUiVisiblityChanged(visible); 1300 } 1301 } 1302 1303 @Override 1304 public void dispatchSystemUiVisibilityChanged(int visible) { 1305 super.dispatchSystemUiVisibilityChanged(visible); 1306 1307 final int count = mChildrenCount; 1308 final View[] children = mChildren; 1309 for (int i=0; i <count; i++) { 1310 final View child = children[i]; 1311 child.dispatchSystemUiVisibilityChanged(visible); 1312 } 1313 } 1314 1315 @Override 1316 void updateLocalSystemUiVisibility(int localValue, int localChanges) { 1317 super.updateLocalSystemUiVisibility(localValue, localChanges); 1318 1319 final int count = mChildrenCount; 1320 final View[] children = mChildren; 1321 for (int i=0; i <count; i++) { 1322 final View child = children[i]; 1323 child.updateLocalSystemUiVisibility(localValue, localChanges); 1324 } 1325 } 1326 1327 /** 1328 * {@inheritDoc} 1329 */ 1330 @Override 1331 public boolean dispatchKeyEventPreIme(KeyEvent event) { 1332 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1333 return super.dispatchKeyEventPreIme(event); 1334 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1335 return mFocused.dispatchKeyEventPreIme(event); 1336 } 1337 return false; 1338 } 1339 1340 /** 1341 * {@inheritDoc} 1342 */ 1343 @Override 1344 public boolean dispatchKeyEvent(KeyEvent event) { 1345 if (mInputEventConsistencyVerifier != null) { 1346 mInputEventConsistencyVerifier.onKeyEvent(event, 1); 1347 } 1348 1349 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1350 if (super.dispatchKeyEvent(event)) { 1351 return true; 1352 } 1353 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1354 if (mFocused.dispatchKeyEvent(event)) { 1355 return true; 1356 } 1357 } 1358 1359 if (mInputEventConsistencyVerifier != null) { 1360 mInputEventConsistencyVerifier.onUnhandledEvent(event, 1); 1361 } 1362 return false; 1363 } 1364 1365 /** 1366 * {@inheritDoc} 1367 */ 1368 @Override 1369 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 1370 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1371 return super.dispatchKeyShortcutEvent(event); 1372 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1373 return mFocused.dispatchKeyShortcutEvent(event); 1374 } 1375 return false; 1376 } 1377 1378 /** 1379 * {@inheritDoc} 1380 */ 1381 @Override 1382 public boolean dispatchTrackballEvent(MotionEvent event) { 1383 if (mInputEventConsistencyVerifier != null) { 1384 mInputEventConsistencyVerifier.onTrackballEvent(event, 1); 1385 } 1386 1387 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1388 if (super.dispatchTrackballEvent(event)) { 1389 return true; 1390 } 1391 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1392 if (mFocused.dispatchTrackballEvent(event)) { 1393 return true; 1394 } 1395 } 1396 1397 if (mInputEventConsistencyVerifier != null) { 1398 mInputEventConsistencyVerifier.onUnhandledEvent(event, 1); 1399 } 1400 return false; 1401 } 1402 1403 /** 1404 * {@inheritDoc} 1405 */ 1406 @SuppressWarnings({"ConstantConditions"}) 1407 @Override 1408 protected boolean dispatchHoverEvent(MotionEvent event) { 1409 final int action = event.getAction(); 1410 1411 // First check whether the view group wants to intercept the hover event. 1412 final boolean interceptHover = onInterceptHoverEvent(event); 1413 event.setAction(action); // restore action in case it was changed 1414 1415 MotionEvent eventNoHistory = event; 1416 boolean handled = false; 1417 1418 // Send events to the hovered children and build a new list of hover targets until 1419 // one is found that handles the event. 1420 HoverTarget firstOldHoverTarget = mFirstHoverTarget; 1421 mFirstHoverTarget = null; 1422 if (!interceptHover && action != MotionEvent.ACTION_HOVER_EXIT) { 1423 final float x = event.getX(); 1424 final float y = event.getY(); 1425 final int childrenCount = mChildrenCount; 1426 if (childrenCount != 0) { 1427 final View[] children = mChildren; 1428 HoverTarget lastHoverTarget = null; 1429 for (int i = childrenCount - 1; i >= 0; i--) { 1430 final View child = children[i]; 1431 if (!canViewReceivePointerEvents(child) 1432 || !isTransformedTouchPointInView(x, y, child, null)) { 1433 continue; 1434 } 1435 1436 // Obtain a hover target for this child. Dequeue it from the 1437 // old hover target list if the child was previously hovered. 1438 HoverTarget hoverTarget = firstOldHoverTarget; 1439 final boolean wasHovered; 1440 for (HoverTarget predecessor = null; ;) { 1441 if (hoverTarget == null) { 1442 hoverTarget = HoverTarget.obtain(child); 1443 wasHovered = false; 1444 break; 1445 } 1446 1447 if (hoverTarget.child == child) { 1448 if (predecessor != null) { 1449 predecessor.next = hoverTarget.next; 1450 } else { 1451 firstOldHoverTarget = hoverTarget.next; 1452 } 1453 hoverTarget.next = null; 1454 wasHovered = true; 1455 break; 1456 } 1457 1458 predecessor = hoverTarget; 1459 hoverTarget = hoverTarget.next; 1460 } 1461 1462 // Enqueue the hover target onto the new hover target list. 1463 if (lastHoverTarget != null) { 1464 lastHoverTarget.next = hoverTarget; 1465 } else { 1466 lastHoverTarget = hoverTarget; 1467 mFirstHoverTarget = hoverTarget; 1468 } 1469 1470 // Dispatch the event to the child. 1471 if (action == MotionEvent.ACTION_HOVER_ENTER) { 1472 if (!wasHovered) { 1473 // Send the enter as is. 1474 handled |= dispatchTransformedGenericPointerEvent( 1475 event, child); // enter 1476 } 1477 } else if (action == MotionEvent.ACTION_HOVER_MOVE) { 1478 if (!wasHovered) { 1479 // Synthesize an enter from a move. 1480 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1481 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER); 1482 handled |= dispatchTransformedGenericPointerEvent( 1483 eventNoHistory, child); // enter 1484 eventNoHistory.setAction(action); 1485 1486 handled |= dispatchTransformedGenericPointerEvent( 1487 eventNoHistory, child); // move 1488 } else { 1489 // Send the move as is. 1490 handled |= dispatchTransformedGenericPointerEvent(event, child); 1491 } 1492 } 1493 if (handled) { 1494 break; 1495 } 1496 } 1497 } 1498 } 1499 1500 // Send exit events to all previously hovered children that are no longer hovered. 1501 while (firstOldHoverTarget != null) { 1502 final View child = firstOldHoverTarget.child; 1503 1504 // Exit the old hovered child. 1505 if (action == MotionEvent.ACTION_HOVER_EXIT) { 1506 // Send the exit as is. 1507 handled |= dispatchTransformedGenericPointerEvent( 1508 event, child); // exit 1509 } else { 1510 // Synthesize an exit from a move or enter. 1511 // Ignore the result because hover focus has moved to a different view. 1512 if (action == MotionEvent.ACTION_HOVER_MOVE) { 1513 dispatchTransformedGenericPointerEvent( 1514 event, child); // move 1515 } 1516 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1517 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT); 1518 dispatchTransformedGenericPointerEvent( 1519 eventNoHistory, child); // exit 1520 eventNoHistory.setAction(action); 1521 } 1522 1523 final HoverTarget nextOldHoverTarget = firstOldHoverTarget.next; 1524 firstOldHoverTarget.recycle(); 1525 firstOldHoverTarget = nextOldHoverTarget; 1526 } 1527 1528 // Send events to the view group itself if no children have handled it. 1529 boolean newHoveredSelf = !handled; 1530 if (newHoveredSelf == mHoveredSelf) { 1531 if (newHoveredSelf) { 1532 // Send event to the view group as before. 1533 handled |= super.dispatchHoverEvent(event); 1534 } 1535 } else { 1536 if (mHoveredSelf) { 1537 // Exit the view group. 1538 if (action == MotionEvent.ACTION_HOVER_EXIT) { 1539 // Send the exit as is. 1540 handled |= super.dispatchHoverEvent(event); // exit 1541 } else { 1542 // Synthesize an exit from a move or enter. 1543 // Ignore the result because hover focus is moving to a different view. 1544 if (action == MotionEvent.ACTION_HOVER_MOVE) { 1545 super.dispatchHoverEvent(event); // move 1546 } 1547 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1548 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT); 1549 super.dispatchHoverEvent(eventNoHistory); // exit 1550 eventNoHistory.setAction(action); 1551 } 1552 mHoveredSelf = false; 1553 } 1554 1555 if (newHoveredSelf) { 1556 // Enter the view group. 1557 if (action == MotionEvent.ACTION_HOVER_ENTER) { 1558 // Send the enter as is. 1559 handled |= super.dispatchHoverEvent(event); // enter 1560 mHoveredSelf = true; 1561 } else if (action == MotionEvent.ACTION_HOVER_MOVE) { 1562 // Synthesize an enter from a move. 1563 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1564 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER); 1565 handled |= super.dispatchHoverEvent(eventNoHistory); // enter 1566 eventNoHistory.setAction(action); 1567 1568 handled |= super.dispatchHoverEvent(eventNoHistory); // move 1569 mHoveredSelf = true; 1570 } 1571 } 1572 } 1573 1574 // Recycle the copy of the event that we made. 1575 if (eventNoHistory != event) { 1576 eventNoHistory.recycle(); 1577 } 1578 1579 // Done. 1580 return handled; 1581 } 1582 1583 private void exitHoverTargets() { 1584 if (mHoveredSelf || mFirstHoverTarget != null) { 1585 final long now = SystemClock.uptimeMillis(); 1586 MotionEvent event = MotionEvent.obtain(now, now, 1587 MotionEvent.ACTION_HOVER_EXIT, 0.0f, 0.0f, 0); 1588 event.setSource(InputDevice.SOURCE_TOUCHSCREEN); 1589 dispatchHoverEvent(event); 1590 event.recycle(); 1591 } 1592 } 1593 1594 private void cancelHoverTarget(View view) { 1595 HoverTarget predecessor = null; 1596 HoverTarget target = mFirstHoverTarget; 1597 while (target != null) { 1598 final HoverTarget next = target.next; 1599 if (target.child == view) { 1600 if (predecessor == null) { 1601 mFirstHoverTarget = next; 1602 } else { 1603 predecessor.next = next; 1604 } 1605 target.recycle(); 1606 1607 final long now = SystemClock.uptimeMillis(); 1608 MotionEvent event = MotionEvent.obtain(now, now, 1609 MotionEvent.ACTION_HOVER_EXIT, 0.0f, 0.0f, 0); 1610 event.setSource(InputDevice.SOURCE_TOUCHSCREEN); 1611 view.dispatchHoverEvent(event); 1612 event.recycle(); 1613 return; 1614 } 1615 predecessor = target; 1616 target = next; 1617 } 1618 } 1619 1620 /** @hide */ 1621 @Override 1622 protected boolean hasHoveredChild() { 1623 return mFirstHoverTarget != null; 1624 } 1625 1626 @Override 1627 public void addChildrenForAccessibility(ArrayList<View> childrenForAccessibility) { 1628 ChildListForAccessibility children = ChildListForAccessibility.obtain(this, true); 1629 try { 1630 final int childrenCount = children.getChildCount(); 1631 for (int i = 0; i < childrenCount; i++) { 1632 View child = children.getChildAt(i); 1633 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE 1634 && (child.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 1635 if (child.includeForAccessibility()) { 1636 childrenForAccessibility.add(child); 1637 } else { 1638 child.addChildrenForAccessibility(childrenForAccessibility); 1639 } 1640 } 1641 } 1642 } finally { 1643 children.recycle(); 1644 } 1645 } 1646 1647 /** 1648 * @hide 1649 */ 1650 @Override 1651 public void childAccessibilityStateChanged(View child) { 1652 if (mParent != null) { 1653 mParent.childAccessibilityStateChanged(child); 1654 } 1655 } 1656 1657 /** 1658 * Implement this method to intercept hover events before they are handled 1659 * by child views. 1660 * <p> 1661 * This method is called before dispatching a hover event to a child of 1662 * the view group or to the view group's own {@link #onHoverEvent} to allow 1663 * the view group a chance to intercept the hover event. 1664 * This method can also be used to watch all pointer motions that occur within 1665 * the bounds of the view group even when the pointer is hovering over 1666 * a child of the view group rather than over the view group itself. 1667 * </p><p> 1668 * The view group can prevent its children from receiving hover events by 1669 * implementing this method and returning <code>true</code> to indicate 1670 * that it would like to intercept hover events. The view group must 1671 * continuously return <code>true</code> from {@link #onInterceptHoverEvent} 1672 * for as long as it wishes to continue intercepting hover events from 1673 * its children. 1674 * </p><p> 1675 * Interception preserves the invariant that at most one view can be 1676 * hovered at a time by transferring hover focus from the currently hovered 1677 * child to the view group or vice-versa as needed. 1678 * </p><p> 1679 * If this method returns <code>true</code> and a child is already hovered, then the 1680 * child view will first receive a hover exit event and then the view group 1681 * itself will receive a hover enter event in {@link #onHoverEvent}. 1682 * Likewise, if this method had previously returned <code>true</code> to intercept hover 1683 * events and instead returns <code>false</code> while the pointer is hovering 1684 * within the bounds of one of a child, then the view group will first receive a 1685 * hover exit event in {@link #onHoverEvent} and then the hovered child will 1686 * receive a hover enter event. 1687 * </p><p> 1688 * The default implementation always returns false. 1689 * </p> 1690 * 1691 * @param event The motion event that describes the hover. 1692 * @return True if the view group would like to intercept the hover event 1693 * and prevent its children from receiving it. 1694 */ 1695 public boolean onInterceptHoverEvent(MotionEvent event) { 1696 return false; 1697 } 1698 1699 private static MotionEvent obtainMotionEventNoHistoryOrSelf(MotionEvent event) { 1700 if (event.getHistorySize() == 0) { 1701 return event; 1702 } 1703 return MotionEvent.obtainNoHistory(event); 1704 } 1705 1706 /** 1707 * {@inheritDoc} 1708 */ 1709 @Override 1710 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 1711 // Send the event to the child under the pointer. 1712 final int childrenCount = mChildrenCount; 1713 if (childrenCount != 0) { 1714 final View[] children = mChildren; 1715 final float x = event.getX(); 1716 final float y = event.getY(); 1717 1718 for (int i = childrenCount - 1; i >= 0; i--) { 1719 final View child = children[i]; 1720 if (!canViewReceivePointerEvents(child) 1721 || !isTransformedTouchPointInView(x, y, child, null)) { 1722 continue; 1723 } 1724 1725 if (dispatchTransformedGenericPointerEvent(event, child)) { 1726 return true; 1727 } 1728 } 1729 } 1730 1731 // No child handled the event. Send it to this view group. 1732 return super.dispatchGenericPointerEvent(event); 1733 } 1734 1735 /** 1736 * {@inheritDoc} 1737 */ 1738 @Override 1739 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 1740 // Send the event to the focused child or to this view group if it has focus. 1741 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1742 return super.dispatchGenericFocusedEvent(event); 1743 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1744 return mFocused.dispatchGenericMotionEvent(event); 1745 } 1746 return false; 1747 } 1748 1749 /** 1750 * Dispatches a generic pointer event to a child, taking into account 1751 * transformations that apply to the child. 1752 * 1753 * @param event The event to send. 1754 * @param child The view to send the event to. 1755 * @return {@code true} if the child handled the event. 1756 */ 1757 private boolean dispatchTransformedGenericPointerEvent(MotionEvent event, View child) { 1758 final float offsetX = mScrollX - child.mLeft; 1759 final float offsetY = mScrollY - child.mTop; 1760 1761 boolean handled; 1762 if (!child.hasIdentityMatrix()) { 1763 MotionEvent transformedEvent = MotionEvent.obtain(event); 1764 transformedEvent.offsetLocation(offsetX, offsetY); 1765 transformedEvent.transform(child.getInverseMatrix()); 1766 handled = child.dispatchGenericMotionEvent(transformedEvent); 1767 transformedEvent.recycle(); 1768 } else { 1769 event.offsetLocation(offsetX, offsetY); 1770 handled = child.dispatchGenericMotionEvent(event); 1771 event.offsetLocation(-offsetX, -offsetY); 1772 } 1773 return handled; 1774 } 1775 1776 /** 1777 * {@inheritDoc} 1778 */ 1779 @Override 1780 public boolean dispatchTouchEvent(MotionEvent ev) { 1781 if (mInputEventConsistencyVerifier != null) { 1782 mInputEventConsistencyVerifier.onTouchEvent(ev, 1); 1783 } 1784 1785 boolean handled = false; 1786 if (onFilterTouchEventForSecurity(ev)) { 1787 final int action = ev.getAction(); 1788 final int actionMasked = action & MotionEvent.ACTION_MASK; 1789 1790 // Handle an initial down. 1791 if (actionMasked == MotionEvent.ACTION_DOWN) { 1792 // Throw away all previous state when starting a new touch gesture. 1793 // The framework may have dropped the up or cancel event for the previous gesture 1794 // due to an app switch, ANR, or some other state change. 1795 cancelAndClearTouchTargets(ev); 1796 resetTouchState(); 1797 } 1798 1799 // Check for interception. 1800 final boolean intercepted; 1801 if (actionMasked == MotionEvent.ACTION_DOWN 1802 || mFirstTouchTarget != null) { 1803 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; 1804 if (!disallowIntercept) { 1805 intercepted = onInterceptTouchEvent(ev); 1806 ev.setAction(action); // restore action in case it was changed 1807 } else { 1808 intercepted = false; 1809 } 1810 } else { 1811 // There are no touch targets and this action is not an initial down 1812 // so this view group continues to intercept touches. 1813 intercepted = true; 1814 } 1815 1816 // Check for cancelation. 1817 final boolean canceled = resetCancelNextUpFlag(this) 1818 || actionMasked == MotionEvent.ACTION_CANCEL; 1819 1820 // Update list of touch targets for pointer down, if needed. 1821 final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0; 1822 TouchTarget newTouchTarget = null; 1823 boolean alreadyDispatchedToNewTouchTarget = false; 1824 if (!canceled && !intercepted) { 1825 if (actionMasked == MotionEvent.ACTION_DOWN 1826 || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) 1827 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { 1828 final int actionIndex = ev.getActionIndex(); // always 0 for down 1829 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) 1830 : TouchTarget.ALL_POINTER_IDS; 1831 1832 // Clean up earlier touch targets for this pointer id in case they 1833 // have become out of sync. 1834 removePointersFromTouchTargets(idBitsToAssign); 1835 1836 final int childrenCount = mChildrenCount; 1837 if (childrenCount != 0) { 1838 // Find a child that can receive the event. 1839 // Scan children from front to back. 1840 final View[] children = mChildren; 1841 final float x = ev.getX(actionIndex); 1842 final float y = ev.getY(actionIndex); 1843 1844 for (int i = childrenCount - 1; i >= 0; i--) { 1845 final View child = children[i]; 1846 if (!canViewReceivePointerEvents(child) 1847 || !isTransformedTouchPointInView(x, y, child, null)) { 1848 continue; 1849 } 1850 1851 newTouchTarget = getTouchTarget(child); 1852 if (newTouchTarget != null) { 1853 // Child is already receiving touch within its bounds. 1854 // Give it the new pointer in addition to the ones it is handling. 1855 newTouchTarget.pointerIdBits |= idBitsToAssign; 1856 break; 1857 } 1858 1859 resetCancelNextUpFlag(child); 1860 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { 1861 // Child wants to receive touch within its bounds. 1862 mLastTouchDownTime = ev.getDownTime(); 1863 mLastTouchDownIndex = i; 1864 mLastTouchDownX = ev.getX(); 1865 mLastTouchDownY = ev.getY(); 1866 newTouchTarget = addTouchTarget(child, idBitsToAssign); 1867 alreadyDispatchedToNewTouchTarget = true; 1868 break; 1869 } 1870 } 1871 } 1872 1873 if (newTouchTarget == null && mFirstTouchTarget != null) { 1874 // Did not find a child to receive the event. 1875 // Assign the pointer to the least recently added target. 1876 newTouchTarget = mFirstTouchTarget; 1877 while (newTouchTarget.next != null) { 1878 newTouchTarget = newTouchTarget.next; 1879 } 1880 newTouchTarget.pointerIdBits |= idBitsToAssign; 1881 } 1882 } 1883 } 1884 1885 // Dispatch to touch targets. 1886 if (mFirstTouchTarget == null) { 1887 // No touch targets so treat this as an ordinary view. 1888 handled = dispatchTransformedTouchEvent(ev, canceled, null, 1889 TouchTarget.ALL_POINTER_IDS); 1890 } else { 1891 // Dispatch to touch targets, excluding the new touch target if we already 1892 // dispatched to it. Cancel touch targets if necessary. 1893 TouchTarget predecessor = null; 1894 TouchTarget target = mFirstTouchTarget; 1895 while (target != null) { 1896 final TouchTarget next = target.next; 1897 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { 1898 handled = true; 1899 } else { 1900 final boolean cancelChild = resetCancelNextUpFlag(target.child) 1901 || intercepted; 1902 if (dispatchTransformedTouchEvent(ev, cancelChild, 1903 target.child, target.pointerIdBits)) { 1904 handled = true; 1905 } 1906 if (cancelChild) { 1907 if (predecessor == null) { 1908 mFirstTouchTarget = next; 1909 } else { 1910 predecessor.next = next; 1911 } 1912 target.recycle(); 1913 target = next; 1914 continue; 1915 } 1916 } 1917 predecessor = target; 1918 target = next; 1919 } 1920 } 1921 1922 // Update list of touch targets for pointer up or cancel, if needed. 1923 if (canceled 1924 || actionMasked == MotionEvent.ACTION_UP 1925 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { 1926 resetTouchState(); 1927 } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) { 1928 final int actionIndex = ev.getActionIndex(); 1929 final int idBitsToRemove = 1 << ev.getPointerId(actionIndex); 1930 removePointersFromTouchTargets(idBitsToRemove); 1931 } 1932 } 1933 1934 if (!handled && mInputEventConsistencyVerifier != null) { 1935 mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1); 1936 } 1937 return handled; 1938 } 1939 1940 /** 1941 * Resets all touch state in preparation for a new cycle. 1942 */ 1943 private void resetTouchState() { 1944 clearTouchTargets(); 1945 resetCancelNextUpFlag(this); 1946 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 1947 } 1948 1949 /** 1950 * Resets the cancel next up flag. 1951 * Returns true if the flag was previously set. 1952 */ 1953 private static boolean resetCancelNextUpFlag(View view) { 1954 if ((view.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) { 1955 view.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 1956 return true; 1957 } 1958 return false; 1959 } 1960 1961 /** 1962 * Clears all touch targets. 1963 */ 1964 private void clearTouchTargets() { 1965 TouchTarget target = mFirstTouchTarget; 1966 if (target != null) { 1967 do { 1968 TouchTarget next = target.next; 1969 target.recycle(); 1970 target = next; 1971 } while (target != null); 1972 mFirstTouchTarget = null; 1973 } 1974 } 1975 1976 /** 1977 * Cancels and clears all touch targets. 1978 */ 1979 private void cancelAndClearTouchTargets(MotionEvent event) { 1980 if (mFirstTouchTarget != null) { 1981 boolean syntheticEvent = false; 1982 if (event == null) { 1983 final long now = SystemClock.uptimeMillis(); 1984 event = MotionEvent.obtain(now, now, 1985 MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); 1986 event.setSource(InputDevice.SOURCE_TOUCHSCREEN); 1987 syntheticEvent = true; 1988 } 1989 1990 for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) { 1991 resetCancelNextUpFlag(target.child); 1992 dispatchTransformedTouchEvent(event, true, target.child, target.pointerIdBits); 1993 } 1994 clearTouchTargets(); 1995 1996 if (syntheticEvent) { 1997 event.recycle(); 1998 } 1999 } 2000 } 2001 2002 /** 2003 * Gets the touch target for specified child view. 2004 * Returns null if not found. 2005 */ 2006 private TouchTarget getTouchTarget(View child) { 2007 for (TouchTarget target = mFirstTouchTarget; target != null; target = target.next) { 2008 if (target.child == child) { 2009 return target; 2010 } 2011 } 2012 return null; 2013 } 2014 2015 /** 2016 * Adds a touch target for specified child to the beginning of the list. 2017 * Assumes the target child is not already present. 2018 */ 2019 private TouchTarget addTouchTarget(View child, int pointerIdBits) { 2020 TouchTarget target = TouchTarget.obtain(child, pointerIdBits); 2021 target.next = mFirstTouchTarget; 2022 mFirstTouchTarget = target; 2023 return target; 2024 } 2025 2026 /** 2027 * Removes the pointer ids from consideration. 2028 */ 2029 private void removePointersFromTouchTargets(int pointerIdBits) { 2030 TouchTarget predecessor = null; 2031 TouchTarget target = mFirstTouchTarget; 2032 while (target != null) { 2033 final TouchTarget next = target.next; 2034 if ((target.pointerIdBits & pointerIdBits) != 0) { 2035 target.pointerIdBits &= ~pointerIdBits; 2036 if (target.pointerIdBits == 0) { 2037 if (predecessor == null) { 2038 mFirstTouchTarget = next; 2039 } else { 2040 predecessor.next = next; 2041 } 2042 target.recycle(); 2043 target = next; 2044 continue; 2045 } 2046 } 2047 predecessor = target; 2048 target = next; 2049 } 2050 } 2051 2052 private void cancelTouchTarget(View view) { 2053 TouchTarget predecessor = null; 2054 TouchTarget target = mFirstTouchTarget; 2055 while (target != null) { 2056 final TouchTarget next = target.next; 2057 if (target.child == view) { 2058 if (predecessor == null) { 2059 mFirstTouchTarget = next; 2060 } else { 2061 predecessor.next = next; 2062 } 2063 target.recycle(); 2064 2065 final long now = SystemClock.uptimeMillis(); 2066 MotionEvent event = MotionEvent.obtain(now, now, 2067 MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); 2068 event.setSource(InputDevice.SOURCE_TOUCHSCREEN); 2069 view.dispatchTouchEvent(event); 2070 event.recycle(); 2071 return; 2072 } 2073 predecessor = target; 2074 target = next; 2075 } 2076 } 2077 2078 /** 2079 * Returns true if a child view can receive pointer events. 2080 * @hide 2081 */ 2082 private static boolean canViewReceivePointerEvents(View child) { 2083 return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE 2084 || child.getAnimation() != null; 2085 } 2086 2087 /** 2088 * Returns true if a child view contains the specified point when transformed 2089 * into its coordinate space. 2090 * Child must not be null. 2091 * @hide 2092 */ 2093 protected boolean isTransformedTouchPointInView(float x, float y, View child, 2094 PointF outLocalPoint) { 2095 float localX = x + mScrollX - child.mLeft; 2096 float localY = y + mScrollY - child.mTop; 2097 if (! child.hasIdentityMatrix() && mAttachInfo != null) { 2098 final float[] localXY = mAttachInfo.mTmpTransformLocation; 2099 localXY[0] = localX; 2100 localXY[1] = localY; 2101 child.getInverseMatrix().mapPoints(localXY); 2102 localX = localXY[0]; 2103 localY = localXY[1]; 2104 } 2105 final boolean isInView = child.pointInView(localX, localY); 2106 if (isInView && outLocalPoint != null) { 2107 outLocalPoint.set(localX, localY); 2108 } 2109 return isInView; 2110 } 2111 2112 /** 2113 * Transforms a motion event into the coordinate space of a particular child view, 2114 * filters out irrelevant pointer ids, and overrides its action if necessary. 2115 * If child is null, assumes the MotionEvent will be sent to this ViewGroup instead. 2116 */ 2117 private boolean dispatchTransformedTouchEvent(MotionEvent event, boolean cancel, 2118 View child, int desiredPointerIdBits) { 2119 final boolean handled; 2120 2121 // Canceling motions is a special case. We don't need to perform any transformations 2122 // or filtering. The important part is the action, not the contents. 2123 final int oldAction = event.getAction(); 2124 if (cancel || oldAction == MotionEvent.ACTION_CANCEL) { 2125 event.setAction(MotionEvent.ACTION_CANCEL); 2126 if (child == null) { 2127 handled = super.dispatchTouchEvent(event); 2128 } else { 2129 handled = child.dispatchTouchEvent(event); 2130 } 2131 event.setAction(oldAction); 2132 return handled; 2133 } 2134 2135 // Calculate the number of pointers to deliver. 2136 final int oldPointerIdBits = event.getPointerIdBits(); 2137 final int newPointerIdBits = oldPointerIdBits & desiredPointerIdBits; 2138 2139 // If for some reason we ended up in an inconsistent state where it looks like we 2140 // might produce a motion event with no pointers in it, then drop the event. 2141 if (newPointerIdBits == 0) { 2142 return false; 2143 } 2144 2145 // If the number of pointers is the same and we don't need to perform any fancy 2146 // irreversible transformations, then we can reuse the motion event for this 2147 // dispatch as long as we are careful to revert any changes we make. 2148 // Otherwise we need to make a copy. 2149 final MotionEvent transformedEvent; 2150 if (newPointerIdBits == oldPointerIdBits) { 2151 if (child == null || child.hasIdentityMatrix()) { 2152 if (child == null) { 2153 handled = super.dispatchTouchEvent(event); 2154 } else { 2155 final float offsetX = mScrollX - child.mLeft; 2156 final float offsetY = mScrollY - child.mTop; 2157 event.offsetLocation(offsetX, offsetY); 2158 2159 handled = child.dispatchTouchEvent(event); 2160 2161 event.offsetLocation(-offsetX, -offsetY); 2162 } 2163 return handled; 2164 } 2165 transformedEvent = MotionEvent.obtain(event); 2166 } else { 2167 transformedEvent = event.split(newPointerIdBits); 2168 } 2169 2170 // Perform any necessary transformations and dispatch. 2171 if (child == null) { 2172 handled = super.dispatchTouchEvent(transformedEvent); 2173 } else { 2174 final float offsetX = mScrollX - child.mLeft; 2175 final float offsetY = mScrollY - child.mTop; 2176 transformedEvent.offsetLocation(offsetX, offsetY); 2177 if (! child.hasIdentityMatrix()) { 2178 transformedEvent.transform(child.getInverseMatrix()); 2179 } 2180 2181 handled = child.dispatchTouchEvent(transformedEvent); 2182 } 2183 2184 // Done. 2185 transformedEvent.recycle(); 2186 return handled; 2187 } 2188 2189 /** 2190 * Enable or disable the splitting of MotionEvents to multiple children during touch event 2191 * dispatch. This behavior is enabled by default for applications that target an 2192 * SDK version of {@link Build.VERSION_CODES#HONEYCOMB} or newer. 2193 * 2194 * <p>When this option is enabled MotionEvents may be split and dispatched to different child 2195 * views depending on where each pointer initially went down. This allows for user interactions 2196 * such as scrolling two panes of content independently, chording of buttons, and performing 2197 * independent gestures on different pieces of content. 2198 * 2199 * @param split <code>true</code> to allow MotionEvents to be split and dispatched to multiple 2200 * child views. <code>false</code> to only allow one child view to be the target of 2201 * any MotionEvent received by this ViewGroup. 2202 */ 2203 public void setMotionEventSplittingEnabled(boolean split) { 2204 // TODO Applications really shouldn't change this setting mid-touch event, 2205 // but perhaps this should handle that case and send ACTION_CANCELs to any child views 2206 // with gestures in progress when this is changed. 2207 if (split) { 2208 mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS; 2209 } else { 2210 mGroupFlags &= ~FLAG_SPLIT_MOTION_EVENTS; 2211 } 2212 } 2213 2214 /** 2215 * Returns true if MotionEvents dispatched to this ViewGroup can be split to multiple children. 2216 * @return true if MotionEvents dispatched to this ViewGroup can be split to multiple children. 2217 */ 2218 public boolean isMotionEventSplittingEnabled() { 2219 return (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) == FLAG_SPLIT_MOTION_EVENTS; 2220 } 2221 2222 /** 2223 * {@inheritDoc} 2224 */ 2225 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 2226 2227 if (disallowIntercept == ((mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0)) { 2228 // We're already in this state, assume our ancestors are too 2229 return; 2230 } 2231 2232 if (disallowIntercept) { 2233 mGroupFlags |= FLAG_DISALLOW_INTERCEPT; 2234 } else { 2235 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 2236 } 2237 2238 // Pass it up to our parent 2239 if (mParent != null) { 2240 mParent.requestDisallowInterceptTouchEvent(disallowIntercept); 2241 } 2242 } 2243 2244 /** 2245 * Implement this method to intercept all touch screen motion events. This 2246 * allows you to watch events as they are dispatched to your children, and 2247 * take ownership of the current gesture at any point. 2248 * 2249 * <p>Using this function takes some care, as it has a fairly complicated 2250 * interaction with {@link View#onTouchEvent(MotionEvent) 2251 * View.onTouchEvent(MotionEvent)}, and using it requires implementing 2252 * that method as well as this one in the correct way. Events will be 2253 * received in the following order: 2254 * 2255 * <ol> 2256 * <li> You will receive the down event here. 2257 * <li> The down event will be handled either by a child of this view 2258 * group, or given to your own onTouchEvent() method to handle; this means 2259 * you should implement onTouchEvent() to return true, so you will 2260 * continue to see the rest of the gesture (instead of looking for 2261 * a parent view to handle it). Also, by returning true from 2262 * onTouchEvent(), you will not receive any following 2263 * events in onInterceptTouchEvent() and all touch processing must 2264 * happen in onTouchEvent() like normal. 2265 * <li> For as long as you return false from this function, each following 2266 * event (up to and including the final up) will be delivered first here 2267 * and then to the target's onTouchEvent(). 2268 * <li> If you return true from here, you will not receive any 2269 * following events: the target view will receive the same event but 2270 * with the action {@link MotionEvent#ACTION_CANCEL}, and all further 2271 * events will be delivered to your onTouchEvent() method and no longer 2272 * appear here. 2273 * </ol> 2274 * 2275 * @param ev The motion event being dispatched down the hierarchy. 2276 * @return Return true to steal motion events from the children and have 2277 * them dispatched to this ViewGroup through onTouchEvent(). 2278 * The current target will receive an ACTION_CANCEL event, and no further 2279 * messages will be delivered here. 2280 */ 2281 public boolean onInterceptTouchEvent(MotionEvent ev) { 2282 return false; 2283 } 2284 2285 /** 2286 * {@inheritDoc} 2287 * 2288 * Looks for a view to give focus to respecting the setting specified by 2289 * {@link #getDescendantFocusability()}. 2290 * 2291 * Uses {@link #onRequestFocusInDescendants(int, android.graphics.Rect)} to 2292 * find focus within the children of this group when appropriate. 2293 * 2294 * @see #FOCUS_BEFORE_DESCENDANTS 2295 * @see #FOCUS_AFTER_DESCENDANTS 2296 * @see #FOCUS_BLOCK_DESCENDANTS 2297 * @see #onRequestFocusInDescendants(int, android.graphics.Rect) 2298 */ 2299 @Override 2300 public boolean requestFocus(int direction, Rect previouslyFocusedRect) { 2301 if (DBG) { 2302 System.out.println(this + " ViewGroup.requestFocus direction=" 2303 + direction); 2304 } 2305 int descendantFocusability = getDescendantFocusability(); 2306 2307 switch (descendantFocusability) { 2308 case FOCUS_BLOCK_DESCENDANTS: 2309 return super.requestFocus(direction, previouslyFocusedRect); 2310 case FOCUS_BEFORE_DESCENDANTS: { 2311 final boolean took = super.requestFocus(direction, previouslyFocusedRect); 2312 return took ? took : onRequestFocusInDescendants(direction, previouslyFocusedRect); 2313 } 2314 case FOCUS_AFTER_DESCENDANTS: { 2315 final boolean took = onRequestFocusInDescendants(direction, previouslyFocusedRect); 2316 return took ? took : super.requestFocus(direction, previouslyFocusedRect); 2317 } 2318 default: 2319 throw new IllegalStateException("descendant focusability must be " 2320 + "one of FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS " 2321 + "but is " + descendantFocusability); 2322 } 2323 } 2324 2325 /** 2326 * Look for a descendant to call {@link View#requestFocus} on. 2327 * Called by {@link ViewGroup#requestFocus(int, android.graphics.Rect)} 2328 * when it wants to request focus within its children. Override this to 2329 * customize how your {@link ViewGroup} requests focus within its children. 2330 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and FOCUS_RIGHT 2331 * @param previouslyFocusedRect The rectangle (in this View's coordinate system) 2332 * to give a finer grained hint about where focus is coming from. May be null 2333 * if there is no hint. 2334 * @return Whether focus was taken. 2335 */ 2336 @SuppressWarnings({"ConstantConditions"}) 2337 protected boolean onRequestFocusInDescendants(int direction, 2338 Rect previouslyFocusedRect) { 2339 int index; 2340 int increment; 2341 int end; 2342 int count = mChildrenCount; 2343 if ((direction & FOCUS_FORWARD) != 0) { 2344 index = 0; 2345 increment = 1; 2346 end = count; 2347 } else { 2348 index = count - 1; 2349 increment = -1; 2350 end = -1; 2351 } 2352 final View[] children = mChildren; 2353 for (int i = index; i != end; i += increment) { 2354 View child = children[i]; 2355 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 2356 if (child.requestFocus(direction, previouslyFocusedRect)) { 2357 return true; 2358 } 2359 } 2360 } 2361 return false; 2362 } 2363 2364 /** 2365 * {@inheritDoc} 2366 * 2367 * @hide 2368 */ 2369 @Override 2370 public void dispatchStartTemporaryDetach() { 2371 super.dispatchStartTemporaryDetach(); 2372 final int count = mChildrenCount; 2373 final View[] children = mChildren; 2374 for (int i = 0; i < count; i++) { 2375 children[i].dispatchStartTemporaryDetach(); 2376 } 2377 } 2378 2379 /** 2380 * {@inheritDoc} 2381 * 2382 * @hide 2383 */ 2384 @Override 2385 public void dispatchFinishTemporaryDetach() { 2386 super.dispatchFinishTemporaryDetach(); 2387 final int count = mChildrenCount; 2388 final View[] children = mChildren; 2389 for (int i = 0; i < count; i++) { 2390 children[i].dispatchFinishTemporaryDetach(); 2391 } 2392 } 2393 2394 /** 2395 * {@inheritDoc} 2396 */ 2397 @Override 2398 void dispatchAttachedToWindow(AttachInfo info, int visibility) { 2399 mGroupFlags |= FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW; 2400 super.dispatchAttachedToWindow(info, visibility); 2401 mGroupFlags &= ~FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW; 2402 2403 final int count = mChildrenCount; 2404 final View[] children = mChildren; 2405 for (int i = 0; i < count; i++) { 2406 final View child = children[i]; 2407 child.dispatchAttachedToWindow(info, 2408 visibility | (child.mViewFlags&VISIBILITY_MASK)); 2409 } 2410 } 2411 2412 @Override 2413 void dispatchScreenStateChanged(int screenState) { 2414 super.dispatchScreenStateChanged(screenState); 2415 2416 final int count = mChildrenCount; 2417 final View[] children = mChildren; 2418 for (int i = 0; i < count; i++) { 2419 children[i].dispatchScreenStateChanged(screenState); 2420 } 2421 } 2422 2423 @Override 2424 boolean dispatchPopulateAccessibilityEventInternal(AccessibilityEvent event) { 2425 boolean handled = false; 2426 if (includeForAccessibility()) { 2427 handled = super.dispatchPopulateAccessibilityEventInternal(event); 2428 if (handled) { 2429 return handled; 2430 } 2431 } 2432 // Let our children have a shot in populating the event. 2433 ChildListForAccessibility children = ChildListForAccessibility.obtain(this, true); 2434 try { 2435 final int childCount = children.getChildCount(); 2436 for (int i = 0; i < childCount; i++) { 2437 View child = children.getChildAt(i); 2438 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 2439 handled = child.dispatchPopulateAccessibilityEvent(event); 2440 if (handled) { 2441 return handled; 2442 } 2443 } 2444 } 2445 } finally { 2446 children.recycle(); 2447 } 2448 return false; 2449 } 2450 2451 @Override 2452 void onInitializeAccessibilityNodeInfoInternal(AccessibilityNodeInfo info) { 2453 super.onInitializeAccessibilityNodeInfoInternal(info); 2454 if (mAttachInfo != null) { 2455 ArrayList<View> childrenForAccessibility = mAttachInfo.mTempArrayList; 2456 childrenForAccessibility.clear(); 2457 addChildrenForAccessibility(childrenForAccessibility); 2458 final int childrenForAccessibilityCount = childrenForAccessibility.size(); 2459 for (int i = 0; i < childrenForAccessibilityCount; i++) { 2460 View child = childrenForAccessibility.get(i); 2461 info.addChild(child); 2462 } 2463 childrenForAccessibility.clear(); 2464 } 2465 } 2466 2467 @Override 2468 void onInitializeAccessibilityEventInternal(AccessibilityEvent event) { 2469 super.onInitializeAccessibilityEventInternal(event); 2470 event.setClassName(ViewGroup.class.getName()); 2471 } 2472 2473 /** 2474 * @hide 2475 */ 2476 @Override 2477 public void resetAccessibilityStateChanged() { 2478 super.resetAccessibilityStateChanged(); 2479 View[] children = mChildren; 2480 final int childCount = mChildrenCount; 2481 for (int i = 0; i < childCount; i++) { 2482 View child = children[i]; 2483 child.resetAccessibilityStateChanged(); 2484 } 2485 } 2486 2487 /** 2488 * {@inheritDoc} 2489 */ 2490 @Override 2491 void dispatchDetachedFromWindow() { 2492 // If we still have a touch target, we are still in the process of 2493 // dispatching motion events to a child; we need to get rid of that 2494 // child to avoid dispatching events to it after the window is torn 2495 // down. To make sure we keep the child in a consistent state, we 2496 // first send it an ACTION_CANCEL motion event. 2497 cancelAndClearTouchTargets(null); 2498 2499 // Similarly, set ACTION_EXIT to all hover targets and clear them. 2500 exitHoverTargets(); 2501 2502 // In case view is detached while transition is running 2503 mLayoutSuppressed = false; 2504 2505 // Tear down our drag tracking 2506 mDragNotifiedChildren = null; 2507 if (mCurrentDrag != null) { 2508 mCurrentDrag.recycle(); 2509 mCurrentDrag = null; 2510 } 2511 2512 final int count = mChildrenCount; 2513 final View[] children = mChildren; 2514 for (int i = 0; i < count; i++) { 2515 children[i].dispatchDetachedFromWindow(); 2516 } 2517 super.dispatchDetachedFromWindow(); 2518 } 2519 2520 /** 2521 * {@inheritDoc} 2522 */ 2523 @Override 2524 public void setPadding(int left, int top, int right, int bottom) { 2525 super.setPadding(left, top, right, bottom); 2526 2527 if ((mPaddingLeft | mPaddingTop | mPaddingRight | mPaddingBottom) != 0) { 2528 mGroupFlags |= FLAG_PADDING_NOT_NULL; 2529 } else { 2530 mGroupFlags &= ~FLAG_PADDING_NOT_NULL; 2531 } 2532 } 2533 2534 /** 2535 * {@inheritDoc} 2536 */ 2537 @Override 2538 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 2539 super.dispatchSaveInstanceState(container); 2540 final int count = mChildrenCount; 2541 final View[] children = mChildren; 2542 for (int i = 0; i < count; i++) { 2543 View c = children[i]; 2544 if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) { 2545 c.dispatchSaveInstanceState(container); 2546 } 2547 } 2548 } 2549 2550 /** 2551 * Perform dispatching of a {@link #saveHierarchyState(android.util.SparseArray)} freeze()} 2552 * to only this view, not to its children. For use when overriding 2553 * {@link #dispatchSaveInstanceState(android.util.SparseArray)} dispatchFreeze()} to allow 2554 * subclasses to freeze their own state but not the state of their children. 2555 * 2556 * @param container the container 2557 */ 2558 protected void dispatchFreezeSelfOnly(SparseArray<Parcelable> container) { 2559 super.dispatchSaveInstanceState(container); 2560 } 2561 2562 /** 2563 * {@inheritDoc} 2564 */ 2565 @Override 2566 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 2567 super.dispatchRestoreInstanceState(container); 2568 final int count = mChildrenCount; 2569 final View[] children = mChildren; 2570 for (int i = 0; i < count; i++) { 2571 View c = children[i]; 2572 if ((c.mViewFlags & PARENT_SAVE_DISABLED_MASK) != PARENT_SAVE_DISABLED) { 2573 c.dispatchRestoreInstanceState(container); 2574 } 2575 } 2576 } 2577 2578 /** 2579 * Perform dispatching of a {@link #restoreHierarchyState(android.util.SparseArray)} 2580 * to only this view, not to its children. For use when overriding 2581 * {@link #dispatchRestoreInstanceState(android.util.SparseArray)} to allow 2582 * subclasses to thaw their own state but not the state of their children. 2583 * 2584 * @param container the container 2585 */ 2586 protected void dispatchThawSelfOnly(SparseArray<Parcelable> container) { 2587 super.dispatchRestoreInstanceState(container); 2588 } 2589 2590 /** 2591 * Enables or disables the drawing cache for each child of this view group. 2592 * 2593 * @param enabled true to enable the cache, false to dispose of it 2594 */ 2595 protected void setChildrenDrawingCacheEnabled(boolean enabled) { 2596 if (enabled || (mPersistentDrawingCache & PERSISTENT_ALL_CACHES) != PERSISTENT_ALL_CACHES) { 2597 final View[] children = mChildren; 2598 final int count = mChildrenCount; 2599 for (int i = 0; i < count; i++) { 2600 children[i].setDrawingCacheEnabled(enabled); 2601 } 2602 } 2603 } 2604 2605 @Override 2606 protected void onAnimationStart() { 2607 super.onAnimationStart(); 2608 2609 // When this ViewGroup's animation starts, build the cache for the children 2610 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) { 2611 final int count = mChildrenCount; 2612 final View[] children = mChildren; 2613 final boolean buildCache = !isHardwareAccelerated(); 2614 2615 for (int i = 0; i < count; i++) { 2616 final View child = children[i]; 2617 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 2618 child.setDrawingCacheEnabled(true); 2619 if (buildCache) { 2620 child.buildDrawingCache(true); 2621 } 2622 } 2623 } 2624 2625 mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE; 2626 } 2627 } 2628 2629 @Override 2630 protected void onAnimationEnd() { 2631 super.onAnimationEnd(); 2632 2633 // When this ViewGroup's animation ends, destroy the cache of the children 2634 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) { 2635 mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE; 2636 2637 if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) { 2638 setChildrenDrawingCacheEnabled(false); 2639 } 2640 } 2641 } 2642 2643 @Override 2644 Bitmap createSnapshot(Bitmap.Config quality, int backgroundColor, boolean skipChildren) { 2645 int count = mChildrenCount; 2646 int[] visibilities = null; 2647 2648 if (skipChildren) { 2649 visibilities = new int[count]; 2650 for (int i = 0; i < count; i++) { 2651 View child = getChildAt(i); 2652 visibilities[i] = child.getVisibility(); 2653 if (visibilities[i] == View.VISIBLE) { 2654 child.setVisibility(INVISIBLE); 2655 } 2656 } 2657 } 2658 2659 Bitmap b = super.createSnapshot(quality, backgroundColor, skipChildren); 2660 2661 if (skipChildren) { 2662 for (int i = 0; i < count; i++) { 2663 getChildAt(i).setVisibility(visibilities[i]); 2664 } 2665 } 2666 2667 return b; 2668 } 2669 2670 private static void drawRect(Canvas canvas, int x1, int y1, int x2, int y2, int color) { 2671 Paint paint = getDebugPaint(); 2672 paint.setColor(color); 2673 2674 canvas.drawLines(getDebugLines(x1, y1, x2, y2), paint); 2675 } 2676 2677 /** 2678 * @hide 2679 */ 2680 protected void onDebugDrawMargins(Canvas canvas) { 2681 for (int i = 0; i < getChildCount(); i++) { 2682 View c = getChildAt(i); 2683 c.getLayoutParams().onDebugDraw(c, canvas); 2684 } 2685 } 2686 2687 /** 2688 * @hide 2689 */ 2690 protected void onDebugDraw(Canvas canvas) { 2691 // Draw optical bounds 2692 if (getLayoutMode() == OPTICAL_BOUNDS) { 2693 for (int i = 0; i < getChildCount(); i++) { 2694 View c = getChildAt(i); 2695 Insets insets = c.getOpticalInsets(); 2696 drawRect(canvas, 2697 c.getLeft() + insets.left, 2698 c.getTop() + insets.top, 2699 c.getRight() - insets.right, 2700 c.getBottom() - insets.bottom, Color.RED); 2701 } 2702 } 2703 2704 // Draw margins 2705 onDebugDrawMargins(canvas); 2706 2707 // Draw bounds 2708 for (int i = 0; i < getChildCount(); i++) { 2709 View c = getChildAt(i); 2710 drawRect(canvas, c.getLeft(), c.getTop(), c.getRight(), c.getBottom(), Color.BLUE); 2711 } 2712 } 2713 2714 /** 2715 * {@inheritDoc} 2716 */ 2717 @Override 2718 protected void dispatchDraw(Canvas canvas) { 2719 final int count = mChildrenCount; 2720 final View[] children = mChildren; 2721 int flags = mGroupFlags; 2722 2723 if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) { 2724 final boolean cache = (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE; 2725 2726 final boolean buildCache = !isHardwareAccelerated(); 2727 for (int i = 0; i < count; i++) { 2728 final View child = children[i]; 2729 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 2730 final LayoutParams params = child.getLayoutParams(); 2731 attachLayoutAnimationParameters(child, params, i, count); 2732 bindLayoutAnimation(child); 2733 if (cache) { 2734 child.setDrawingCacheEnabled(true); 2735 if (buildCache) { 2736 child.buildDrawingCache(true); 2737 } 2738 } 2739 } 2740 } 2741 2742 final LayoutAnimationController controller = mLayoutAnimationController; 2743 if (controller.willOverlap()) { 2744 mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE; 2745 } 2746 2747 controller.start(); 2748 2749 mGroupFlags &= ~FLAG_RUN_ANIMATION; 2750 mGroupFlags &= ~FLAG_ANIMATION_DONE; 2751 2752 if (cache) { 2753 mGroupFlags |= FLAG_CHILDREN_DRAWN_WITH_CACHE; 2754 } 2755 2756 if (mAnimationListener != null) { 2757 mAnimationListener.onAnimationStart(controller.getAnimation()); 2758 } 2759 } 2760 2761 int saveCount = 0; 2762 final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK; 2763 if (clipToPadding) { 2764 saveCount = canvas.save(); 2765 canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop, 2766 mScrollX + mRight - mLeft - mPaddingRight, 2767 mScrollY + mBottom - mTop - mPaddingBottom); 2768 2769 } 2770 2771 // We will draw our child's animation, let's reset the flag 2772 mPrivateFlags &= ~DRAW_ANIMATION; 2773 mGroupFlags &= ~FLAG_INVALIDATE_REQUIRED; 2774 2775 boolean more = false; 2776 final long drawingTime = getDrawingTime(); 2777 2778 if ((flags & FLAG_USE_CHILD_DRAWING_ORDER) == 0) { 2779 for (int i = 0; i < count; i++) { 2780 final View child = children[i]; 2781 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 2782 more |= drawChild(canvas, child, drawingTime); 2783 } 2784 } 2785 } else { 2786 for (int i = 0; i < count; i++) { 2787 final View child = children[getChildDrawingOrder(count, i)]; 2788 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 2789 more |= drawChild(canvas, child, drawingTime); 2790 } 2791 } 2792 } 2793 2794 // Draw any disappearing views that have animations 2795 if (mDisappearingChildren != null) { 2796 final ArrayList<View> disappearingChildren = mDisappearingChildren; 2797 final int disappearingCount = disappearingChildren.size() - 1; 2798 // Go backwards -- we may delete as animations finish 2799 for (int i = disappearingCount; i >= 0; i--) { 2800 final View child = disappearingChildren.get(i); 2801 more |= drawChild(canvas, child, drawingTime); 2802 } 2803 } 2804 2805 if (debugDraw()) { 2806 onDebugDraw(canvas); 2807 } 2808 2809 if (clipToPadding) { 2810 canvas.restoreToCount(saveCount); 2811 } 2812 2813 // mGroupFlags might have been updated by drawChild() 2814 flags = mGroupFlags; 2815 2816 if ((flags & FLAG_INVALIDATE_REQUIRED) == FLAG_INVALIDATE_REQUIRED) { 2817 invalidate(true); 2818 } 2819 2820 if ((flags & FLAG_ANIMATION_DONE) == 0 && (flags & FLAG_NOTIFY_ANIMATION_LISTENER) == 0 && 2821 mLayoutAnimationController.isDone() && !more) { 2822 // We want to erase the drawing cache and notify the listener after the 2823 // next frame is drawn because one extra invalidate() is caused by 2824 // drawChild() after the animation is over 2825 mGroupFlags |= FLAG_NOTIFY_ANIMATION_LISTENER; 2826 final Runnable end = new Runnable() { 2827 public void run() { 2828 notifyAnimationListener(); 2829 } 2830 }; 2831 post(end); 2832 } 2833 } 2834 2835 /** 2836 * Returns the index of the child to draw for this iteration. Override this 2837 * if you want to change the drawing order of children. By default, it 2838 * returns i. 2839 * <p> 2840 * NOTE: In order for this method to be called, you must enable child ordering 2841 * first by calling {@link #setChildrenDrawingOrderEnabled(boolean)}. 2842 * 2843 * @param i The current iteration. 2844 * @return The index of the child to draw this iteration. 2845 * 2846 * @see #setChildrenDrawingOrderEnabled(boolean) 2847 * @see #isChildrenDrawingOrderEnabled() 2848 */ 2849 protected int getChildDrawingOrder(int childCount, int i) { 2850 return i; 2851 } 2852 2853 private void notifyAnimationListener() { 2854 mGroupFlags &= ~FLAG_NOTIFY_ANIMATION_LISTENER; 2855 mGroupFlags |= FLAG_ANIMATION_DONE; 2856 2857 if (mAnimationListener != null) { 2858 final Runnable end = new Runnable() { 2859 public void run() { 2860 mAnimationListener.onAnimationEnd(mLayoutAnimationController.getAnimation()); 2861 } 2862 }; 2863 post(end); 2864 } 2865 2866 if ((mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE) { 2867 mGroupFlags &= ~FLAG_CHILDREN_DRAWN_WITH_CACHE; 2868 if ((mPersistentDrawingCache & PERSISTENT_ANIMATION_CACHE) == 0) { 2869 setChildrenDrawingCacheEnabled(false); 2870 } 2871 } 2872 2873 invalidate(true); 2874 } 2875 2876 /** 2877 * This method is used to cause children of this ViewGroup to restore or recreate their 2878 * display lists. It is called by getDisplayList() when the parent ViewGroup does not need 2879 * to recreate its own display list, which would happen if it went through the normal 2880 * draw/dispatchDraw mechanisms. 2881 * 2882 * @hide 2883 */ 2884 @Override 2885 protected void dispatchGetDisplayList() { 2886 final int count = mChildrenCount; 2887 final View[] children = mChildren; 2888 for (int i = 0; i < count; i++) { 2889 final View child = children[i]; 2890 if (((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) && 2891 child.hasStaticLayer()) { 2892 child.mRecreateDisplayList = (child.mPrivateFlags & INVALIDATED) == INVALIDATED; 2893 child.mPrivateFlags &= ~INVALIDATED; 2894 child.getDisplayList(); 2895 child.mRecreateDisplayList = false; 2896 } 2897 } 2898 } 2899 2900 /** 2901 * Draw one child of this View Group. This method is responsible for getting 2902 * the canvas in the right state. This includes clipping, translating so 2903 * that the child's scrolled origin is at 0, 0, and applying any animation 2904 * transformations. 2905 * 2906 * @param canvas The canvas on which to draw the child 2907 * @param child Who to draw 2908 * @param drawingTime The time at which draw is occurring 2909 * @return True if an invalidate() was issued 2910 */ 2911 protected boolean drawChild(Canvas canvas, View child, long drawingTime) { 2912 return child.draw(canvas, this, drawingTime); 2913 } 2914 2915 /** 2916 * 2917 * @param enabled True if children should be drawn with layers, false otherwise. 2918 * 2919 * @hide 2920 */ 2921 public void setChildrenLayersEnabled(boolean enabled) { 2922 if (enabled != mDrawLayers) { 2923 mDrawLayers = enabled; 2924 invalidate(true); 2925 2926 boolean flushLayers = !enabled; 2927 AttachInfo info = mAttachInfo; 2928 if (info != null && info.mHardwareRenderer != null && 2929 info.mHardwareRenderer.isEnabled()) { 2930 if (!info.mHardwareRenderer.validate()) { 2931 flushLayers = false; 2932 } 2933 } else { 2934 flushLayers = false; 2935 } 2936 2937 // We need to invalidate any child with a layer. For instance, 2938 // if a child is backed by a hardware layer and we disable layers 2939 // the child is marked as not dirty (flags cleared the last time 2940 // the child was drawn inside its layer.) However, that child might 2941 // never have created its own display list or have an obsolete 2942 // display list. By invalidating the child we ensure the display 2943 // list is in sync with the content of the hardware layer. 2944 for (int i = 0; i < mChildrenCount; i++) { 2945 View child = mChildren[i]; 2946 if (child.mLayerType != LAYER_TYPE_NONE) { 2947 if (flushLayers) child.flushLayer(); 2948 child.invalidate(true); 2949 } 2950 } 2951 } 2952 } 2953 2954 /** 2955 * By default, children are clipped to their bounds before drawing. This 2956 * allows view groups to override this behavior for animations, etc. 2957 * 2958 * @param clipChildren true to clip children to their bounds, 2959 * false otherwise 2960 * @attr ref android.R.styleable#ViewGroup_clipChildren 2961 */ 2962 public void setClipChildren(boolean clipChildren) { 2963 boolean previousValue = (mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN; 2964 if (clipChildren != previousValue) { 2965 setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren); 2966 for (int i = 0; i < mChildrenCount; ++i) { 2967 View child = getChildAt(i); 2968 if (child.mDisplayList != null) { 2969 child.mDisplayList.setClipChildren(clipChildren); 2970 } 2971 } 2972 } 2973 } 2974 2975 /** 2976 * By default, children are clipped to the padding of the ViewGroup. This 2977 * allows view groups to override this behavior 2978 * 2979 * @param clipToPadding true to clip children to the padding of the 2980 * group, false otherwise 2981 * @attr ref android.R.styleable#ViewGroup_clipToPadding 2982 */ 2983 public void setClipToPadding(boolean clipToPadding) { 2984 setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding); 2985 } 2986 2987 /** 2988 * {@inheritDoc} 2989 */ 2990 @Override 2991 public void dispatchSetSelected(boolean selected) { 2992 final View[] children = mChildren; 2993 final int count = mChildrenCount; 2994 for (int i = 0; i < count; i++) { 2995 children[i].setSelected(selected); 2996 } 2997 } 2998 2999 /** 3000 * {@inheritDoc} 3001 */ 3002 @Override 3003 public void dispatchSetActivated(boolean activated) { 3004 final View[] children = mChildren; 3005 final int count = mChildrenCount; 3006 for (int i = 0; i < count; i++) { 3007 children[i].setActivated(activated); 3008 } 3009 } 3010 3011 @Override 3012 protected void dispatchSetPressed(boolean pressed) { 3013 final View[] children = mChildren; 3014 final int count = mChildrenCount; 3015 for (int i = 0; i < count; i++) { 3016 final View child = children[i]; 3017 // Children that are clickable on their own should not 3018 // show a pressed state when their parent view does. 3019 // Clearing a pressed state always propagates. 3020 if (!pressed || (!child.isClickable() && !child.isLongClickable())) { 3021 child.setPressed(pressed); 3022 } 3023 } 3024 } 3025 3026 /** 3027 * When this property is set to true, this ViewGroup supports static transformations on 3028 * children; this causes 3029 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be 3030 * invoked when a child is drawn. 3031 * 3032 * Any subclass overriding 3033 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should 3034 * set this property to true. 3035 * 3036 * @param enabled True to enable static transformations on children, false otherwise. 3037 * 3038 * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS 3039 */ 3040 protected void setStaticTransformationsEnabled(boolean enabled) { 3041 setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled); 3042 } 3043 3044 /** 3045 * Sets <code>t</code> to be the static transformation of the child, if set, returning a 3046 * boolean to indicate whether a static transform was set. The default implementation 3047 * simply returns <code>false</code>; subclasses may override this method for different 3048 * behavior. 3049 * 3050 * @param child The child view whose static transform is being requested 3051 * @param t The Transformation which will hold the result 3052 * @return true if the transformation was set, false otherwise 3053 * @see #setStaticTransformationsEnabled(boolean) 3054 */ 3055 protected boolean getChildStaticTransformation(View child, Transformation t) { 3056 return false; 3057 } 3058 3059 /** 3060 * {@hide} 3061 */ 3062 @Override 3063 protected View findViewTraversal(int id) { 3064 if (id == mID) { 3065 return this; 3066 } 3067 3068 final View[] where = mChildren; 3069 final int len = mChildrenCount; 3070 3071 for (int i = 0; i < len; i++) { 3072 View v = where[i]; 3073 3074 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 3075 v = v.findViewById(id); 3076 3077 if (v != null) { 3078 return v; 3079 } 3080 } 3081 } 3082 3083 return null; 3084 } 3085 3086 /** 3087 * {@hide} 3088 */ 3089 @Override 3090 protected View findViewWithTagTraversal(Object tag) { 3091 if (tag != null && tag.equals(mTag)) { 3092 return this; 3093 } 3094 3095 final View[] where = mChildren; 3096 final int len = mChildrenCount; 3097 3098 for (int i = 0; i < len; i++) { 3099 View v = where[i]; 3100 3101 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 3102 v = v.findViewWithTag(tag); 3103 3104 if (v != null) { 3105 return v; 3106 } 3107 } 3108 } 3109 3110 return null; 3111 } 3112 3113 /** 3114 * {@hide} 3115 */ 3116 @Override 3117 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 3118 if (predicate.apply(this)) { 3119 return this; 3120 } 3121 3122 final View[] where = mChildren; 3123 final int len = mChildrenCount; 3124 3125 for (int i = 0; i < len; i++) { 3126 View v = where[i]; 3127 3128 if (v != childToSkip && (v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 3129 v = v.findViewByPredicate(predicate); 3130 3131 if (v != null) { 3132 return v; 3133 } 3134 } 3135 } 3136 3137 return null; 3138 } 3139 3140 /** 3141 * Adds a child view. If no layout parameters are already set on the child, the 3142 * default parameters for this ViewGroup are set on the child. 3143 * 3144 * @param child the child view to add 3145 * 3146 * @see #generateDefaultLayoutParams() 3147 */ 3148 public void addView(View child) { 3149 addView(child, -1); 3150 } 3151 3152 /** 3153 * Adds a child view. If no layout parameters are already set on the child, the 3154 * default parameters for this ViewGroup are set on the child. 3155 * 3156 * @param child the child view to add 3157 * @param index the position at which to add the child 3158 * 3159 * @see #generateDefaultLayoutParams() 3160 */ 3161 public void addView(View child, int index) { 3162 LayoutParams params = child.getLayoutParams(); 3163 if (params == null) { 3164 params = generateDefaultLayoutParams(); 3165 if (params == null) { 3166 throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); 3167 } 3168 } 3169 addView(child, index, params); 3170 } 3171 3172 /** 3173 * Adds a child view with this ViewGroup's default layout parameters and the 3174 * specified width and height. 3175 * 3176 * @param child the child view to add 3177 */ 3178 public void addView(View child, int width, int height) { 3179 final LayoutParams params = generateDefaultLayoutParams(); 3180 params.width = width; 3181 params.height = height; 3182 addView(child, -1, params); 3183 } 3184 3185 /** 3186 * Adds a child view with the specified layout parameters. 3187 * 3188 * @param child the child view to add 3189 * @param params the layout parameters to set on the child 3190 */ 3191 public void addView(View child, LayoutParams params) { 3192 addView(child, -1, params); 3193 } 3194 3195 /** 3196 * Adds a child view with the specified layout parameters. 3197 * 3198 * @param child the child view to add 3199 * @param index the position at which to add the child 3200 * @param params the layout parameters to set on the child 3201 */ 3202 public void addView(View child, int index, LayoutParams params) { 3203 if (DBG) { 3204 System.out.println(this + " addView"); 3205 } 3206 3207 // addViewInner() will call child.requestLayout() when setting the new LayoutParams 3208 // therefore, we call requestLayout() on ourselves before, so that the child's request 3209 // will be blocked at our level 3210 requestLayout(); 3211 invalidate(true); 3212 addViewInner(child, index, params, false); 3213 } 3214 3215 /** 3216 * {@inheritDoc} 3217 */ 3218 public void updateViewLayout(View view, ViewGroup.LayoutParams params) { 3219 if (!checkLayoutParams(params)) { 3220 throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this); 3221 } 3222 if (view.mParent != this) { 3223 throw new IllegalArgumentException("Given view not a child of " + this); 3224 } 3225 view.setLayoutParams(params); 3226 } 3227 3228 /** 3229 * {@inheritDoc} 3230 */ 3231 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 3232 return p != null; 3233 } 3234 3235 /** 3236 * Interface definition for a callback to be invoked when the hierarchy 3237 * within this view changed. The hierarchy changes whenever a child is added 3238 * to or removed from this view. 3239 */ 3240 public interface OnHierarchyChangeListener { 3241 /** 3242 * Called when a new child is added to a parent view. 3243 * 3244 * @param parent the view in which a child was added 3245 * @param child the new child view added in the hierarchy 3246 */ 3247 void onChildViewAdded(View parent, View child); 3248 3249 /** 3250 * Called when a child is removed from a parent view. 3251 * 3252 * @param parent the view from which the child was removed 3253 * @param child the child removed from the hierarchy 3254 */ 3255 void onChildViewRemoved(View parent, View child); 3256 } 3257 3258 /** 3259 * Register a callback to be invoked when a child is added to or removed 3260 * from this view. 3261 * 3262 * @param listener the callback to invoke on hierarchy change 3263 */ 3264 public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) { 3265 mOnHierarchyChangeListener = listener; 3266 } 3267 3268 /** 3269 * @hide 3270 */ 3271 protected void onViewAdded(View child) { 3272 if (mOnHierarchyChangeListener != null) { 3273 mOnHierarchyChangeListener.onChildViewAdded(this, child); 3274 } 3275 } 3276 3277 /** 3278 * @hide 3279 */ 3280 protected void onViewRemoved(View child) { 3281 if (mOnHierarchyChangeListener != null) { 3282 mOnHierarchyChangeListener.onChildViewRemoved(this, child); 3283 } 3284 } 3285 3286 /** 3287 * Adds a view during layout. This is useful if in your onLayout() method, 3288 * you need to add more views (as does the list view for example). 3289 * 3290 * If index is negative, it means put it at the end of the list. 3291 * 3292 * @param child the view to add to the group 3293 * @param index the index at which the child must be added 3294 * @param params the layout parameters to associate with the child 3295 * @return true if the child was added, false otherwise 3296 */ 3297 protected boolean addViewInLayout(View child, int index, LayoutParams params) { 3298 return addViewInLayout(child, index, params, false); 3299 } 3300 3301 /** 3302 * Adds a view during layout. This is useful if in your onLayout() method, 3303 * you need to add more views (as does the list view for example). 3304 * 3305 * If index is negative, it means put it at the end of the list. 3306 * 3307 * @param child the view to add to the group 3308 * @param index the index at which the child must be added 3309 * @param params the layout parameters to associate with the child 3310 * @param preventRequestLayout if true, calling this method will not trigger a 3311 * layout request on child 3312 * @return true if the child was added, false otherwise 3313 */ 3314 protected boolean addViewInLayout(View child, int index, LayoutParams params, 3315 boolean preventRequestLayout) { 3316 child.mParent = null; 3317 addViewInner(child, index, params, preventRequestLayout); 3318 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN; 3319 return true; 3320 } 3321 3322 /** 3323 * Prevents the specified child to be laid out during the next layout pass. 3324 * 3325 * @param child the child on which to perform the cleanup 3326 */ 3327 protected void cleanupLayoutState(View child) { 3328 child.mPrivateFlags &= ~View.FORCE_LAYOUT; 3329 } 3330 3331 private void addViewInner(View child, int index, LayoutParams params, 3332 boolean preventRequestLayout) { 3333 3334 if (mTransition != null) { 3335 // Don't prevent other add transitions from completing, but cancel remove 3336 // transitions to let them complete the process before we add to the container 3337 mTransition.cancel(LayoutTransition.DISAPPEARING); 3338 } 3339 3340 if (child.getParent() != null) { 3341 throw new IllegalStateException("The specified child already has a parent. " + 3342 "You must call removeView() on the child's parent first."); 3343 } 3344 3345 if (mTransition != null) { 3346 mTransition.addChild(this, child); 3347 } 3348 3349 if (!checkLayoutParams(params)) { 3350 params = generateLayoutParams(params); 3351 } 3352 3353 if (preventRequestLayout) { 3354 child.mLayoutParams = params; 3355 } else { 3356 child.setLayoutParams(params); 3357 } 3358 3359 if (index < 0) { 3360 index = mChildrenCount; 3361 } 3362 3363 addInArray(child, index); 3364 3365 // tell our children 3366 if (preventRequestLayout) { 3367 child.assignParent(this); 3368 } else { 3369 child.mParent = this; 3370 } 3371 3372 if (child.hasFocus()) { 3373 requestChildFocus(child, child.findFocus()); 3374 } 3375 3376 AttachInfo ai = mAttachInfo; 3377 if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) { 3378 boolean lastKeepOn = ai.mKeepScreenOn; 3379 ai.mKeepScreenOn = false; 3380 child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK)); 3381 if (ai.mKeepScreenOn) { 3382 needGlobalAttributesUpdate(true); 3383 } 3384 ai.mKeepScreenOn = lastKeepOn; 3385 } 3386 3387 onViewAdded(child); 3388 3389 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) { 3390 mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE; 3391 } 3392 3393 if (child.hasTransientState()) { 3394 childHasTransientStateChanged(child, true); 3395 } 3396 } 3397 3398 private void addInArray(View child, int index) { 3399 View[] children = mChildren; 3400 final int count = mChildrenCount; 3401 final int size = children.length; 3402 if (index == count) { 3403 if (size == count) { 3404 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 3405 System.arraycopy(children, 0, mChildren, 0, size); 3406 children = mChildren; 3407 } 3408 children[mChildrenCount++] = child; 3409 } else if (index < count) { 3410 if (size == count) { 3411 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 3412 System.arraycopy(children, 0, mChildren, 0, index); 3413 System.arraycopy(children, index, mChildren, index + 1, count - index); 3414 children = mChildren; 3415 } else { 3416 System.arraycopy(children, index, children, index + 1, count - index); 3417 } 3418 children[index] = child; 3419 mChildrenCount++; 3420 if (mLastTouchDownIndex >= index) { 3421 mLastTouchDownIndex++; 3422 } 3423 } else { 3424 throw new IndexOutOfBoundsException("index=" + index + " count=" + count); 3425 } 3426 } 3427 3428 // This method also sets the child's mParent to null 3429 private void removeFromArray(int index) { 3430 final View[] children = mChildren; 3431 if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) { 3432 children[index].mParent = null; 3433 } 3434 final int count = mChildrenCount; 3435 if (index == count - 1) { 3436 children[--mChildrenCount] = null; 3437 } else if (index >= 0 && index < count) { 3438 System.arraycopy(children, index + 1, children, index, count - index - 1); 3439 children[--mChildrenCount] = null; 3440 } else { 3441 throw new IndexOutOfBoundsException(); 3442 } 3443 if (mLastTouchDownIndex == index) { 3444 mLastTouchDownTime = 0; 3445 mLastTouchDownIndex = -1; 3446 } else if (mLastTouchDownIndex > index) { 3447 mLastTouchDownIndex--; 3448 } 3449 } 3450 3451 // This method also sets the children's mParent to null 3452 private void removeFromArray(int start, int count) { 3453 final View[] children = mChildren; 3454 final int childrenCount = mChildrenCount; 3455 3456 start = Math.max(0, start); 3457 final int end = Math.min(childrenCount, start + count); 3458 3459 if (start == end) { 3460 return; 3461 } 3462 3463 if (end == childrenCount) { 3464 for (int i = start; i < end; i++) { 3465 children[i].mParent = null; 3466 children[i] = null; 3467 } 3468 } else { 3469 for (int i = start; i < end; i++) { 3470 children[i].mParent = null; 3471 } 3472 3473 // Since we're looping above, we might as well do the copy, but is arraycopy() 3474 // faster than the extra 2 bounds checks we would do in the loop? 3475 System.arraycopy(children, end, children, start, childrenCount - end); 3476 3477 for (int i = childrenCount - (end - start); i < childrenCount; i++) { 3478 children[i] = null; 3479 } 3480 } 3481 3482 mChildrenCount -= (end - start); 3483 } 3484 3485 private void bindLayoutAnimation(View child) { 3486 Animation a = mLayoutAnimationController.getAnimationForView(child); 3487 child.setAnimation(a); 3488 } 3489 3490 /** 3491 * Subclasses should override this method to set layout animation 3492 * parameters on the supplied child. 3493 * 3494 * @param child the child to associate with animation parameters 3495 * @param params the child's layout parameters which hold the animation 3496 * parameters 3497 * @param index the index of the child in the view group 3498 * @param count the number of children in the view group 3499 */ 3500 protected void attachLayoutAnimationParameters(View child, 3501 LayoutParams params, int index, int count) { 3502 LayoutAnimationController.AnimationParameters animationParams = 3503 params.layoutAnimationParameters; 3504 if (animationParams == null) { 3505 animationParams = new LayoutAnimationController.AnimationParameters(); 3506 params.layoutAnimationParameters = animationParams; 3507 } 3508 3509 animationParams.count = count; 3510 animationParams.index = index; 3511 } 3512 3513 /** 3514 * {@inheritDoc} 3515 */ 3516 public void removeView(View view) { 3517 removeViewInternal(view); 3518 requestLayout(); 3519 invalidate(true); 3520 } 3521 3522 /** 3523 * Removes a view during layout. This is useful if in your onLayout() method, 3524 * you need to remove more views. 3525 * 3526 * @param view the view to remove from the group 3527 */ 3528 public void removeViewInLayout(View view) { 3529 removeViewInternal(view); 3530 } 3531 3532 /** 3533 * Removes a range of views during layout. This is useful if in your onLayout() method, 3534 * you need to remove more views. 3535 * 3536 * @param start the index of the first view to remove from the group 3537 * @param count the number of views to remove from the group 3538 */ 3539 public void removeViewsInLayout(int start, int count) { 3540 removeViewsInternal(start, count); 3541 } 3542 3543 /** 3544 * Removes the view at the specified position in the group. 3545 * 3546 * @param index the position in the group of the view to remove 3547 */ 3548 public void removeViewAt(int index) { 3549 removeViewInternal(index, getChildAt(index)); 3550 requestLayout(); 3551 invalidate(true); 3552 } 3553 3554 /** 3555 * Removes the specified range of views from the group. 3556 * 3557 * @param start the first position in the group of the range of views to remove 3558 * @param count the number of views to remove 3559 */ 3560 public void removeViews(int start, int count) { 3561 removeViewsInternal(start, count); 3562 requestLayout(); 3563 invalidate(true); 3564 } 3565 3566 private void removeViewInternal(View view) { 3567 final int index = indexOfChild(view); 3568 if (index >= 0) { 3569 removeViewInternal(index, view); 3570 } 3571 } 3572 3573 private void removeViewInternal(int index, View view) { 3574 3575 if (mTransition != null) { 3576 mTransition.removeChild(this, view); 3577 } 3578 3579 boolean clearChildFocus = false; 3580 if (view == mFocused) { 3581 view.unFocus(); 3582 clearChildFocus = true; 3583 } 3584 3585 cancelTouchTarget(view); 3586 cancelHoverTarget(view); 3587 3588 if (view.getAnimation() != null || 3589 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3590 addDisappearingView(view); 3591 } else if (view.mAttachInfo != null) { 3592 view.dispatchDetachedFromWindow(); 3593 } 3594 3595 if (view.hasTransientState()) { 3596 childHasTransientStateChanged(view, false); 3597 } 3598 3599 onViewRemoved(view); 3600 3601 needGlobalAttributesUpdate(false); 3602 3603 removeFromArray(index); 3604 3605 if (clearChildFocus) { 3606 clearChildFocus(view); 3607 ensureInputFocusOnFirstFocusable(); 3608 } 3609 3610 if (view.isAccessibilityFocused()) { 3611 view.clearAccessibilityFocus(); 3612 } 3613 } 3614 3615 /** 3616 * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3617 * not null, changes in layout which occur because of children being added to or removed from 3618 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3619 * object. By default, the transition object is null (so layout changes are not animated). 3620 * 3621 * @param transition The LayoutTransition object that will animated changes in layout. A value 3622 * of <code>null</code> means no transition will run on layout changes. 3623 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges 3624 */ 3625 public void setLayoutTransition(LayoutTransition transition) { 3626 if (mTransition != null) { 3627 mTransition.removeTransitionListener(mLayoutTransitionListener); 3628 } 3629 mTransition = transition; 3630 if (mTransition != null) { 3631 mTransition.addTransitionListener(mLayoutTransitionListener); 3632 } 3633 } 3634 3635 /** 3636 * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3637 * not null, changes in layout which occur because of children being added to or removed from 3638 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3639 * object. By default, the transition object is null (so layout changes are not animated). 3640 * 3641 * @return LayoutTranstion The LayoutTransition object that will animated changes in layout. 3642 * A value of <code>null</code> means no transition will run on layout changes. 3643 */ 3644 public LayoutTransition getLayoutTransition() { 3645 return mTransition; 3646 } 3647 3648 private void removeViewsInternal(int start, int count) { 3649 final View focused = mFocused; 3650 final boolean detach = mAttachInfo != null; 3651 View clearChildFocus = null; 3652 3653 final View[] children = mChildren; 3654 final int end = start + count; 3655 3656 for (int i = start; i < end; i++) { 3657 final View view = children[i]; 3658 3659 if (mTransition != null) { 3660 mTransition.removeChild(this, view); 3661 } 3662 3663 if (view == focused) { 3664 view.unFocus(); 3665 clearChildFocus = view; 3666 } 3667 3668 cancelTouchTarget(view); 3669 cancelHoverTarget(view); 3670 3671 if (view.getAnimation() != null || 3672 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3673 addDisappearingView(view); 3674 } else if (detach) { 3675 view.dispatchDetachedFromWindow(); 3676 } 3677 3678 if (view.hasTransientState()) { 3679 childHasTransientStateChanged(view, false); 3680 } 3681 3682 needGlobalAttributesUpdate(false); 3683 3684 onViewRemoved(view); 3685 } 3686 3687 removeFromArray(start, count); 3688 3689 if (clearChildFocus != null) { 3690 clearChildFocus(clearChildFocus); 3691 ensureInputFocusOnFirstFocusable(); 3692 } 3693 } 3694 3695 /** 3696 * Call this method to remove all child views from the 3697 * ViewGroup. 3698 */ 3699 public void removeAllViews() { 3700 removeAllViewsInLayout(); 3701 requestLayout(); 3702 invalidate(true); 3703 } 3704 3705 /** 3706 * Called by a ViewGroup subclass to remove child views from itself, 3707 * when it must first know its size on screen before it can calculate how many 3708 * child views it will render. An example is a Gallery or a ListView, which 3709 * may "have" 50 children, but actually only render the number of children 3710 * that can currently fit inside the object on screen. Do not call 3711 * this method unless you are extending ViewGroup and understand the 3712 * view measuring and layout pipeline. 3713 */ 3714 public void removeAllViewsInLayout() { 3715 final int count = mChildrenCount; 3716 if (count <= 0) { 3717 return; 3718 } 3719 3720 final View[] children = mChildren; 3721 mChildrenCount = 0; 3722 3723 final View focused = mFocused; 3724 final boolean detach = mAttachInfo != null; 3725 View clearChildFocus = null; 3726 3727 needGlobalAttributesUpdate(false); 3728 3729 for (int i = count - 1; i >= 0; i--) { 3730 final View view = children[i]; 3731 3732 if (mTransition != null) { 3733 mTransition.removeChild(this, view); 3734 } 3735 3736 if (view == focused) { 3737 view.unFocus(); 3738 clearChildFocus = view; 3739 } 3740 3741 cancelTouchTarget(view); 3742 cancelHoverTarget(view); 3743 3744 if (view.getAnimation() != null || 3745 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3746 addDisappearingView(view); 3747 } else if (detach) { 3748 view.dispatchDetachedFromWindow(); 3749 } 3750 3751 if (view.hasTransientState()) { 3752 childHasTransientStateChanged(view, false); 3753 } 3754 3755 onViewRemoved(view); 3756 3757 view.mParent = null; 3758 children[i] = null; 3759 } 3760 3761 if (clearChildFocus != null) { 3762 clearChildFocus(clearChildFocus); 3763 ensureInputFocusOnFirstFocusable(); 3764 } 3765 } 3766 3767 /** 3768 * Finishes the removal of a detached view. This method will dispatch the detached from 3769 * window event and notify the hierarchy change listener. 3770 * 3771 * @param child the child to be definitely removed from the view hierarchy 3772 * @param animate if true and the view has an animation, the view is placed in the 3773 * disappearing views list, otherwise, it is detached from the window 3774 * 3775 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3776 * @see #detachAllViewsFromParent() 3777 * @see #detachViewFromParent(View) 3778 * @see #detachViewFromParent(int) 3779 */ 3780 protected void removeDetachedView(View child, boolean animate) { 3781 if (mTransition != null) { 3782 mTransition.removeChild(this, child); 3783 } 3784 3785 if (child == mFocused) { 3786 child.clearFocus(); 3787 } 3788 3789 cancelTouchTarget(child); 3790 cancelHoverTarget(child); 3791 3792 if ((animate && child.getAnimation() != null) || 3793 (mTransitioningViews != null && mTransitioningViews.contains(child))) { 3794 addDisappearingView(child); 3795 } else if (child.mAttachInfo != null) { 3796 child.dispatchDetachedFromWindow(); 3797 } 3798 3799 if (child.hasTransientState()) { 3800 childHasTransientStateChanged(child, false); 3801 } 3802 3803 onViewRemoved(child); 3804 } 3805 3806 /** 3807 * Attaches a view to this view group. Attaching a view assigns this group as the parent, 3808 * sets the layout parameters and puts the view in the list of children so it can be retrieved 3809 * by calling {@link #getChildAt(int)}. 3810 * 3811 * This method should be called only for view which were detached from their parent. 3812 * 3813 * @param child the child to attach 3814 * @param index the index at which the child should be attached 3815 * @param params the layout parameters of the child 3816 * 3817 * @see #removeDetachedView(View, boolean) 3818 * @see #detachAllViewsFromParent() 3819 * @see #detachViewFromParent(View) 3820 * @see #detachViewFromParent(int) 3821 */ 3822 protected void attachViewToParent(View child, int index, LayoutParams params) { 3823 child.mLayoutParams = params; 3824 3825 if (index < 0) { 3826 index = mChildrenCount; 3827 } 3828 3829 addInArray(child, index); 3830 3831 child.mParent = this; 3832 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) | 3833 DRAWN | INVALIDATED; 3834 this.mPrivateFlags |= INVALIDATED; 3835 3836 if (child.hasFocus()) { 3837 requestChildFocus(child, child.findFocus()); 3838 } 3839 } 3840 3841 /** 3842 * Detaches a view from its parent. Detaching a view should be temporary and followed 3843 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3844 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3845 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3846 * 3847 * @param child the child to detach 3848 * 3849 * @see #detachViewFromParent(int) 3850 * @see #detachViewsFromParent(int, int) 3851 * @see #detachAllViewsFromParent() 3852 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3853 * @see #removeDetachedView(View, boolean) 3854 */ 3855 protected void detachViewFromParent(View child) { 3856 removeFromArray(indexOfChild(child)); 3857 } 3858 3859 /** 3860 * Detaches a view from its parent. Detaching a view should be temporary and followed 3861 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3862 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3863 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3864 * 3865 * @param index the index of the child to detach 3866 * 3867 * @see #detachViewFromParent(View) 3868 * @see #detachAllViewsFromParent() 3869 * @see #detachViewsFromParent(int, int) 3870 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3871 * @see #removeDetachedView(View, boolean) 3872 */ 3873 protected void detachViewFromParent(int index) { 3874 removeFromArray(index); 3875 } 3876 3877 /** 3878 * Detaches a range of view from their parent. Detaching a view should be temporary and followed 3879 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3880 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its 3881 * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3882 * 3883 * @param start the first index of the childrend range to detach 3884 * @param count the number of children to detach 3885 * 3886 * @see #detachViewFromParent(View) 3887 * @see #detachViewFromParent(int) 3888 * @see #detachAllViewsFromParent() 3889 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3890 * @see #removeDetachedView(View, boolean) 3891 */ 3892 protected void detachViewsFromParent(int start, int count) { 3893 removeFromArray(start, count); 3894 } 3895 3896 /** 3897 * Detaches all views from the parent. Detaching a view should be temporary and followed 3898 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3899 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3900 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3901 * 3902 * @see #detachViewFromParent(View) 3903 * @see #detachViewFromParent(int) 3904 * @see #detachViewsFromParent(int, int) 3905 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3906 * @see #removeDetachedView(View, boolean) 3907 */ 3908 protected void detachAllViewsFromParent() { 3909 final int count = mChildrenCount; 3910 if (count <= 0) { 3911 return; 3912 } 3913 3914 final View[] children = mChildren; 3915 mChildrenCount = 0; 3916 3917 for (int i = count - 1; i >= 0; i--) { 3918 children[i].mParent = null; 3919 children[i] = null; 3920 } 3921 } 3922 3923 /** 3924 * Don't call or override this method. It is used for the implementation of 3925 * the view hierarchy. 3926 */ 3927 public final void invalidateChild(View child, final Rect dirty) { 3928 if (ViewDebug.TRACE_HIERARCHY) { 3929 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD); 3930 } 3931 3932 ViewParent parent = this; 3933 3934 final AttachInfo attachInfo = mAttachInfo; 3935 if (attachInfo != null) { 3936 // If the child is drawing an animation, we want to copy this flag onto 3937 // ourselves and the parent to make sure the invalidate request goes 3938 // through 3939 final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION; 3940 3941 //noinspection PointlessBooleanExpression 3942 if (!HardwareRenderer.RENDER_DIRTY_REGIONS) { 3943 if (dirty == null) { 3944 if (child.mLayerType != LAYER_TYPE_NONE) { 3945 mPrivateFlags |= INVALIDATED; 3946 mPrivateFlags &= ~DRAWING_CACHE_VALID; 3947 child.mLocalDirtyRect.setEmpty(); 3948 } 3949 do { 3950 View view = null; 3951 if (parent instanceof View) { 3952 view = (View) parent; 3953 if (view.mLayerType != LAYER_TYPE_NONE) { 3954 view.mLocalDirtyRect.setEmpty(); 3955 if (view.getParent() instanceof View) { 3956 final View grandParent = (View) view.getParent(); 3957 grandParent.mPrivateFlags |= INVALIDATED; 3958 grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID; 3959 } 3960 } 3961 if ((view.mPrivateFlags & DIRTY_MASK) != 0) { 3962 // already marked dirty - we're done 3963 break; 3964 } 3965 } 3966 3967 if (drawAnimation) { 3968 if (view != null) { 3969 view.mPrivateFlags |= DRAW_ANIMATION; 3970 } else if (parent instanceof ViewRootImpl) { 3971 ((ViewRootImpl) parent).mIsAnimating = true; 3972 } 3973 } 3974 3975 if (parent instanceof ViewRootImpl) { 3976 ((ViewRootImpl) parent).invalidate(); 3977 parent = null; 3978 } else if (view != null) { 3979 if ((view.mPrivateFlags & DRAWN) == DRAWN || 3980 (view.mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 3981 view.mPrivateFlags &= ~DRAWING_CACHE_VALID; 3982 view.mPrivateFlags |= DIRTY; 3983 parent = view.mParent; 3984 } else { 3985 parent = null; 3986 } 3987 } 3988 } while (parent != null); 3989 } 3990 3991 return; 3992 } 3993 3994 // Check whether the child that requests the invalidate is fully opaque 3995 // Views being animated or transformed are not considered opaque because we may 3996 // be invalidating their old position and need the parent to paint behind them. 3997 Matrix childMatrix = child.getMatrix(); 3998 final boolean isOpaque = child.isOpaque() && !drawAnimation && 3999 child.getAnimation() == null && childMatrix.isIdentity(); 4000 // Mark the child as dirty, using the appropriate flag 4001 // Make sure we do not set both flags at the same time 4002 int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY; 4003 4004 if (child.mLayerType != LAYER_TYPE_NONE) { 4005 mPrivateFlags |= INVALIDATED; 4006 mPrivateFlags &= ~DRAWING_CACHE_VALID; 4007 child.mLocalDirtyRect.union(dirty); 4008 } 4009 4010 final int[] location = attachInfo.mInvalidateChildLocation; 4011 location[CHILD_LEFT_INDEX] = child.mLeft; 4012 location[CHILD_TOP_INDEX] = child.mTop; 4013 if (!childMatrix.isIdentity()) { 4014 RectF boundingRect = attachInfo.mTmpTransformRect; 4015 boundingRect.set(dirty); 4016 //boundingRect.inset(-0.5f, -0.5f); 4017 childMatrix.mapRect(boundingRect); 4018 dirty.set((int) (boundingRect.left - 0.5f), 4019 (int) (boundingRect.top - 0.5f), 4020 (int) (boundingRect.right + 0.5f), 4021 (int) (boundingRect.bottom + 0.5f)); 4022 } 4023 4024 do { 4025 View view = null; 4026 if (parent instanceof View) { 4027 view = (View) parent; 4028 if (view.mLayerType != LAYER_TYPE_NONE && 4029 view.getParent() instanceof View) { 4030 final View grandParent = (View) view.getParent(); 4031 grandParent.mPrivateFlags |= INVALIDATED; 4032 grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID; 4033 } 4034 } 4035 4036 if (drawAnimation) { 4037 if (view != null) { 4038 view.mPrivateFlags |= DRAW_ANIMATION; 4039 } else if (parent instanceof ViewRootImpl) { 4040 ((ViewRootImpl) parent).mIsAnimating = true; 4041 } 4042 } 4043 4044 // If the parent is dirty opaque or not dirty, mark it dirty with the opaque 4045 // flag coming from the child that initiated the invalidate 4046 if (view != null) { 4047 if ((view.mViewFlags & FADING_EDGE_MASK) != 0 && 4048 view.getSolidColor() == 0) { 4049 opaqueFlag = DIRTY; 4050 } 4051 if ((view.mPrivateFlags & DIRTY_MASK) != DIRTY) { 4052 view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag; 4053 } 4054 } 4055 4056 parent = parent.invalidateChildInParent(location, dirty); 4057 if (view != null) { 4058 // Account for transform on current parent 4059 Matrix m = view.getMatrix(); 4060 if (!m.isIdentity()) { 4061 RectF boundingRect = attachInfo.mTmpTransformRect; 4062 boundingRect.set(dirty); 4063 m.mapRect(boundingRect); 4064 dirty.set((int) (boundingRect.left - 0.5f), 4065 (int) (boundingRect.top - 0.5f), 4066 (int) (boundingRect.right + 0.5f), 4067 (int) (boundingRect.bottom + 0.5f)); 4068 } 4069 } 4070 } while (parent != null); 4071 } 4072 } 4073 4074 /** 4075 * Don't call or override this method. It is used for the implementation of 4076 * the view hierarchy. 4077 * 4078 * This implementation returns null if this ViewGroup does not have a parent, 4079 * if this ViewGroup is already fully invalidated or if the dirty rectangle 4080 * does not intersect with this ViewGroup's bounds. 4081 */ 4082 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) { 4083 if (ViewDebug.TRACE_HIERARCHY) { 4084 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD_IN_PARENT); 4085 } 4086 4087 if ((mPrivateFlags & DRAWN) == DRAWN || 4088 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 4089 if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) != 4090 FLAG_OPTIMIZE_INVALIDATE) { 4091 dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX, 4092 location[CHILD_TOP_INDEX] - mScrollY); 4093 4094 final int left = mLeft; 4095 final int top = mTop; 4096 4097 if ((mGroupFlags & FLAG_CLIP_CHILDREN) != FLAG_CLIP_CHILDREN || 4098 dirty.intersect(0, 0, mRight - left, mBottom - top) || 4099 (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) { 4100 mPrivateFlags &= ~DRAWING_CACHE_VALID; 4101 4102 location[CHILD_LEFT_INDEX] = left; 4103 location[CHILD_TOP_INDEX] = top; 4104 4105 if (mLayerType != LAYER_TYPE_NONE) { 4106 mLocalDirtyRect.union(dirty); 4107 } 4108 4109 return mParent; 4110 } 4111 } else { 4112 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID; 4113 4114 location[CHILD_LEFT_INDEX] = mLeft; 4115 location[CHILD_TOP_INDEX] = mTop; 4116 if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) { 4117 dirty.set(0, 0, mRight - mLeft, mBottom - mTop); 4118 } else { 4119 // in case the dirty rect extends outside the bounds of this container 4120 dirty.union(0, 0, mRight - mLeft, mBottom - mTop); 4121 } 4122 4123 if (mLayerType != LAYER_TYPE_NONE) { 4124 mLocalDirtyRect.union(dirty); 4125 } 4126 4127 return mParent; 4128 } 4129 } 4130 4131 return null; 4132 } 4133 4134 /** 4135 * Quick invalidation method called by View.invalidateViewProperty. This doesn't set the 4136 * DRAWN flags and doesn't handle the Animation logic that the default invalidation methods 4137 * do; all we want to do here is schedule a traversal with the appropriate dirty rect. 4138 * 4139 * @hide 4140 */ 4141 public void invalidateChildFast(View child, final Rect dirty) { 4142 ViewParent parent = this; 4143 4144 final AttachInfo attachInfo = mAttachInfo; 4145 if (attachInfo != null) { 4146 if (child.mLayerType != LAYER_TYPE_NONE) { 4147 child.mLocalDirtyRect.union(dirty); 4148 } 4149 4150 int left = child.mLeft; 4151 int top = child.mTop; 4152 if (!child.getMatrix().isIdentity()) { 4153 child.transformRect(dirty); 4154 } 4155 4156 do { 4157 if (parent instanceof ViewGroup) { 4158 ViewGroup parentVG = (ViewGroup) parent; 4159 if (parentVG.mLayerType != LAYER_TYPE_NONE) { 4160 // Layered parents should be recreated, not just re-issued 4161 parentVG.invalidate(); 4162 parent = null; 4163 } else { 4164 parent = parentVG.invalidateChildInParentFast(left, top, dirty); 4165 left = parentVG.mLeft; 4166 top = parentVG.mTop; 4167 } 4168 } else { 4169 // Reached the top; this calls into the usual invalidate method in 4170 // ViewRootImpl, which schedules a traversal 4171 final int[] location = attachInfo.mInvalidateChildLocation; 4172 location[0] = left; 4173 location[1] = top; 4174 parent = parent.invalidateChildInParent(location, dirty); 4175 } 4176 } while (parent != null); 4177 } 4178 } 4179 4180 /** 4181 * Quick invalidation method that simply transforms the dirty rect into the parent's 4182 * coordinate system, pruning the invalidation if the parent has already been invalidated. 4183 */ 4184 private ViewParent invalidateChildInParentFast(int left, int top, final Rect dirty) { 4185 if ((mPrivateFlags & DRAWN) == DRAWN || 4186 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 4187 dirty.offset(left - mScrollX, top - mScrollY); 4188 4189 if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0 || 4190 dirty.intersect(0, 0, mRight - mLeft, mBottom - mTop)) { 4191 4192 if (mLayerType != LAYER_TYPE_NONE) { 4193 mLocalDirtyRect.union(dirty); 4194 } 4195 if (!getMatrix().isIdentity()) { 4196 transformRect(dirty); 4197 } 4198 4199 return mParent; 4200 } 4201 } 4202 4203 return null; 4204 } 4205 4206 /** 4207 * Offset a rectangle that is in a descendant's coordinate 4208 * space into our coordinate space. 4209 * @param descendant A descendant of this view 4210 * @param rect A rectangle defined in descendant's coordinate space. 4211 */ 4212 public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) { 4213 offsetRectBetweenParentAndChild(descendant, rect, true, false); 4214 } 4215 4216 /** 4217 * Offset a rectangle that is in our coordinate space into an ancestor's 4218 * coordinate space. 4219 * @param descendant A descendant of this view 4220 * @param rect A rectangle defined in descendant's coordinate space. 4221 */ 4222 public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) { 4223 offsetRectBetweenParentAndChild(descendant, rect, false, false); 4224 } 4225 4226 /** 4227 * Helper method that offsets a rect either from parent to descendant or 4228 * descendant to parent. 4229 */ 4230 void offsetRectBetweenParentAndChild(View descendant, Rect rect, 4231 boolean offsetFromChildToParent, boolean clipToBounds) { 4232 4233 // already in the same coord system :) 4234 if (descendant == this) { 4235 return; 4236 } 4237 4238 ViewParent theParent = descendant.mParent; 4239 4240 // search and offset up to the parent 4241 while ((theParent != null) 4242 && (theParent instanceof View) 4243 && (theParent != this)) { 4244 4245 if (offsetFromChildToParent) { 4246 rect.offset(descendant.mLeft - descendant.mScrollX, 4247 descendant.mTop - descendant.mScrollY); 4248 if (clipToBounds) { 4249 View p = (View) theParent; 4250 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 4251 } 4252 } else { 4253 if (clipToBounds) { 4254 View p = (View) theParent; 4255 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 4256 } 4257 rect.offset(descendant.mScrollX - descendant.mLeft, 4258 descendant.mScrollY - descendant.mTop); 4259 } 4260 4261 descendant = (View) theParent; 4262 theParent = descendant.mParent; 4263 } 4264 4265 // now that we are up to this view, need to offset one more time 4266 // to get into our coordinate space 4267 if (theParent == this) { 4268 if (offsetFromChildToParent) { 4269 rect.offset(descendant.mLeft - descendant.mScrollX, 4270 descendant.mTop - descendant.mScrollY); 4271 } else { 4272 rect.offset(descendant.mScrollX - descendant.mLeft, 4273 descendant.mScrollY - descendant.mTop); 4274 } 4275 } else { 4276 throw new IllegalArgumentException("parameter must be a descendant of this view"); 4277 } 4278 } 4279 4280 /** 4281 * Offset the vertical location of all children of this view by the specified number of pixels. 4282 * 4283 * @param offset the number of pixels to offset 4284 * 4285 * @hide 4286 */ 4287 public void offsetChildrenTopAndBottom(int offset) { 4288 final int count = mChildrenCount; 4289 final View[] children = mChildren; 4290 4291 for (int i = 0; i < count; i++) { 4292 final View v = children[i]; 4293 v.mTop += offset; 4294 v.mBottom += offset; 4295 if (v.mDisplayList != null) { 4296 v.mDisplayList.offsetTopBottom(offset); 4297 invalidateViewProperty(false, false); 4298 } 4299 } 4300 } 4301 4302 /** 4303 * {@inheritDoc} 4304 */ 4305 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 4306 // It doesn't make a whole lot of sense to call this on a view that isn't attached, 4307 // but for some simple tests it can be useful. If we don't have attach info this 4308 // will allocate memory. 4309 final RectF rect = mAttachInfo != null ? mAttachInfo.mTmpTransformRect : new RectF(); 4310 rect.set(r); 4311 4312 if (!child.hasIdentityMatrix()) { 4313 child.getMatrix().mapRect(rect); 4314 } 4315 4316 int dx = child.mLeft - mScrollX; 4317 int dy = child.mTop - mScrollY; 4318 4319 rect.offset(dx, dy); 4320 4321 if (offset != null) { 4322 if (!child.hasIdentityMatrix()) { 4323 float[] position = mAttachInfo != null ? mAttachInfo.mTmpTransformLocation 4324 : new float[2]; 4325 position[0] = offset.x; 4326 position[1] = offset.y; 4327 child.getMatrix().mapPoints(position); 4328 offset.x = (int) (position[0] + 0.5f); 4329 offset.y = (int) (position[1] + 0.5f); 4330 } 4331 offset.x += dx; 4332 offset.y += dy; 4333 } 4334 4335 if (rect.intersect(0, 0, mRight - mLeft, mBottom - mTop)) { 4336 if (mParent == null) return true; 4337 r.set((int) (rect.left + 0.5f), (int) (rect.top + 0.5f), 4338 (int) (rect.right + 0.5f), (int) (rect.bottom + 0.5f)); 4339 return mParent.getChildVisibleRect(this, r, offset); 4340 } 4341 4342 return false; 4343 } 4344 4345 /** 4346 * {@inheritDoc} 4347 */ 4348 @Override 4349 public final void layout(int l, int t, int r, int b) { 4350 if (mTransition == null || !mTransition.isChangingLayout()) { 4351 if (mTransition != null) { 4352 mTransition.layoutChange(this); 4353 } 4354 super.layout(l, t, r, b); 4355 } else { 4356 // record the fact that we noop'd it; request layout when transition finishes 4357 mLayoutSuppressed = true; 4358 } 4359 } 4360 4361 /** 4362 * {@inheritDoc} 4363 */ 4364 @Override 4365 protected abstract void onLayout(boolean changed, 4366 int l, int t, int r, int b); 4367 4368 /** 4369 * Indicates whether the view group has the ability to animate its children 4370 * after the first layout. 4371 * 4372 * @return true if the children can be animated, false otherwise 4373 */ 4374 protected boolean canAnimate() { 4375 return mLayoutAnimationController != null; 4376 } 4377 4378 /** 4379 * Runs the layout animation. Calling this method triggers a relayout of 4380 * this view group. 4381 */ 4382 public void startLayoutAnimation() { 4383 if (mLayoutAnimationController != null) { 4384 mGroupFlags |= FLAG_RUN_ANIMATION; 4385 requestLayout(); 4386 } 4387 } 4388 4389 /** 4390 * Schedules the layout animation to be played after the next layout pass 4391 * of this view group. This can be used to restart the layout animation 4392 * when the content of the view group changes or when the activity is 4393 * paused and resumed. 4394 */ 4395 public void scheduleLayoutAnimation() { 4396 mGroupFlags |= FLAG_RUN_ANIMATION; 4397 } 4398 4399 /** 4400 * Sets the layout animation controller used to animate the group's 4401 * children after the first layout. 4402 * 4403 * @param controller the animation controller 4404 */ 4405 public void setLayoutAnimation(LayoutAnimationController controller) { 4406 mLayoutAnimationController = controller; 4407 if (mLayoutAnimationController != null) { 4408 mGroupFlags |= FLAG_RUN_ANIMATION; 4409 } 4410 } 4411 4412 /** 4413 * Returns the layout animation controller used to animate the group's 4414 * children. 4415 * 4416 * @return the current animation controller 4417 */ 4418 public LayoutAnimationController getLayoutAnimation() { 4419 return mLayoutAnimationController; 4420 } 4421 4422 /** 4423 * Indicates whether the children's drawing cache is used during a layout 4424 * animation. By default, the drawing cache is enabled but this will prevent 4425 * nested layout animations from working. To nest animations, you must disable 4426 * the cache. 4427 * 4428 * @return true if the animation cache is enabled, false otherwise 4429 * 4430 * @see #setAnimationCacheEnabled(boolean) 4431 * @see View#setDrawingCacheEnabled(boolean) 4432 */ 4433 @ViewDebug.ExportedProperty 4434 public boolean isAnimationCacheEnabled() { 4435 return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE; 4436 } 4437 4438 /** 4439 * Enables or disables the children's drawing cache during a layout animation. 4440 * By default, the drawing cache is enabled but this will prevent nested 4441 * layout animations from working. To nest animations, you must disable the 4442 * cache. 4443 * 4444 * @param enabled true to enable the animation cache, false otherwise 4445 * 4446 * @see #isAnimationCacheEnabled() 4447 * @see View#setDrawingCacheEnabled(boolean) 4448 */ 4449 public void setAnimationCacheEnabled(boolean enabled) { 4450 setBooleanFlag(FLAG_ANIMATION_CACHE, enabled); 4451 } 4452 4453 /** 4454 * Indicates whether this ViewGroup will always try to draw its children using their 4455 * drawing cache. By default this property is enabled. 4456 * 4457 * @return true if the animation cache is enabled, false otherwise 4458 * 4459 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4460 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4461 * @see View#setDrawingCacheEnabled(boolean) 4462 */ 4463 @ViewDebug.ExportedProperty(category = "drawing") 4464 public boolean isAlwaysDrawnWithCacheEnabled() { 4465 return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE; 4466 } 4467 4468 /** 4469 * Indicates whether this ViewGroup will always try to draw its children using their 4470 * drawing cache. This property can be set to true when the cache rendering is 4471 * slightly different from the children's normal rendering. Renderings can be different, 4472 * for instance, when the cache's quality is set to low. 4473 * 4474 * When this property is disabled, the ViewGroup will use the drawing cache of its 4475 * children only when asked to. It's usually the task of subclasses to tell ViewGroup 4476 * when to start using the drawing cache and when to stop using it. 4477 * 4478 * @param always true to always draw with the drawing cache, false otherwise 4479 * 4480 * @see #isAlwaysDrawnWithCacheEnabled() 4481 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4482 * @see View#setDrawingCacheEnabled(boolean) 4483 * @see View#setDrawingCacheQuality(int) 4484 */ 4485 public void setAlwaysDrawnWithCacheEnabled(boolean always) { 4486 setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always); 4487 } 4488 4489 /** 4490 * Indicates whether the ViewGroup is currently drawing its children using 4491 * their drawing cache. 4492 * 4493 * @return true if children should be drawn with their cache, false otherwise 4494 * 4495 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4496 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4497 */ 4498 @ViewDebug.ExportedProperty(category = "drawing") 4499 protected boolean isChildrenDrawnWithCacheEnabled() { 4500 return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE; 4501 } 4502 4503 /** 4504 * Tells the ViewGroup to draw its children using their drawing cache. This property 4505 * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache 4506 * will be used only if it has been enabled. 4507 * 4508 * Subclasses should call this method to start and stop using the drawing cache when 4509 * they perform performance sensitive operations, like scrolling or animating. 4510 * 4511 * @param enabled true if children should be drawn with their cache, false otherwise 4512 * 4513 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4514 * @see #isChildrenDrawnWithCacheEnabled() 4515 */ 4516 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) { 4517 setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled); 4518 } 4519 4520 /** 4521 * Indicates whether the ViewGroup is drawing its children in the order defined by 4522 * {@link #getChildDrawingOrder(int, int)}. 4523 * 4524 * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)}, 4525 * false otherwise 4526 * 4527 * @see #setChildrenDrawingOrderEnabled(boolean) 4528 * @see #getChildDrawingOrder(int, int) 4529 */ 4530 @ViewDebug.ExportedProperty(category = "drawing") 4531 protected boolean isChildrenDrawingOrderEnabled() { 4532 return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER; 4533 } 4534 4535 /** 4536 * Tells the ViewGroup whether to draw its children in the order defined by the method 4537 * {@link #getChildDrawingOrder(int, int)}. 4538 * 4539 * @param enabled true if the order of the children when drawing is determined by 4540 * {@link #getChildDrawingOrder(int, int)}, false otherwise 4541 * 4542 * @see #isChildrenDrawingOrderEnabled() 4543 * @see #getChildDrawingOrder(int, int) 4544 */ 4545 protected void setChildrenDrawingOrderEnabled(boolean enabled) { 4546 setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled); 4547 } 4548 4549 private void setBooleanFlag(int flag, boolean value) { 4550 if (value) { 4551 mGroupFlags |= flag; 4552 } else { 4553 mGroupFlags &= ~flag; 4554 } 4555 } 4556 4557 /** 4558 * Returns an integer indicating what types of drawing caches are kept in memory. 4559 * 4560 * @see #setPersistentDrawingCache(int) 4561 * @see #setAnimationCacheEnabled(boolean) 4562 * 4563 * @return one or a combination of {@link #PERSISTENT_NO_CACHE}, 4564 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4565 * and {@link #PERSISTENT_ALL_CACHES} 4566 */ 4567 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 4568 @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE, to = "NONE"), 4569 @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"), 4570 @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"), 4571 @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES, to = "ALL") 4572 }) 4573 public int getPersistentDrawingCache() { 4574 return mPersistentDrawingCache; 4575 } 4576 4577 /** 4578 * Indicates what types of drawing caches should be kept in memory after 4579 * they have been created. 4580 * 4581 * @see #getPersistentDrawingCache() 4582 * @see #setAnimationCacheEnabled(boolean) 4583 * 4584 * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE}, 4585 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4586 * and {@link #PERSISTENT_ALL_CACHES} 4587 */ 4588 public void setPersistentDrawingCache(int drawingCacheToKeep) { 4589 mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES; 4590 } 4591 4592 /** 4593 * Returns the basis of alignment during layout operations on this view group: 4594 * either {@link #CLIP_BOUNDS} or {@link #OPTICAL_BOUNDS}. 4595 * 4596 * @return the layout mode to use during layout operations 4597 * 4598 * @see #setLayoutMode(int) 4599 */ 4600 public int getLayoutMode() { 4601 return mLayoutMode; 4602 } 4603 4604 /** 4605 * Sets the basis of alignment during the layout of this view group. 4606 * Valid values are either {@link #CLIP_BOUNDS} or {@link #OPTICAL_BOUNDS}. 4607 * <p> 4608 * The default is {@link #CLIP_BOUNDS}. 4609 * 4610 * @param layoutMode the layout mode to use during layout operations 4611 * 4612 * @see #getLayoutMode() 4613 */ 4614 public void setLayoutMode(int layoutMode) { 4615 if (mLayoutMode != layoutMode) { 4616 mLayoutMode = layoutMode; 4617 requestLayout(); 4618 } 4619 } 4620 4621 /** 4622 * Returns a new set of layout parameters based on the supplied attributes set. 4623 * 4624 * @param attrs the attributes to build the layout parameters from 4625 * 4626 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4627 * of its descendants 4628 */ 4629 public LayoutParams generateLayoutParams(AttributeSet attrs) { 4630 return new LayoutParams(getContext(), attrs); 4631 } 4632 4633 /** 4634 * Returns a safe set of layout parameters based on the supplied layout params. 4635 * When a ViewGroup is passed a View whose layout params do not pass the test of 4636 * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method 4637 * is invoked. This method should return a new set of layout params suitable for 4638 * this ViewGroup, possibly by copying the appropriate attributes from the 4639 * specified set of layout params. 4640 * 4641 * @param p The layout parameters to convert into a suitable set of layout parameters 4642 * for this ViewGroup. 4643 * 4644 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4645 * of its descendants 4646 */ 4647 protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 4648 return p; 4649 } 4650 4651 /** 4652 * Returns a set of default layout parameters. These parameters are requested 4653 * when the View passed to {@link #addView(View)} has no layout parameters 4654 * already set. If null is returned, an exception is thrown from addView. 4655 * 4656 * @return a set of default layout parameters or null 4657 */ 4658 protected LayoutParams generateDefaultLayoutParams() { 4659 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 4660 } 4661 4662 /** 4663 * @hide 4664 */ 4665 @Override 4666 protected boolean dispatchConsistencyCheck(int consistency) { 4667 boolean result = super.dispatchConsistencyCheck(consistency); 4668 4669 final int count = mChildrenCount; 4670 final View[] children = mChildren; 4671 for (int i = 0; i < count; i++) { 4672 if (!children[i].dispatchConsistencyCheck(consistency)) result = false; 4673 } 4674 4675 return result; 4676 } 4677 4678 /** 4679 * @hide 4680 */ 4681 @Override 4682 protected boolean onConsistencyCheck(int consistency) { 4683 boolean result = super.onConsistencyCheck(consistency); 4684 4685 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 4686 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 4687 4688 if (checkLayout) { 4689 final int count = mChildrenCount; 4690 final View[] children = mChildren; 4691 for (int i = 0; i < count; i++) { 4692 if (children[i].getParent() != this) { 4693 result = false; 4694 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 4695 "View " + children[i] + " has no parent/a parent that is not " + this); 4696 } 4697 } 4698 } 4699 4700 if (checkDrawing) { 4701 // If this group is dirty, check that the parent is dirty as well 4702 if ((mPrivateFlags & DIRTY_MASK) != 0) { 4703 final ViewParent parent = getParent(); 4704 if (parent != null && !(parent instanceof ViewRootImpl)) { 4705 if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) { 4706 result = false; 4707 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 4708 "ViewGroup " + this + " is dirty but its parent is not: " + this); 4709 } 4710 } 4711 } 4712 } 4713 4714 return result; 4715 } 4716 4717 /** 4718 * {@inheritDoc} 4719 */ 4720 @Override 4721 protected void debug(int depth) { 4722 super.debug(depth); 4723 String output; 4724 4725 if (mFocused != null) { 4726 output = debugIndent(depth); 4727 output += "mFocused"; 4728 Log.d(VIEW_LOG_TAG, output); 4729 } 4730 if (mChildrenCount != 0) { 4731 output = debugIndent(depth); 4732 output += "{"; 4733 Log.d(VIEW_LOG_TAG, output); 4734 } 4735 int count = mChildrenCount; 4736 for (int i = 0; i < count; i++) { 4737 View child = mChildren[i]; 4738 child.debug(depth + 1); 4739 } 4740 4741 if (mChildrenCount != 0) { 4742 output = debugIndent(depth); 4743 output += "}"; 4744 Log.d(VIEW_LOG_TAG, output); 4745 } 4746 } 4747 4748 /** 4749 * Returns the position in the group of the specified child view. 4750 * 4751 * @param child the view for which to get the position 4752 * @return a positive integer representing the position of the view in the 4753 * group, or -1 if the view does not exist in the group 4754 */ 4755 public int indexOfChild(View child) { 4756 final int count = mChildrenCount; 4757 final View[] children = mChildren; 4758 for (int i = 0; i < count; i++) { 4759 if (children[i] == child) { 4760 return i; 4761 } 4762 } 4763 return -1; 4764 } 4765 4766 /** 4767 * Returns the number of children in the group. 4768 * 4769 * @return a positive integer representing the number of children in 4770 * the group 4771 */ 4772 public int getChildCount() { 4773 return mChildrenCount; 4774 } 4775 4776 /** 4777 * Returns the view at the specified position in the group. 4778 * 4779 * @param index the position at which to get the view from 4780 * @return the view at the specified position or null if the position 4781 * does not exist within the group 4782 */ 4783 public View getChildAt(int index) { 4784 if (index < 0 || index >= mChildrenCount) { 4785 return null; 4786 } 4787 return mChildren[index]; 4788 } 4789 4790 /** 4791 * Ask all of the children of this view to measure themselves, taking into 4792 * account both the MeasureSpec requirements for this view and its padding. 4793 * We skip children that are in the GONE state The heavy lifting is done in 4794 * getChildMeasureSpec. 4795 * 4796 * @param widthMeasureSpec The width requirements for this view 4797 * @param heightMeasureSpec The height requirements for this view 4798 */ 4799 protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) { 4800 final int size = mChildrenCount; 4801 final View[] children = mChildren; 4802 for (int i = 0; i < size; ++i) { 4803 final View child = children[i]; 4804 if ((child.mViewFlags & VISIBILITY_MASK) != GONE) { 4805 measureChild(child, widthMeasureSpec, heightMeasureSpec); 4806 } 4807 } 4808 } 4809 4810 /** 4811 * Ask one of the children of this view to measure itself, taking into 4812 * account both the MeasureSpec requirements for this view and its padding. 4813 * The heavy lifting is done in getChildMeasureSpec. 4814 * 4815 * @param child The child to measure 4816 * @param parentWidthMeasureSpec The width requirements for this view 4817 * @param parentHeightMeasureSpec The height requirements for this view 4818 */ 4819 protected void measureChild(View child, int parentWidthMeasureSpec, 4820 int parentHeightMeasureSpec) { 4821 final LayoutParams lp = child.getLayoutParams(); 4822 4823 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4824 mPaddingLeft + mPaddingRight, lp.width); 4825 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4826 mPaddingTop + mPaddingBottom, lp.height); 4827 4828 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4829 } 4830 4831 /** 4832 * Ask one of the children of this view to measure itself, taking into 4833 * account both the MeasureSpec requirements for this view and its padding 4834 * and margins. The child must have MarginLayoutParams The heavy lifting is 4835 * done in getChildMeasureSpec. 4836 * 4837 * @param child The child to measure 4838 * @param parentWidthMeasureSpec The width requirements for this view 4839 * @param widthUsed Extra space that has been used up by the parent 4840 * horizontally (possibly by other children of the parent) 4841 * @param parentHeightMeasureSpec The height requirements for this view 4842 * @param heightUsed Extra space that has been used up by the parent 4843 * vertically (possibly by other children of the parent) 4844 */ 4845 protected void measureChildWithMargins(View child, 4846 int parentWidthMeasureSpec, int widthUsed, 4847 int parentHeightMeasureSpec, int heightUsed) { 4848 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 4849 4850 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4851 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 4852 + widthUsed, lp.width); 4853 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4854 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin 4855 + heightUsed, lp.height); 4856 4857 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4858 } 4859 4860 /** 4861 * Does the hard part of measureChildren: figuring out the MeasureSpec to 4862 * pass to a particular child. This method figures out the right MeasureSpec 4863 * for one dimension (height or width) of one child view. 4864 * 4865 * The goal is to combine information from our MeasureSpec with the 4866 * LayoutParams of the child to get the best possible results. For example, 4867 * if the this view knows its size (because its MeasureSpec has a mode of 4868 * EXACTLY), and the child has indicated in its LayoutParams that it wants 4869 * to be the same size as the parent, the parent should ask the child to 4870 * layout given an exact size. 4871 * 4872 * @param spec The requirements for this view 4873 * @param padding The padding of this view for the current dimension and 4874 * margins, if applicable 4875 * @param childDimension How big the child wants to be in the current 4876 * dimension 4877 * @return a MeasureSpec integer for the child 4878 */ 4879 public static int getChildMeasureSpec(int spec, int padding, int childDimension) { 4880 int specMode = MeasureSpec.getMode(spec); 4881 int specSize = MeasureSpec.getSize(spec); 4882 4883 int size = Math.max(0, specSize - padding); 4884 4885 int resultSize = 0; 4886 int resultMode = 0; 4887 4888 switch (specMode) { 4889 // Parent has imposed an exact size on us 4890 case MeasureSpec.EXACTLY: 4891 if (childDimension >= 0) { 4892 resultSize = childDimension; 4893 resultMode = MeasureSpec.EXACTLY; 4894 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4895 // Child wants to be our size. So be it. 4896 resultSize = size; 4897 resultMode = MeasureSpec.EXACTLY; 4898 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4899 // Child wants to determine its own size. It can't be 4900 // bigger than us. 4901 resultSize = size; 4902 resultMode = MeasureSpec.AT_MOST; 4903 } 4904 break; 4905 4906 // Parent has imposed a maximum size on us 4907 case MeasureSpec.AT_MOST: 4908 if (childDimension >= 0) { 4909 // Child wants a specific size... so be it 4910 resultSize = childDimension; 4911 resultMode = MeasureSpec.EXACTLY; 4912 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4913 // Child wants to be our size, but our size is not fixed. 4914 // Constrain child to not be bigger than us. 4915 resultSize = size; 4916 resultMode = MeasureSpec.AT_MOST; 4917 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4918 // Child wants to determine its own size. It can't be 4919 // bigger than us. 4920 resultSize = size; 4921 resultMode = MeasureSpec.AT_MOST; 4922 } 4923 break; 4924 4925 // Parent asked to see how big we want to be 4926 case MeasureSpec.UNSPECIFIED: 4927 if (childDimension >= 0) { 4928 // Child wants a specific size... let him have it 4929 resultSize = childDimension; 4930 resultMode = MeasureSpec.EXACTLY; 4931 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4932 // Child wants to be our size... find out how big it should 4933 // be 4934 resultSize = 0; 4935 resultMode = MeasureSpec.UNSPECIFIED; 4936 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4937 // Child wants to determine its own size.... find out how 4938 // big it should be 4939 resultSize = 0; 4940 resultMode = MeasureSpec.UNSPECIFIED; 4941 } 4942 break; 4943 } 4944 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 4945 } 4946 4947 4948 /** 4949 * Removes any pending animations for views that have been removed. Call 4950 * this if you don't want animations for exiting views to stack up. 4951 */ 4952 public void clearDisappearingChildren() { 4953 if (mDisappearingChildren != null) { 4954 mDisappearingChildren.clear(); 4955 invalidate(); 4956 } 4957 } 4958 4959 /** 4960 * Add a view which is removed from mChildren but still needs animation 4961 * 4962 * @param v View to add 4963 */ 4964 private void addDisappearingView(View v) { 4965 ArrayList<View> disappearingChildren = mDisappearingChildren; 4966 4967 if (disappearingChildren == null) { 4968 disappearingChildren = mDisappearingChildren = new ArrayList<View>(); 4969 } 4970 4971 disappearingChildren.add(v); 4972 } 4973 4974 /** 4975 * Cleanup a view when its animation is done. This may mean removing it from 4976 * the list of disappearing views. 4977 * 4978 * @param view The view whose animation has finished 4979 * @param animation The animation, cannot be null 4980 */ 4981 void finishAnimatingView(final View view, Animation animation) { 4982 final ArrayList<View> disappearingChildren = mDisappearingChildren; 4983 if (disappearingChildren != null) { 4984 if (disappearingChildren.contains(view)) { 4985 disappearingChildren.remove(view); 4986 4987 if (view.mAttachInfo != null) { 4988 view.dispatchDetachedFromWindow(); 4989 } 4990 4991 view.clearAnimation(); 4992 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4993 } 4994 } 4995 4996 if (animation != null && !animation.getFillAfter()) { 4997 view.clearAnimation(); 4998 } 4999 5000 if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) { 5001 view.onAnimationEnd(); 5002 // Should be performed by onAnimationEnd() but this avoid an infinite loop, 5003 // so we'd rather be safe than sorry 5004 view.mPrivateFlags &= ~ANIMATION_STARTED; 5005 // Draw one more frame after the animation is done 5006 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 5007 } 5008 } 5009 5010 /** 5011 * Utility function called by View during invalidation to determine whether a view that 5012 * is invisible or gone should still be invalidated because it is being transitioned (and 5013 * therefore still needs to be drawn). 5014 */ 5015 boolean isViewTransitioning(View view) { 5016 return (mTransitioningViews != null && mTransitioningViews.contains(view)); 5017 } 5018 5019 /** 5020 * This method tells the ViewGroup that the given View object, which should have this 5021 * ViewGroup as its parent, 5022 * should be kept around (re-displayed when the ViewGroup draws its children) even if it 5023 * is removed from its parent. This allows animations, such as those used by 5024 * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate 5025 * the removal of views. A call to this method should always be accompanied by a later call 5026 * to {@link #endViewTransition(View)}, such as after an animation on the View has finished, 5027 * so that the View finally gets removed. 5028 * 5029 * @param view The View object to be kept visible even if it gets removed from its parent. 5030 */ 5031 public void startViewTransition(View view) { 5032 if (view.mParent == this) { 5033 if (mTransitioningViews == null) { 5034 mTransitioningViews = new ArrayList<View>(); 5035 } 5036 mTransitioningViews.add(view); 5037 } 5038 } 5039 5040 /** 5041 * This method should always be called following an earlier call to 5042 * {@link #startViewTransition(View)}. The given View is finally removed from its parent 5043 * and will no longer be displayed. Note that this method does not perform the functionality 5044 * of removing a view from its parent; it just discontinues the display of a View that 5045 * has previously been removed. 5046 * 5047 * @return view The View object that has been removed but is being kept around in the visible 5048 * hierarchy by an earlier call to {@link #startViewTransition(View)}. 5049 */ 5050 public void endViewTransition(View view) { 5051 if (mTransitioningViews != null) { 5052 mTransitioningViews.remove(view); 5053 final ArrayList<View> disappearingChildren = mDisappearingChildren; 5054 if (disappearingChildren != null && disappearingChildren.contains(view)) { 5055 disappearingChildren.remove(view); 5056 if (mVisibilityChangingChildren != null && 5057 mVisibilityChangingChildren.contains(view)) { 5058 mVisibilityChangingChildren.remove(view); 5059 } else { 5060 if (view.mAttachInfo != null) { 5061 view.dispatchDetachedFromWindow(); 5062 } 5063 if (view.mParent != null) { 5064 view.mParent = null; 5065 } 5066 } 5067 invalidate(); 5068 } 5069 } 5070 } 5071 5072 private LayoutTransition.TransitionListener mLayoutTransitionListener = 5073 new LayoutTransition.TransitionListener() { 5074 @Override 5075 public void startTransition(LayoutTransition transition, ViewGroup container, 5076 View view, int transitionType) { 5077 // We only care about disappearing items, since we need special logic to keep 5078 // those items visible after they've been 'removed' 5079 if (transitionType == LayoutTransition.DISAPPEARING) { 5080 startViewTransition(view); 5081 } 5082 } 5083 5084 @Override 5085 public void endTransition(LayoutTransition transition, ViewGroup container, 5086 View view, int transitionType) { 5087 if (mLayoutSuppressed && !transition.isChangingLayout()) { 5088 requestLayout(); 5089 mLayoutSuppressed = false; 5090 } 5091 if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) { 5092 endViewTransition(view); 5093 } 5094 } 5095 }; 5096 5097 /** 5098 * {@inheritDoc} 5099 */ 5100 @Override 5101 public boolean gatherTransparentRegion(Region region) { 5102 // If no transparent regions requested, we are always opaque. 5103 final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0; 5104 if (meOpaque && region == null) { 5105 // The caller doesn't care about the region, so stop now. 5106 return true; 5107 } 5108 super.gatherTransparentRegion(region); 5109 final View[] children = mChildren; 5110 final int count = mChildrenCount; 5111 boolean noneOfTheChildrenAreTransparent = true; 5112 for (int i = 0; i < count; i++) { 5113 final View child = children[i]; 5114 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 5115 if (!child.gatherTransparentRegion(region)) { 5116 noneOfTheChildrenAreTransparent = false; 5117 } 5118 } 5119 } 5120 return meOpaque || noneOfTheChildrenAreTransparent; 5121 } 5122 5123 /** 5124 * {@inheritDoc} 5125 */ 5126 public void requestTransparentRegion(View child) { 5127 if (child != null) { 5128 child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS; 5129 if (mParent != null) { 5130 mParent.requestTransparentRegion(this); 5131 } 5132 } 5133 } 5134 5135 5136 @Override 5137 protected boolean fitSystemWindows(Rect insets) { 5138 boolean done = super.fitSystemWindows(insets); 5139 if (!done) { 5140 final int count = mChildrenCount; 5141 final View[] children = mChildren; 5142 for (int i = 0; i < count; i++) { 5143 done = children[i].fitSystemWindows(insets); 5144 if (done) { 5145 break; 5146 } 5147 } 5148 } 5149 return done; 5150 } 5151 5152 /** 5153 * Returns the animation listener to which layout animation events are 5154 * sent. 5155 * 5156 * @return an {@link android.view.animation.Animation.AnimationListener} 5157 */ 5158 public Animation.AnimationListener getLayoutAnimationListener() { 5159 return mAnimationListener; 5160 } 5161 5162 @Override 5163 protected void drawableStateChanged() { 5164 super.drawableStateChanged(); 5165 5166 if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) { 5167 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 5168 throw new IllegalStateException("addStateFromChildren cannot be enabled if a" 5169 + " child has duplicateParentState set to true"); 5170 } 5171 5172 final View[] children = mChildren; 5173 final int count = mChildrenCount; 5174 5175 for (int i = 0; i < count; i++) { 5176 final View child = children[i]; 5177 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) { 5178 child.refreshDrawableState(); 5179 } 5180 } 5181 } 5182 } 5183 5184 @Override 5185 public void jumpDrawablesToCurrentState() { 5186 super.jumpDrawablesToCurrentState(); 5187 final View[] children = mChildren; 5188 final int count = mChildrenCount; 5189 for (int i = 0; i < count; i++) { 5190 children[i].jumpDrawablesToCurrentState(); 5191 } 5192 } 5193 5194 @Override 5195 protected int[] onCreateDrawableState(int extraSpace) { 5196 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) { 5197 return super.onCreateDrawableState(extraSpace); 5198 } 5199 5200 int need = 0; 5201 int n = getChildCount(); 5202 for (int i = 0; i < n; i++) { 5203 int[] childState = getChildAt(i).getDrawableState(); 5204 5205 if (childState != null) { 5206 need += childState.length; 5207 } 5208 } 5209 5210 int[] state = super.onCreateDrawableState(extraSpace + need); 5211 5212 for (int i = 0; i < n; i++) { 5213 int[] childState = getChildAt(i).getDrawableState(); 5214 5215 if (childState != null) { 5216 state = mergeDrawableStates(state, childState); 5217 } 5218 } 5219 5220 return state; 5221 } 5222 5223 /** 5224 * Sets whether this ViewGroup's drawable states also include 5225 * its children's drawable states. This is used, for example, to 5226 * make a group appear to be focused when its child EditText or button 5227 * is focused. 5228 */ 5229 public void setAddStatesFromChildren(boolean addsStates) { 5230 if (addsStates) { 5231 mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN; 5232 } else { 5233 mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN; 5234 } 5235 5236 refreshDrawableState(); 5237 } 5238 5239 /** 5240 * Returns whether this ViewGroup's drawable states also include 5241 * its children's drawable states. This is used, for example, to 5242 * make a group appear to be focused when its child EditText or button 5243 * is focused. 5244 */ 5245 public boolean addStatesFromChildren() { 5246 return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0; 5247 } 5248 5249 /** 5250 * If {link #addStatesFromChildren} is true, refreshes this group's 5251 * drawable state (to include the states from its children). 5252 */ 5253 public void childDrawableStateChanged(View child) { 5254 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 5255 refreshDrawableState(); 5256 } 5257 } 5258 5259 /** 5260 * Specifies the animation listener to which layout animation events must 5261 * be sent. Only 5262 * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)} 5263 * and 5264 * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)} 5265 * are invoked. 5266 * 5267 * @param animationListener the layout animation listener 5268 */ 5269 public void setLayoutAnimationListener(Animation.AnimationListener animationListener) { 5270 mAnimationListener = animationListener; 5271 } 5272 5273 /** 5274 * This method is called by LayoutTransition when there are 'changing' animations that need 5275 * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who 5276 * starts all pending transitions prior to the drawing phase in the current traversal. 5277 * 5278 * @param transition The LayoutTransition to be started on the next traversal. 5279 * 5280 * @hide 5281 */ 5282 public void requestTransitionStart(LayoutTransition transition) { 5283 ViewRootImpl viewAncestor = getViewRootImpl(); 5284 if (viewAncestor != null) { 5285 viewAncestor.requestTransitionStart(transition); 5286 } 5287 } 5288 5289 @Override 5290 public void onResolvedLayoutDirectionReset() { 5291 // Take care of resetting the children resolution too 5292 final int count = getChildCount(); 5293 for (int i = 0; i < count; i++) { 5294 final View child = getChildAt(i); 5295 if (child.getLayoutDirection() == LAYOUT_DIRECTION_INHERIT) { 5296 child.resetResolvedLayoutDirection(); 5297 } 5298 } 5299 } 5300 5301 @Override 5302 public void onResolvedTextDirectionReset() { 5303 // Take care of resetting the children resolution too 5304 final int count = getChildCount(); 5305 for (int i = 0; i < count; i++) { 5306 final View child = getChildAt(i); 5307 if (child.getTextDirection() == TEXT_DIRECTION_INHERIT) { 5308 child.resetResolvedTextDirection(); 5309 } 5310 } 5311 } 5312 5313 @Override 5314 public void onResolvedTextAlignmentReset() { 5315 // Take care of resetting the children resolution too 5316 final int count = getChildCount(); 5317 for (int i = 0; i < count; i++) { 5318 final View child = getChildAt(i); 5319 if (child.getTextAlignment() == TEXT_ALIGNMENT_INHERIT) { 5320 child.resetResolvedTextAlignment(); 5321 } 5322 } 5323 } 5324 5325 /** 5326 * Return true if the pressed state should be delayed for children or descendants of this 5327 * ViewGroup. Generally, this should be done for containers that can scroll, such as a List. 5328 * This prevents the pressed state from appearing when the user is actually trying to scroll 5329 * the content. 5330 * 5331 * The default implementation returns true for compatibility reasons. Subclasses that do 5332 * not scroll should generally override this method and return false. 5333 */ 5334 public boolean shouldDelayChildPressedState() { 5335 return true; 5336 } 5337 5338 /** @hide */ 5339 protected void onSetLayoutParams(View child, LayoutParams layoutParams) { 5340 } 5341 5342 /** 5343 * LayoutParams are used by views to tell their parents how they want to be 5344 * laid out. See 5345 * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes} 5346 * for a list of all child view attributes that this class supports. 5347 * 5348 * <p> 5349 * The base LayoutParams class just describes how big the view wants to be 5350 * for both width and height. For each dimension, it can specify one of: 5351 * <ul> 5352 * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which 5353 * means that the view wants to be as big as its parent (minus padding) 5354 * <li> WRAP_CONTENT, which means that the view wants to be just big enough 5355 * to enclose its content (plus padding) 5356 * <li> an exact number 5357 * </ul> 5358 * There are subclasses of LayoutParams for different subclasses of 5359 * ViewGroup. For example, AbsoluteLayout has its own subclass of 5360 * LayoutParams which adds an X and Y value.</p> 5361 * 5362 * <div class="special reference"> 5363 * <h3>Developer Guides</h3> 5364 * <p>For more information about creating user interface layouts, read the 5365 * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer 5366 * guide.</p></div> 5367 * 5368 * @attr ref android.R.styleable#ViewGroup_Layout_layout_height 5369 * @attr ref android.R.styleable#ViewGroup_Layout_layout_width 5370 */ 5371 public static class LayoutParams { 5372 /** 5373 * Special value for the height or width requested by a View. 5374 * FILL_PARENT means that the view wants to be as big as its parent, 5375 * minus the parent's padding, if any. This value is deprecated 5376 * starting in API Level 8 and replaced by {@link #MATCH_PARENT}. 5377 */ 5378 @SuppressWarnings({"UnusedDeclaration"}) 5379 @Deprecated 5380 public static final int FILL_PARENT = -1; 5381 5382 /** 5383 * Special value for the height or width requested by a View. 5384 * MATCH_PARENT means that the view wants to be as big as its parent, 5385 * minus the parent's padding, if any. Introduced in API Level 8. 5386 */ 5387 public static final int MATCH_PARENT = -1; 5388 5389 /** 5390 * Special value for the height or width requested by a View. 5391 * WRAP_CONTENT means that the view wants to be just large enough to fit 5392 * its own internal content, taking its own padding into account. 5393 */ 5394 public static final int WRAP_CONTENT = -2; 5395 5396 /** 5397 * Information about how wide the view wants to be. Can be one of the 5398 * constants FILL_PARENT (replaced by MATCH_PARENT , 5399 * in API Level 8) or WRAP_CONTENT. or an exact size. 5400 */ 5401 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5402 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5403 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5404 }) 5405 public int width; 5406 5407 /** 5408 * Information about how tall the view wants to be. Can be one of the 5409 * constants FILL_PARENT (replaced by MATCH_PARENT , 5410 * in API Level 8) or WRAP_CONTENT. or an exact size. 5411 */ 5412 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5413 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5414 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5415 }) 5416 public int height; 5417 5418 /** 5419 * Used to animate layouts. 5420 */ 5421 public LayoutAnimationController.AnimationParameters layoutAnimationParameters; 5422 5423 /** 5424 * Creates a new set of layout parameters. The values are extracted from 5425 * the supplied attributes set and context. The XML attributes mapped 5426 * to this set of layout parameters are: 5427 * 5428 * <ul> 5429 * <li><code>layout_width</code>: the width, either an exact value, 5430 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5431 * {@link #MATCH_PARENT} in API Level 8)</li> 5432 * <li><code>layout_height</code>: the height, either an exact value, 5433 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5434 * {@link #MATCH_PARENT} in API Level 8)</li> 5435 * </ul> 5436 * 5437 * @param c the application environment 5438 * @param attrs the set of attributes from which to extract the layout 5439 * parameters' values 5440 */ 5441 public LayoutParams(Context c, AttributeSet attrs) { 5442 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout); 5443 setBaseAttributes(a, 5444 R.styleable.ViewGroup_Layout_layout_width, 5445 R.styleable.ViewGroup_Layout_layout_height); 5446 a.recycle(); 5447 } 5448 5449 /** 5450 * Creates a new set of layout parameters with the specified width 5451 * and height. 5452 * 5453 * @param width the width, either {@link #WRAP_CONTENT}, 5454 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5455 * API Level 8), or a fixed size in pixels 5456 * @param height the height, either {@link #WRAP_CONTENT}, 5457 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5458 * API Level 8), or a fixed size in pixels 5459 */ 5460 public LayoutParams(int width, int height) { 5461 this.width = width; 5462 this.height = height; 5463 } 5464 5465 /** 5466 * Copy constructor. Clones the width and height values of the source. 5467 * 5468 * @param source The layout params to copy from. 5469 */ 5470 public LayoutParams(LayoutParams source) { 5471 this.width = source.width; 5472 this.height = source.height; 5473 } 5474 5475 /** 5476 * Used internally by MarginLayoutParams. 5477 * @hide 5478 */ 5479 LayoutParams() { 5480 } 5481 5482 /** 5483 * Extracts the layout parameters from the supplied attributes. 5484 * 5485 * @param a the style attributes to extract the parameters from 5486 * @param widthAttr the identifier of the width attribute 5487 * @param heightAttr the identifier of the height attribute 5488 */ 5489 protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { 5490 width = a.getLayoutDimension(widthAttr, "layout_width"); 5491 height = a.getLayoutDimension(heightAttr, "layout_height"); 5492 } 5493 5494 /** 5495 * Resolve layout parameters depending on the layout direction. Subclasses that care about 5496 * layoutDirection changes should override this method. The default implementation does 5497 * nothing. 5498 * 5499 * @param layoutDirection the direction of the layout 5500 * 5501 * {@link View#LAYOUT_DIRECTION_LTR} 5502 * {@link View#LAYOUT_DIRECTION_RTL} 5503 */ 5504 public void onResolveLayoutDirection(int layoutDirection) { 5505 } 5506 5507 /** 5508 * Returns a String representation of this set of layout parameters. 5509 * 5510 * @param output the String to prepend to the internal representation 5511 * @return a String with the following format: output + 5512 * "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }" 5513 * 5514 * @hide 5515 */ 5516 public String debug(String output) { 5517 return output + "ViewGroup.LayoutParams={ width=" 5518 + sizeToString(width) + ", height=" + sizeToString(height) + " }"; 5519 } 5520 5521 /** 5522 * Use {@code canvas} to draw suitable debugging annotations for these LayoutParameters. 5523 * 5524 * @param view the view that contains these layout parameters 5525 * @param canvas the canvas on which to draw 5526 * 5527 * @hide 5528 */ 5529 public void onDebugDraw(View view, Canvas canvas) { 5530 } 5531 5532 /** 5533 * Converts the specified size to a readable String. 5534 * 5535 * @param size the size to convert 5536 * @return a String instance representing the supplied size 5537 * 5538 * @hide 5539 */ 5540 protected static String sizeToString(int size) { 5541 if (size == WRAP_CONTENT) { 5542 return "wrap-content"; 5543 } 5544 if (size == MATCH_PARENT) { 5545 return "match-parent"; 5546 } 5547 return String.valueOf(size); 5548 } 5549 } 5550 5551 /** 5552 * Per-child layout information for layouts that support margins. 5553 * See 5554 * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes} 5555 * for a list of all child view attributes that this class supports. 5556 */ 5557 public static class MarginLayoutParams extends ViewGroup.LayoutParams { 5558 /** 5559 * The left margin in pixels of the child. 5560 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5561 * to this field. 5562 */ 5563 @ViewDebug.ExportedProperty(category = "layout") 5564 public int leftMargin; 5565 5566 /** 5567 * The top margin in pixels of the child. 5568 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5569 * to this field. 5570 */ 5571 @ViewDebug.ExportedProperty(category = "layout") 5572 public int topMargin; 5573 5574 /** 5575 * The right margin in pixels of the child. 5576 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5577 * to this field. 5578 */ 5579 @ViewDebug.ExportedProperty(category = "layout") 5580 public int rightMargin; 5581 5582 /** 5583 * The bottom margin in pixels of the child. 5584 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5585 * to this field. 5586 */ 5587 @ViewDebug.ExportedProperty(category = "layout") 5588 public int bottomMargin; 5589 5590 /** 5591 * The start margin in pixels of the child. 5592 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5593 * to this field. 5594 */ 5595 @ViewDebug.ExportedProperty(category = "layout") 5596 public int startMargin = DEFAULT_RELATIVE; 5597 5598 /** 5599 * The end margin in pixels of the child. 5600 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5601 * to this field. 5602 */ 5603 @ViewDebug.ExportedProperty(category = "layout") 5604 public int endMargin = DEFAULT_RELATIVE; 5605 5606 /** 5607 * The default start and end margin. 5608 */ 5609 static private final int DEFAULT_RELATIVE = Integer.MIN_VALUE; 5610 5611 /** 5612 * Creates a new set of layout parameters. The values are extracted from 5613 * the supplied attributes set and context. 5614 * 5615 * @param c the application environment 5616 * @param attrs the set of attributes from which to extract the layout 5617 * parameters' values 5618 */ 5619 public MarginLayoutParams(Context c, AttributeSet attrs) { 5620 super(); 5621 5622 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout); 5623 setBaseAttributes(a, 5624 R.styleable.ViewGroup_MarginLayout_layout_width, 5625 R.styleable.ViewGroup_MarginLayout_layout_height); 5626 5627 int margin = a.getDimensionPixelSize( 5628 com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1); 5629 if (margin >= 0) { 5630 leftMargin = margin; 5631 topMargin = margin; 5632 rightMargin= margin; 5633 bottomMargin = margin; 5634 } else { 5635 leftMargin = a.getDimensionPixelSize( 5636 R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0); 5637 topMargin = a.getDimensionPixelSize( 5638 R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0); 5639 rightMargin = a.getDimensionPixelSize( 5640 R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0); 5641 bottomMargin = a.getDimensionPixelSize( 5642 R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0); 5643 startMargin = a.getDimensionPixelSize( 5644 R.styleable.ViewGroup_MarginLayout_layout_marginStart, DEFAULT_RELATIVE); 5645 endMargin = a.getDimensionPixelSize( 5646 R.styleable.ViewGroup_MarginLayout_layout_marginEnd, DEFAULT_RELATIVE); 5647 } 5648 5649 a.recycle(); 5650 } 5651 5652 /** 5653 * {@inheritDoc} 5654 */ 5655 public MarginLayoutParams(int width, int height) { 5656 super(width, height); 5657 } 5658 5659 /** 5660 * Copy constructor. Clones the width, height and margin values of the source. 5661 * 5662 * @param source The layout params to copy from. 5663 */ 5664 public MarginLayoutParams(MarginLayoutParams source) { 5665 this.width = source.width; 5666 this.height = source.height; 5667 5668 this.leftMargin = source.leftMargin; 5669 this.topMargin = source.topMargin; 5670 this.rightMargin = source.rightMargin; 5671 this.bottomMargin = source.bottomMargin; 5672 this.startMargin = source.startMargin; 5673 this.endMargin = source.endMargin; 5674 } 5675 5676 /** 5677 * {@inheritDoc} 5678 */ 5679 public MarginLayoutParams(LayoutParams source) { 5680 super(source); 5681 } 5682 5683 /** 5684 * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs 5685 * to be done so that the new margins are taken into account. Left and right margins may be 5686 * overriden by {@link android.view.View#requestLayout()} depending on layout direction. 5687 * 5688 * @param left the left margin size 5689 * @param top the top margin size 5690 * @param right the right margin size 5691 * @param bottom the bottom margin size 5692 * 5693 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft 5694 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 5695 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight 5696 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 5697 */ 5698 public void setMargins(int left, int top, int right, int bottom) { 5699 leftMargin = left; 5700 topMargin = top; 5701 rightMargin = right; 5702 bottomMargin = bottom; 5703 } 5704 5705 /** 5706 * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()} 5707 * needs to be done so that the new relative margins are taken into account. Left and right 5708 * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout 5709 * direction. 5710 * 5711 * @param start the start margin size 5712 * @param top the top margin size 5713 * @param end the right margin size 5714 * @param bottom the bottom margin size 5715 * 5716 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5717 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 5718 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5719 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 5720 * 5721 * @hide 5722 */ 5723 public void setMarginsRelative(int start, int top, int end, int bottom) { 5724 startMargin = start; 5725 topMargin = top; 5726 endMargin = end; 5727 bottomMargin = bottom; 5728 } 5729 5730 /** 5731 * Returns the start margin in pixels. 5732 * 5733 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5734 * 5735 * @return the start margin in pixels. 5736 */ 5737 public int getMarginStart() { 5738 return startMargin; 5739 } 5740 5741 /** 5742 * Returns the end margin in pixels. 5743 * 5744 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5745 * 5746 * @return the end margin in pixels. 5747 */ 5748 public int getMarginEnd() { 5749 return endMargin; 5750 } 5751 5752 /** 5753 * Check if margins are relative. 5754 * 5755 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5756 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5757 * 5758 * @return true if either marginStart or marginEnd has been set 5759 */ 5760 public boolean isMarginRelative() { 5761 return (startMargin != DEFAULT_RELATIVE) || (endMargin != DEFAULT_RELATIVE); 5762 } 5763 5764 /** 5765 * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins 5766 * may be overridden depending on layout direction. 5767 */ 5768 @Override 5769 public void onResolveLayoutDirection(int layoutDirection) { 5770 switch(layoutDirection) { 5771 case View.LAYOUT_DIRECTION_RTL: 5772 leftMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : leftMargin; 5773 rightMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : rightMargin; 5774 break; 5775 case View.LAYOUT_DIRECTION_LTR: 5776 default: 5777 leftMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : leftMargin; 5778 rightMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : rightMargin; 5779 break; 5780 } 5781 } 5782 5783 /** 5784 * @hide 5785 */ 5786 @Override 5787 public void onDebugDraw(View view, Canvas canvas) { 5788 drawRect(canvas, 5789 view.getLeft() - leftMargin, 5790 view.getTop() - topMargin, 5791 view.getRight() + rightMargin, 5792 view.getBottom() + bottomMargin, Color.MAGENTA); 5793 } 5794 } 5795 5796 /* Describes a touched view and the ids of the pointers that it has captured. 5797 * 5798 * This code assumes that pointer ids are always in the range 0..31 such that 5799 * it can use a bitfield to track which pointer ids are present. 5800 * As it happens, the lower layers of the input dispatch pipeline also use the 5801 * same trick so the assumption should be safe here... 5802 */ 5803 private static final class TouchTarget { 5804 private static final int MAX_RECYCLED = 32; 5805 private static final Object sRecycleLock = new Object(); 5806 private static TouchTarget sRecycleBin; 5807 private static int sRecycledCount; 5808 5809 public static final int ALL_POINTER_IDS = -1; // all ones 5810 5811 // The touched child view. 5812 public View child; 5813 5814 // The combined bit mask of pointer ids for all pointers captured by the target. 5815 public int pointerIdBits; 5816 5817 // The next target in the target list. 5818 public TouchTarget next; 5819 5820 private TouchTarget() { 5821 } 5822 5823 public static TouchTarget obtain(View child, int pointerIdBits) { 5824 final TouchTarget target; 5825 synchronized (sRecycleLock) { 5826 if (sRecycleBin == null) { 5827 target = new TouchTarget(); 5828 } else { 5829 target = sRecycleBin; 5830 sRecycleBin = target.next; 5831 sRecycledCount--; 5832 target.next = null; 5833 } 5834 } 5835 target.child = child; 5836 target.pointerIdBits = pointerIdBits; 5837 return target; 5838 } 5839 5840 public void recycle() { 5841 synchronized (sRecycleLock) { 5842 if (sRecycledCount < MAX_RECYCLED) { 5843 next = sRecycleBin; 5844 sRecycleBin = this; 5845 sRecycledCount += 1; 5846 } else { 5847 next = null; 5848 } 5849 child = null; 5850 } 5851 } 5852 } 5853 5854 /* Describes a hovered view. */ 5855 private static final class HoverTarget { 5856 private static final int MAX_RECYCLED = 32; 5857 private static final Object sRecycleLock = new Object(); 5858 private static HoverTarget sRecycleBin; 5859 private static int sRecycledCount; 5860 5861 // The hovered child view. 5862 public View child; 5863 5864 // The next target in the target list. 5865 public HoverTarget next; 5866 5867 private HoverTarget() { 5868 } 5869 5870 public static HoverTarget obtain(View child) { 5871 final HoverTarget target; 5872 synchronized (sRecycleLock) { 5873 if (sRecycleBin == null) { 5874 target = new HoverTarget(); 5875 } else { 5876 target = sRecycleBin; 5877 sRecycleBin = target.next; 5878 sRecycledCount--; 5879 target.next = null; 5880 } 5881 } 5882 target.child = child; 5883 return target; 5884 } 5885 5886 public void recycle() { 5887 synchronized (sRecycleLock) { 5888 if (sRecycledCount < MAX_RECYCLED) { 5889 next = sRecycleBin; 5890 sRecycleBin = this; 5891 sRecycledCount += 1; 5892 } else { 5893 next = null; 5894 } 5895 child = null; 5896 } 5897 } 5898 } 5899 5900 /** 5901 * Pooled class that orderes the children of a ViewGroup from start 5902 * to end based on how they are laid out and the layout direction. 5903 */ 5904 static class ChildListForAccessibility { 5905 5906 private static final int MAX_POOL_SIZE = 32; 5907 5908 private static final Object sPoolLock = new Object(); 5909 5910 private static ChildListForAccessibility sPool; 5911 5912 private static int sPoolSize; 5913 5914 private boolean mIsPooled; 5915 5916 private ChildListForAccessibility mNext; 5917 5918 private final ArrayList<View> mChildren = new ArrayList<View>(); 5919 5920 private final ArrayList<ViewLocationHolder> mHolders = new ArrayList<ViewLocationHolder>(); 5921 5922 public static ChildListForAccessibility obtain(ViewGroup parent, boolean sort) { 5923 ChildListForAccessibility list = null; 5924 synchronized (sPoolLock) { 5925 if (sPool != null) { 5926 list = sPool; 5927 sPool = list.mNext; 5928 list.mNext = null; 5929 list.mIsPooled = false; 5930 sPoolSize--; 5931 } else { 5932 list = new ChildListForAccessibility(); 5933 } 5934 list.init(parent, sort); 5935 return list; 5936 } 5937 } 5938 5939 public void recycle() { 5940 if (mIsPooled) { 5941 throw new IllegalStateException("Instance already recycled."); 5942 } 5943 clear(); 5944 synchronized (sPoolLock) { 5945 if (sPoolSize < MAX_POOL_SIZE) { 5946 mNext = sPool; 5947 mIsPooled = true; 5948 sPool = this; 5949 sPoolSize++; 5950 } 5951 } 5952 } 5953 5954 public int getChildCount() { 5955 return mChildren.size(); 5956 } 5957 5958 public View getChildAt(int index) { 5959 return mChildren.get(index); 5960 } 5961 5962 public int getChildIndex(View child) { 5963 return mChildren.indexOf(child); 5964 } 5965 5966 private void init(ViewGroup parent, boolean sort) { 5967 ArrayList<View> children = mChildren; 5968 final int childCount = parent.getChildCount(); 5969 for (int i = 0; i < childCount; i++) { 5970 View child = parent.getChildAt(i); 5971 children.add(child); 5972 } 5973 if (sort) { 5974 ArrayList<ViewLocationHolder> holders = mHolders; 5975 for (int i = 0; i < childCount; i++) { 5976 View child = children.get(i); 5977 ViewLocationHolder holder = ViewLocationHolder.obtain(parent, child); 5978 holders.add(holder); 5979 } 5980 Collections.sort(holders); 5981 for (int i = 0; i < childCount; i++) { 5982 ViewLocationHolder holder = holders.get(i); 5983 children.set(i, holder.mView); 5984 holder.recycle(); 5985 } 5986 holders.clear(); 5987 } 5988 } 5989 5990 private void clear() { 5991 mChildren.clear(); 5992 } 5993 } 5994 5995 /** 5996 * Pooled class that holds a View and its location with respect to 5997 * a specified root. This enables sorting of views based on their 5998 * coordinates without recomputing the position relative to the root 5999 * on every comparison. 6000 */ 6001 static class ViewLocationHolder implements Comparable<ViewLocationHolder> { 6002 6003 private static final int MAX_POOL_SIZE = 32; 6004 6005 private static final Object sPoolLock = new Object(); 6006 6007 private static ViewLocationHolder sPool; 6008 6009 private static int sPoolSize; 6010 6011 private boolean mIsPooled; 6012 6013 private ViewLocationHolder mNext; 6014 6015 private final Rect mLocation = new Rect(); 6016 6017 public View mView; 6018 6019 private int mLayoutDirection; 6020 6021 public static ViewLocationHolder obtain(ViewGroup root, View view) { 6022 ViewLocationHolder holder = null; 6023 synchronized (sPoolLock) { 6024 if (sPool != null) { 6025 holder = sPool; 6026 sPool = holder.mNext; 6027 holder.mNext = null; 6028 holder.mIsPooled = false; 6029 sPoolSize--; 6030 } else { 6031 holder = new ViewLocationHolder(); 6032 } 6033 holder.init(root, view); 6034 return holder; 6035 } 6036 } 6037 6038 public void recycle() { 6039 if (mIsPooled) { 6040 throw new IllegalStateException("Instance already recycled."); 6041 } 6042 clear(); 6043 synchronized (sPoolLock) { 6044 if (sPoolSize < MAX_POOL_SIZE) { 6045 mNext = sPool; 6046 mIsPooled = true; 6047 sPool = this; 6048 sPoolSize++; 6049 } 6050 } 6051 } 6052 6053 @Override 6054 public int compareTo(ViewLocationHolder another) { 6055 // This instance is greater than an invalid argument. 6056 if (another == null) { 6057 return 1; 6058 } 6059 if (getClass() != another.getClass()) { 6060 return 1; 6061 } 6062 // First is above second. 6063 if (mLocation.bottom - another.mLocation.top <= 0) { 6064 return -1; 6065 } 6066 // First is below second. 6067 if (mLocation.top - another.mLocation.bottom >= 0) { 6068 return 1; 6069 } 6070 // LTR 6071 if (mLayoutDirection == LAYOUT_DIRECTION_LTR) { 6072 final int leftDifference = mLocation.left - another.mLocation.left; 6073 // First more to the left than second. 6074 if (leftDifference != 0) { 6075 return leftDifference; 6076 } 6077 } else { // RTL 6078 final int rightDifference = mLocation.right - another.mLocation.right; 6079 // First more to the right than second. 6080 if (rightDifference != 0) { 6081 return -rightDifference; 6082 } 6083 } 6084 // Break tie by top. 6085 final int topDiference = mLocation.top - another.mLocation.top; 6086 if (topDiference != 0) { 6087 return topDiference; 6088 } 6089 // Break tie by height. 6090 final int heightDiference = mLocation.height() - another.mLocation.height(); 6091 if (heightDiference != 0) { 6092 return -heightDiference; 6093 } 6094 // Break tie by width. 6095 final int widthDiference = mLocation.width() - another.mLocation.width(); 6096 if (widthDiference != 0) { 6097 return -widthDiference; 6098 } 6099 // Just break the tie somehow. The accessibliity ids are unique 6100 // and stable, hence this is deterministic tie breaking. 6101 return mView.getAccessibilityViewId() - another.mView.getAccessibilityViewId(); 6102 } 6103 6104 private void init(ViewGroup root, View view) { 6105 Rect viewLocation = mLocation; 6106 view.getDrawingRect(viewLocation); 6107 root.offsetDescendantRectToMyCoords(view, viewLocation); 6108 mView = view; 6109 mLayoutDirection = root.getResolvedLayoutDirection(); 6110 } 6111 6112 private void clear() { 6113 mView = null; 6114 mLocation.set(0, 0, 0, 0); 6115 } 6116 } 6117 6118 private static Paint getDebugPaint() { 6119 if (sDebugPaint == null) { 6120 sDebugPaint = new Paint(); 6121 sDebugPaint.setAntiAlias(false); 6122 } 6123 return sDebugPaint; 6124 } 6125 6126 private static float[] getDebugLines(int x1, int y1, int x2, int y2) { 6127 if (sDebugLines== null) { 6128 sDebugLines = new float[16]; 6129 } 6130 6131 x2--; 6132 y2--; 6133 6134 sDebugLines[0] = x1; 6135 sDebugLines[1] = y1; 6136 sDebugLines[2] = x2; 6137 sDebugLines[3] = y1; 6138 6139 sDebugLines[4] = x2; 6140 sDebugLines[5] = y1; 6141 sDebugLines[6] = x2; 6142 sDebugLines[7] = y2 + 1; 6143 6144 sDebugLines[8] = x2 + 1; 6145 sDebugLines[9] = y2; 6146 sDebugLines[10] = x1; 6147 sDebugLines[11] = y2; 6148 6149 sDebugLines[12] = x1; 6150 sDebugLines[13] = y2; 6151 sDebugLines[14] = x1; 6152 sDebugLines[15] = y1; 6153 6154 return sDebugLines; 6155 } 6156} 6157