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