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