ViewGroup.java revision 7dd4a536a125d5e9573e82c39581bf9ee3922424
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 if (mTransition != null) { 4211 mTransition.layoutChange(this); 4212 } 4213 super.layout(l, t, r, b); 4214 } else { 4215 // record the fact that we noop'd it; request layout when transition finishes 4216 mLayoutSuppressed = true; 4217 } 4218 } 4219 4220 /** 4221 * {@inheritDoc} 4222 */ 4223 @Override 4224 protected abstract void onLayout(boolean changed, 4225 int l, int t, int r, int b); 4226 4227 /** 4228 * Indicates whether the view group has the ability to animate its children 4229 * after the first layout. 4230 * 4231 * @return true if the children can be animated, false otherwise 4232 */ 4233 protected boolean canAnimate() { 4234 return mLayoutAnimationController != null; 4235 } 4236 4237 /** 4238 * Runs the layout animation. Calling this method triggers a relayout of 4239 * this view group. 4240 */ 4241 public void startLayoutAnimation() { 4242 if (mLayoutAnimationController != null) { 4243 mGroupFlags |= FLAG_RUN_ANIMATION; 4244 requestLayout(); 4245 } 4246 } 4247 4248 /** 4249 * Schedules the layout animation to be played after the next layout pass 4250 * of this view group. This can be used to restart the layout animation 4251 * when the content of the view group changes or when the activity is 4252 * paused and resumed. 4253 */ 4254 public void scheduleLayoutAnimation() { 4255 mGroupFlags |= FLAG_RUN_ANIMATION; 4256 } 4257 4258 /** 4259 * Sets the layout animation controller used to animate the group's 4260 * children after the first layout. 4261 * 4262 * @param controller the animation controller 4263 */ 4264 public void setLayoutAnimation(LayoutAnimationController controller) { 4265 mLayoutAnimationController = controller; 4266 if (mLayoutAnimationController != null) { 4267 mGroupFlags |= FLAG_RUN_ANIMATION; 4268 } 4269 } 4270 4271 /** 4272 * Returns the layout animation controller used to animate the group's 4273 * children. 4274 * 4275 * @return the current animation controller 4276 */ 4277 public LayoutAnimationController getLayoutAnimation() { 4278 return mLayoutAnimationController; 4279 } 4280 4281 /** 4282 * Indicates whether the children's drawing cache is used during a layout 4283 * animation. By default, the drawing cache is enabled but this will prevent 4284 * nested layout animations from working. To nest animations, you must disable 4285 * the cache. 4286 * 4287 * @return true if the animation cache is enabled, false otherwise 4288 * 4289 * @see #setAnimationCacheEnabled(boolean) 4290 * @see View#setDrawingCacheEnabled(boolean) 4291 */ 4292 @ViewDebug.ExportedProperty 4293 public boolean isAnimationCacheEnabled() { 4294 return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE; 4295 } 4296 4297 /** 4298 * Enables or disables the children's drawing cache during a layout animation. 4299 * By default, the drawing cache is enabled but this will prevent nested 4300 * layout animations from working. To nest animations, you must disable the 4301 * cache. 4302 * 4303 * @param enabled true to enable the animation cache, false otherwise 4304 * 4305 * @see #isAnimationCacheEnabled() 4306 * @see View#setDrawingCacheEnabled(boolean) 4307 */ 4308 public void setAnimationCacheEnabled(boolean enabled) { 4309 setBooleanFlag(FLAG_ANIMATION_CACHE, enabled); 4310 } 4311 4312 /** 4313 * Indicates whether this ViewGroup will always try to draw its children using their 4314 * drawing cache. By default this property is enabled. 4315 * 4316 * @return true if the animation cache is enabled, false otherwise 4317 * 4318 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4319 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4320 * @see View#setDrawingCacheEnabled(boolean) 4321 */ 4322 @ViewDebug.ExportedProperty(category = "drawing") 4323 public boolean isAlwaysDrawnWithCacheEnabled() { 4324 return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE; 4325 } 4326 4327 /** 4328 * Indicates whether this ViewGroup will always try to draw its children using their 4329 * drawing cache. This property can be set to true when the cache rendering is 4330 * slightly different from the children's normal rendering. Renderings can be different, 4331 * for instance, when the cache's quality is set to low. 4332 * 4333 * When this property is disabled, the ViewGroup will use the drawing cache of its 4334 * children only when asked to. It's usually the task of subclasses to tell ViewGroup 4335 * when to start using the drawing cache and when to stop using it. 4336 * 4337 * @param always true to always draw with the drawing cache, false otherwise 4338 * 4339 * @see #isAlwaysDrawnWithCacheEnabled() 4340 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4341 * @see View#setDrawingCacheEnabled(boolean) 4342 * @see View#setDrawingCacheQuality(int) 4343 */ 4344 public void setAlwaysDrawnWithCacheEnabled(boolean always) { 4345 setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always); 4346 } 4347 4348 /** 4349 * Indicates whether the ViewGroup is currently drawing its children using 4350 * their drawing cache. 4351 * 4352 * @return true if children should be drawn with their cache, false otherwise 4353 * 4354 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4355 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4356 */ 4357 @ViewDebug.ExportedProperty(category = "drawing") 4358 protected boolean isChildrenDrawnWithCacheEnabled() { 4359 return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE; 4360 } 4361 4362 /** 4363 * Tells the ViewGroup to draw its children using their drawing cache. This property 4364 * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache 4365 * will be used only if it has been enabled. 4366 * 4367 * Subclasses should call this method to start and stop using the drawing cache when 4368 * they perform performance sensitive operations, like scrolling or animating. 4369 * 4370 * @param enabled true if children should be drawn with their cache, false otherwise 4371 * 4372 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4373 * @see #isChildrenDrawnWithCacheEnabled() 4374 */ 4375 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) { 4376 setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled); 4377 } 4378 4379 /** 4380 * Indicates whether the ViewGroup is drawing its children in the order defined by 4381 * {@link #getChildDrawingOrder(int, int)}. 4382 * 4383 * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)}, 4384 * false otherwise 4385 * 4386 * @see #setChildrenDrawingOrderEnabled(boolean) 4387 * @see #getChildDrawingOrder(int, int) 4388 */ 4389 @ViewDebug.ExportedProperty(category = "drawing") 4390 protected boolean isChildrenDrawingOrderEnabled() { 4391 return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER; 4392 } 4393 4394 /** 4395 * Tells the ViewGroup whether to draw its children in the order defined by the method 4396 * {@link #getChildDrawingOrder(int, int)}. 4397 * 4398 * @param enabled true if the order of the children when drawing is determined by 4399 * {@link #getChildDrawingOrder(int, int)}, false otherwise 4400 * 4401 * @see #isChildrenDrawingOrderEnabled() 4402 * @see #getChildDrawingOrder(int, int) 4403 */ 4404 protected void setChildrenDrawingOrderEnabled(boolean enabled) { 4405 setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled); 4406 } 4407 4408 private void setBooleanFlag(int flag, boolean value) { 4409 if (value) { 4410 mGroupFlags |= flag; 4411 } else { 4412 mGroupFlags &= ~flag; 4413 } 4414 } 4415 4416 /** 4417 * Returns an integer indicating what types of drawing caches are kept in memory. 4418 * 4419 * @see #setPersistentDrawingCache(int) 4420 * @see #setAnimationCacheEnabled(boolean) 4421 * 4422 * @return one or a combination of {@link #PERSISTENT_NO_CACHE}, 4423 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4424 * and {@link #PERSISTENT_ALL_CACHES} 4425 */ 4426 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 4427 @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE, to = "NONE"), 4428 @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"), 4429 @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"), 4430 @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES, to = "ALL") 4431 }) 4432 public int getPersistentDrawingCache() { 4433 return mPersistentDrawingCache; 4434 } 4435 4436 /** 4437 * Indicates what types of drawing caches should be kept in memory after 4438 * they have been created. 4439 * 4440 * @see #getPersistentDrawingCache() 4441 * @see #setAnimationCacheEnabled(boolean) 4442 * 4443 * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE}, 4444 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4445 * and {@link #PERSISTENT_ALL_CACHES} 4446 */ 4447 public void setPersistentDrawingCache(int drawingCacheToKeep) { 4448 mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES; 4449 } 4450 4451 /** 4452 * Returns the basis of alignment during the layout of this view group: 4453 * either {@link #COMPONENT_BOUNDS} or {@link #LAYOUT_BOUNDS}. 4454 * 4455 * @return the layout mode to use during layout operations 4456 * 4457 * @see #setLayoutMode(int) 4458 */ 4459 public int getLayoutMode() { 4460 if (mLayoutMode == UNDEFINED_LAYOUT_MODE) { 4461 ViewParent parent = getParent(); 4462 if (parent instanceof ViewGroup) { 4463 ViewGroup viewGroup = (ViewGroup) parent; 4464 return viewGroup.getLayoutMode(); 4465 } else { 4466 int targetSdkVersion = mContext.getApplicationInfo().targetSdkVersion; 4467 boolean preJellyBean = targetSdkVersion < Build.VERSION_CODES.JELLY_BEAN; 4468 return preJellyBean ? COMPONENT_BOUNDS : LAYOUT_BOUNDS; 4469 } 4470 4471 } 4472 return mLayoutMode; 4473 } 4474 4475 /** 4476 * Sets the basis of alignment during alignment of this view group. 4477 * Valid values are either {@link #COMPONENT_BOUNDS} or {@link #LAYOUT_BOUNDS}. 4478 * <p> 4479 * The default is to query the property of the parent if this view group has a parent. 4480 * If this ViewGroup is the root of the view hierarchy the default 4481 * value is {@link #LAYOUT_BOUNDS} for target SDK's greater than JellyBean, 4482 * {@link #LAYOUT_BOUNDS} otherwise. 4483 * 4484 * @param layoutMode the layout mode to use during layout operations 4485 * 4486 * @see #getLayoutMode() 4487 */ 4488 public void setLayoutMode(int layoutMode) { 4489 if (mLayoutMode != layoutMode) { 4490 mLayoutMode = layoutMode; 4491 requestLayout(); 4492 } 4493 } 4494 4495 /** 4496 * Returns a new set of layout parameters based on the supplied attributes set. 4497 * 4498 * @param attrs the attributes to build the layout parameters from 4499 * 4500 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4501 * of its descendants 4502 */ 4503 public LayoutParams generateLayoutParams(AttributeSet attrs) { 4504 return new LayoutParams(getContext(), attrs); 4505 } 4506 4507 /** 4508 * Returns a safe set of layout parameters based on the supplied layout params. 4509 * When a ViewGroup is passed a View whose layout params do not pass the test of 4510 * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method 4511 * is invoked. This method should return a new set of layout params suitable for 4512 * this ViewGroup, possibly by copying the appropriate attributes from the 4513 * specified set of layout params. 4514 * 4515 * @param p The layout parameters to convert into a suitable set of layout parameters 4516 * for this ViewGroup. 4517 * 4518 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4519 * of its descendants 4520 */ 4521 protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 4522 return p; 4523 } 4524 4525 /** 4526 * Returns a set of default layout parameters. These parameters are requested 4527 * when the View passed to {@link #addView(View)} has no layout parameters 4528 * already set. If null is returned, an exception is thrown from addView. 4529 * 4530 * @return a set of default layout parameters or null 4531 */ 4532 protected LayoutParams generateDefaultLayoutParams() { 4533 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 4534 } 4535 4536 /** 4537 * @hide 4538 */ 4539 @Override 4540 protected boolean dispatchConsistencyCheck(int consistency) { 4541 boolean result = super.dispatchConsistencyCheck(consistency); 4542 4543 final int count = mChildrenCount; 4544 final View[] children = mChildren; 4545 for (int i = 0; i < count; i++) { 4546 if (!children[i].dispatchConsistencyCheck(consistency)) result = false; 4547 } 4548 4549 return result; 4550 } 4551 4552 /** 4553 * @hide 4554 */ 4555 @Override 4556 protected boolean onConsistencyCheck(int consistency) { 4557 boolean result = super.onConsistencyCheck(consistency); 4558 4559 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 4560 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 4561 4562 if (checkLayout) { 4563 final int count = mChildrenCount; 4564 final View[] children = mChildren; 4565 for (int i = 0; i < count; i++) { 4566 if (children[i].getParent() != this) { 4567 result = false; 4568 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 4569 "View " + children[i] + " has no parent/a parent that is not " + this); 4570 } 4571 } 4572 } 4573 4574 if (checkDrawing) { 4575 // If this group is dirty, check that the parent is dirty as well 4576 if ((mPrivateFlags & DIRTY_MASK) != 0) { 4577 final ViewParent parent = getParent(); 4578 if (parent != null && !(parent instanceof ViewRootImpl)) { 4579 if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) { 4580 result = false; 4581 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 4582 "ViewGroup " + this + " is dirty but its parent is not: " + this); 4583 } 4584 } 4585 } 4586 } 4587 4588 return result; 4589 } 4590 4591 /** 4592 * {@inheritDoc} 4593 */ 4594 @Override 4595 protected void debug(int depth) { 4596 super.debug(depth); 4597 String output; 4598 4599 if (mFocused != null) { 4600 output = debugIndent(depth); 4601 output += "mFocused"; 4602 Log.d(VIEW_LOG_TAG, output); 4603 } 4604 if (mChildrenCount != 0) { 4605 output = debugIndent(depth); 4606 output += "{"; 4607 Log.d(VIEW_LOG_TAG, output); 4608 } 4609 int count = mChildrenCount; 4610 for (int i = 0; i < count; i++) { 4611 View child = mChildren[i]; 4612 child.debug(depth + 1); 4613 } 4614 4615 if (mChildrenCount != 0) { 4616 output = debugIndent(depth); 4617 output += "}"; 4618 Log.d(VIEW_LOG_TAG, output); 4619 } 4620 } 4621 4622 /** 4623 * Returns the position in the group of the specified child view. 4624 * 4625 * @param child the view for which to get the position 4626 * @return a positive integer representing the position of the view in the 4627 * group, or -1 if the view does not exist in the group 4628 */ 4629 public int indexOfChild(View child) { 4630 final int count = mChildrenCount; 4631 final View[] children = mChildren; 4632 for (int i = 0; i < count; i++) { 4633 if (children[i] == child) { 4634 return i; 4635 } 4636 } 4637 return -1; 4638 } 4639 4640 /** 4641 * Returns the number of children in the group. 4642 * 4643 * @return a positive integer representing the number of children in 4644 * the group 4645 */ 4646 public int getChildCount() { 4647 return mChildrenCount; 4648 } 4649 4650 /** 4651 * Returns the view at the specified position in the group. 4652 * 4653 * @param index the position at which to get the view from 4654 * @return the view at the specified position or null if the position 4655 * does not exist within the group 4656 */ 4657 public View getChildAt(int index) { 4658 if (index < 0 || index >= mChildrenCount) { 4659 return null; 4660 } 4661 return mChildren[index]; 4662 } 4663 4664 /** 4665 * Ask all of the children of this view to measure themselves, taking into 4666 * account both the MeasureSpec requirements for this view and its padding. 4667 * We skip children that are in the GONE state The heavy lifting is done in 4668 * getChildMeasureSpec. 4669 * 4670 * @param widthMeasureSpec The width requirements for this view 4671 * @param heightMeasureSpec The height requirements for this view 4672 */ 4673 protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) { 4674 final int size = mChildrenCount; 4675 final View[] children = mChildren; 4676 for (int i = 0; i < size; ++i) { 4677 final View child = children[i]; 4678 if ((child.mViewFlags & VISIBILITY_MASK) != GONE) { 4679 measureChild(child, widthMeasureSpec, heightMeasureSpec); 4680 } 4681 } 4682 } 4683 4684 /** 4685 * Ask one of the children of this view to measure itself, taking into 4686 * account both the MeasureSpec requirements for this view and its padding. 4687 * The heavy lifting is done in getChildMeasureSpec. 4688 * 4689 * @param child The child to measure 4690 * @param parentWidthMeasureSpec The width requirements for this view 4691 * @param parentHeightMeasureSpec The height requirements for this view 4692 */ 4693 protected void measureChild(View child, int parentWidthMeasureSpec, 4694 int parentHeightMeasureSpec) { 4695 final LayoutParams lp = child.getLayoutParams(); 4696 4697 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4698 mPaddingLeft + mPaddingRight, lp.width); 4699 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4700 mPaddingTop + mPaddingBottom, lp.height); 4701 4702 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4703 } 4704 4705 /** 4706 * Ask one of the children of this view to measure itself, taking into 4707 * account both the MeasureSpec requirements for this view and its padding 4708 * and margins. The child must have MarginLayoutParams The heavy lifting is 4709 * done in getChildMeasureSpec. 4710 * 4711 * @param child The child to measure 4712 * @param parentWidthMeasureSpec The width requirements for this view 4713 * @param widthUsed Extra space that has been used up by the parent 4714 * horizontally (possibly by other children of the parent) 4715 * @param parentHeightMeasureSpec The height requirements for this view 4716 * @param heightUsed Extra space that has been used up by the parent 4717 * vertically (possibly by other children of the parent) 4718 */ 4719 protected void measureChildWithMargins(View child, 4720 int parentWidthMeasureSpec, int widthUsed, 4721 int parentHeightMeasureSpec, int heightUsed) { 4722 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 4723 4724 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4725 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 4726 + widthUsed, lp.width); 4727 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4728 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin 4729 + heightUsed, lp.height); 4730 4731 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4732 } 4733 4734 /** 4735 * Does the hard part of measureChildren: figuring out the MeasureSpec to 4736 * pass to a particular child. This method figures out the right MeasureSpec 4737 * for one dimension (height or width) of one child view. 4738 * 4739 * The goal is to combine information from our MeasureSpec with the 4740 * LayoutParams of the child to get the best possible results. For example, 4741 * if the this view knows its size (because its MeasureSpec has a mode of 4742 * EXACTLY), and the child has indicated in its LayoutParams that it wants 4743 * to be the same size as the parent, the parent should ask the child to 4744 * layout given an exact size. 4745 * 4746 * @param spec The requirements for this view 4747 * @param padding The padding of this view for the current dimension and 4748 * margins, if applicable 4749 * @param childDimension How big the child wants to be in the current 4750 * dimension 4751 * @return a MeasureSpec integer for the child 4752 */ 4753 public static int getChildMeasureSpec(int spec, int padding, int childDimension) { 4754 int specMode = MeasureSpec.getMode(spec); 4755 int specSize = MeasureSpec.getSize(spec); 4756 4757 int size = Math.max(0, specSize - padding); 4758 4759 int resultSize = 0; 4760 int resultMode = 0; 4761 4762 switch (specMode) { 4763 // Parent has imposed an exact size on us 4764 case MeasureSpec.EXACTLY: 4765 if (childDimension >= 0) { 4766 resultSize = childDimension; 4767 resultMode = MeasureSpec.EXACTLY; 4768 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4769 // Child wants to be our size. So be it. 4770 resultSize = size; 4771 resultMode = MeasureSpec.EXACTLY; 4772 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4773 // Child wants to determine its own size. It can't be 4774 // bigger than us. 4775 resultSize = size; 4776 resultMode = MeasureSpec.AT_MOST; 4777 } 4778 break; 4779 4780 // Parent has imposed a maximum size on us 4781 case MeasureSpec.AT_MOST: 4782 if (childDimension >= 0) { 4783 // Child wants a specific size... so be it 4784 resultSize = childDimension; 4785 resultMode = MeasureSpec.EXACTLY; 4786 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4787 // Child wants to be our size, but our size is not fixed. 4788 // Constrain child to not be bigger than us. 4789 resultSize = size; 4790 resultMode = MeasureSpec.AT_MOST; 4791 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4792 // Child wants to determine its own size. It can't be 4793 // bigger than us. 4794 resultSize = size; 4795 resultMode = MeasureSpec.AT_MOST; 4796 } 4797 break; 4798 4799 // Parent asked to see how big we want to be 4800 case MeasureSpec.UNSPECIFIED: 4801 if (childDimension >= 0) { 4802 // Child wants a specific size... let him have it 4803 resultSize = childDimension; 4804 resultMode = MeasureSpec.EXACTLY; 4805 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4806 // Child wants to be our size... find out how big it should 4807 // be 4808 resultSize = 0; 4809 resultMode = MeasureSpec.UNSPECIFIED; 4810 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4811 // Child wants to determine its own size.... find out how 4812 // big it should be 4813 resultSize = 0; 4814 resultMode = MeasureSpec.UNSPECIFIED; 4815 } 4816 break; 4817 } 4818 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 4819 } 4820 4821 4822 /** 4823 * Removes any pending animations for views that have been removed. Call 4824 * this if you don't want animations for exiting views to stack up. 4825 */ 4826 public void clearDisappearingChildren() { 4827 if (mDisappearingChildren != null) { 4828 mDisappearingChildren.clear(); 4829 invalidate(); 4830 } 4831 } 4832 4833 /** 4834 * Add a view which is removed from mChildren but still needs animation 4835 * 4836 * @param v View to add 4837 */ 4838 private void addDisappearingView(View v) { 4839 ArrayList<View> disappearingChildren = mDisappearingChildren; 4840 4841 if (disappearingChildren == null) { 4842 disappearingChildren = mDisappearingChildren = new ArrayList<View>(); 4843 } 4844 4845 disappearingChildren.add(v); 4846 } 4847 4848 /** 4849 * Cleanup a view when its animation is done. This may mean removing it from 4850 * the list of disappearing views. 4851 * 4852 * @param view The view whose animation has finished 4853 * @param animation The animation, cannot be null 4854 */ 4855 void finishAnimatingView(final View view, Animation animation) { 4856 final ArrayList<View> disappearingChildren = mDisappearingChildren; 4857 if (disappearingChildren != null) { 4858 if (disappearingChildren.contains(view)) { 4859 disappearingChildren.remove(view); 4860 4861 if (view.mAttachInfo != null) { 4862 view.dispatchDetachedFromWindow(); 4863 } 4864 4865 view.clearAnimation(); 4866 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4867 } 4868 } 4869 4870 if (animation != null && !animation.getFillAfter()) { 4871 view.clearAnimation(); 4872 } 4873 4874 if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) { 4875 view.onAnimationEnd(); 4876 // Should be performed by onAnimationEnd() but this avoid an infinite loop, 4877 // so we'd rather be safe than sorry 4878 view.mPrivateFlags &= ~ANIMATION_STARTED; 4879 // Draw one more frame after the animation is done 4880 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4881 } 4882 } 4883 4884 /** 4885 * Utility function called by View during invalidation to determine whether a view that 4886 * is invisible or gone should still be invalidated because it is being transitioned (and 4887 * therefore still needs to be drawn). 4888 */ 4889 boolean isViewTransitioning(View view) { 4890 return (mTransitioningViews != null && mTransitioningViews.contains(view)); 4891 } 4892 4893 /** 4894 * This method tells the ViewGroup that the given View object, which should have this 4895 * ViewGroup as its parent, 4896 * should be kept around (re-displayed when the ViewGroup draws its children) even if it 4897 * is removed from its parent. This allows animations, such as those used by 4898 * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate 4899 * the removal of views. A call to this method should always be accompanied by a later call 4900 * to {@link #endViewTransition(View)}, such as after an animation on the View has finished, 4901 * so that the View finally gets removed. 4902 * 4903 * @param view The View object to be kept visible even if it gets removed from its parent. 4904 */ 4905 public void startViewTransition(View view) { 4906 if (view.mParent == this) { 4907 if (mTransitioningViews == null) { 4908 mTransitioningViews = new ArrayList<View>(); 4909 } 4910 mTransitioningViews.add(view); 4911 } 4912 } 4913 4914 /** 4915 * This method should always be called following an earlier call to 4916 * {@link #startViewTransition(View)}. The given View is finally removed from its parent 4917 * and will no longer be displayed. Note that this method does not perform the functionality 4918 * of removing a view from its parent; it just discontinues the display of a View that 4919 * has previously been removed. 4920 * 4921 * @return view The View object that has been removed but is being kept around in the visible 4922 * hierarchy by an earlier call to {@link #startViewTransition(View)}. 4923 */ 4924 public void endViewTransition(View view) { 4925 if (mTransitioningViews != null) { 4926 mTransitioningViews.remove(view); 4927 final ArrayList<View> disappearingChildren = mDisappearingChildren; 4928 if (disappearingChildren != null && disappearingChildren.contains(view)) { 4929 disappearingChildren.remove(view); 4930 if (mVisibilityChangingChildren != null && 4931 mVisibilityChangingChildren.contains(view)) { 4932 mVisibilityChangingChildren.remove(view); 4933 } else { 4934 if (view.mAttachInfo != null) { 4935 view.dispatchDetachedFromWindow(); 4936 } 4937 if (view.mParent != null) { 4938 view.mParent = null; 4939 } 4940 } 4941 invalidate(); 4942 } 4943 } 4944 } 4945 4946 private LayoutTransition.TransitionListener mLayoutTransitionListener = 4947 new LayoutTransition.TransitionListener() { 4948 @Override 4949 public void startTransition(LayoutTransition transition, ViewGroup container, 4950 View view, int transitionType) { 4951 // We only care about disappearing items, since we need special logic to keep 4952 // those items visible after they've been 'removed' 4953 if (transitionType == LayoutTransition.DISAPPEARING) { 4954 startViewTransition(view); 4955 } 4956 } 4957 4958 @Override 4959 public void endTransition(LayoutTransition transition, ViewGroup container, 4960 View view, int transitionType) { 4961 if (mLayoutSuppressed && !transition.isChangingLayout()) { 4962 requestLayout(); 4963 mLayoutSuppressed = false; 4964 } 4965 if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) { 4966 endViewTransition(view); 4967 } 4968 } 4969 }; 4970 4971 /** 4972 * {@inheritDoc} 4973 */ 4974 @Override 4975 public boolean gatherTransparentRegion(Region region) { 4976 // If no transparent regions requested, we are always opaque. 4977 final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0; 4978 if (meOpaque && region == null) { 4979 // The caller doesn't care about the region, so stop now. 4980 return true; 4981 } 4982 super.gatherTransparentRegion(region); 4983 final View[] children = mChildren; 4984 final int count = mChildrenCount; 4985 boolean noneOfTheChildrenAreTransparent = true; 4986 for (int i = 0; i < count; i++) { 4987 final View child = children[i]; 4988 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 4989 if (!child.gatherTransparentRegion(region)) { 4990 noneOfTheChildrenAreTransparent = false; 4991 } 4992 } 4993 } 4994 return meOpaque || noneOfTheChildrenAreTransparent; 4995 } 4996 4997 /** 4998 * {@inheritDoc} 4999 */ 5000 public void requestTransparentRegion(View child) { 5001 if (child != null) { 5002 child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS; 5003 if (mParent != null) { 5004 mParent.requestTransparentRegion(this); 5005 } 5006 } 5007 } 5008 5009 5010 @Override 5011 protected boolean fitSystemWindows(Rect insets) { 5012 boolean done = super.fitSystemWindows(insets); 5013 if (!done) { 5014 final int count = mChildrenCount; 5015 final View[] children = mChildren; 5016 for (int i = 0; i < count; i++) { 5017 done = children[i].fitSystemWindows(insets); 5018 if (done) { 5019 break; 5020 } 5021 } 5022 } 5023 return done; 5024 } 5025 5026 /** 5027 * Returns the animation listener to which layout animation events are 5028 * sent. 5029 * 5030 * @return an {@link android.view.animation.Animation.AnimationListener} 5031 */ 5032 public Animation.AnimationListener getLayoutAnimationListener() { 5033 return mAnimationListener; 5034 } 5035 5036 @Override 5037 protected void drawableStateChanged() { 5038 super.drawableStateChanged(); 5039 5040 if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) { 5041 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 5042 throw new IllegalStateException("addStateFromChildren cannot be enabled if a" 5043 + " child has duplicateParentState set to true"); 5044 } 5045 5046 final View[] children = mChildren; 5047 final int count = mChildrenCount; 5048 5049 for (int i = 0; i < count; i++) { 5050 final View child = children[i]; 5051 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) { 5052 child.refreshDrawableState(); 5053 } 5054 } 5055 } 5056 } 5057 5058 @Override 5059 public void jumpDrawablesToCurrentState() { 5060 super.jumpDrawablesToCurrentState(); 5061 final View[] children = mChildren; 5062 final int count = mChildrenCount; 5063 for (int i = 0; i < count; i++) { 5064 children[i].jumpDrawablesToCurrentState(); 5065 } 5066 } 5067 5068 @Override 5069 protected int[] onCreateDrawableState(int extraSpace) { 5070 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) { 5071 return super.onCreateDrawableState(extraSpace); 5072 } 5073 5074 int need = 0; 5075 int n = getChildCount(); 5076 for (int i = 0; i < n; i++) { 5077 int[] childState = getChildAt(i).getDrawableState(); 5078 5079 if (childState != null) { 5080 need += childState.length; 5081 } 5082 } 5083 5084 int[] state = super.onCreateDrawableState(extraSpace + need); 5085 5086 for (int i = 0; i < n; i++) { 5087 int[] childState = getChildAt(i).getDrawableState(); 5088 5089 if (childState != null) { 5090 state = mergeDrawableStates(state, childState); 5091 } 5092 } 5093 5094 return state; 5095 } 5096 5097 /** 5098 * Sets whether this ViewGroup's drawable states also include 5099 * its children's drawable states. This is used, for example, to 5100 * make a group appear to be focused when its child EditText or button 5101 * is focused. 5102 */ 5103 public void setAddStatesFromChildren(boolean addsStates) { 5104 if (addsStates) { 5105 mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN; 5106 } else { 5107 mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN; 5108 } 5109 5110 refreshDrawableState(); 5111 } 5112 5113 /** 5114 * Returns whether this ViewGroup's drawable states also include 5115 * its children's drawable states. This is used, for example, to 5116 * make a group appear to be focused when its child EditText or button 5117 * is focused. 5118 */ 5119 public boolean addStatesFromChildren() { 5120 return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0; 5121 } 5122 5123 /** 5124 * If {link #addStatesFromChildren} is true, refreshes this group's 5125 * drawable state (to include the states from its children). 5126 */ 5127 public void childDrawableStateChanged(View child) { 5128 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 5129 refreshDrawableState(); 5130 } 5131 } 5132 5133 /** 5134 * Specifies the animation listener to which layout animation events must 5135 * be sent. Only 5136 * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)} 5137 * and 5138 * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)} 5139 * are invoked. 5140 * 5141 * @param animationListener the layout animation listener 5142 */ 5143 public void setLayoutAnimationListener(Animation.AnimationListener animationListener) { 5144 mAnimationListener = animationListener; 5145 } 5146 5147 /** 5148 * This method is called by LayoutTransition when there are 'changing' animations that need 5149 * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who 5150 * starts all pending transitions prior to the drawing phase in the current traversal. 5151 * 5152 * @param transition The LayoutTransition to be started on the next traversal. 5153 * 5154 * @hide 5155 */ 5156 public void requestTransitionStart(LayoutTransition transition) { 5157 ViewRootImpl viewAncestor = getViewRootImpl(); 5158 if (viewAncestor != null) { 5159 viewAncestor.requestTransitionStart(transition); 5160 } 5161 } 5162 5163 @Override 5164 public void onResolvedLayoutDirectionReset() { 5165 // Take care of resetting the children resolution too 5166 final int count = getChildCount(); 5167 for (int i = 0; i < count; i++) { 5168 final View child = getChildAt(i); 5169 if (child.getLayoutDirection() == LAYOUT_DIRECTION_INHERIT) { 5170 child.resetResolvedLayoutDirection(); 5171 } 5172 } 5173 } 5174 5175 @Override 5176 public void onResolvedTextDirectionReset() { 5177 // Take care of resetting the children resolution too 5178 final int count = getChildCount(); 5179 for (int i = 0; i < count; i++) { 5180 final View child = getChildAt(i); 5181 if (child.getTextDirection() == TEXT_DIRECTION_INHERIT) { 5182 child.resetResolvedTextDirection(); 5183 } 5184 } 5185 } 5186 5187 @Override 5188 public void onResolvedTextAlignmentReset() { 5189 // Take care of resetting the children resolution too 5190 final int count = getChildCount(); 5191 for (int i = 0; i < count; i++) { 5192 final View child = getChildAt(i); 5193 if (child.getTextAlignment() == TEXT_ALIGNMENT_INHERIT) { 5194 child.resetResolvedTextAlignment(); 5195 } 5196 } 5197 } 5198 5199 /** 5200 * Return true if the pressed state should be delayed for children or descendants of this 5201 * ViewGroup. Generally, this should be done for containers that can scroll, such as a List. 5202 * This prevents the pressed state from appearing when the user is actually trying to scroll 5203 * the content. 5204 * 5205 * The default implementation returns true for compatibility reasons. Subclasses that do 5206 * not scroll should generally override this method and return false. 5207 */ 5208 public boolean shouldDelayChildPressedState() { 5209 return true; 5210 } 5211 5212 /** @hide */ 5213 protected void onSetLayoutParams(View child, LayoutParams layoutParams) { 5214 } 5215 5216 /** 5217 * LayoutParams are used by views to tell their parents how they want to be 5218 * laid out. See 5219 * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes} 5220 * for a list of all child view attributes that this class supports. 5221 * 5222 * <p> 5223 * The base LayoutParams class just describes how big the view wants to be 5224 * for both width and height. For each dimension, it can specify one of: 5225 * <ul> 5226 * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which 5227 * means that the view wants to be as big as its parent (minus padding) 5228 * <li> WRAP_CONTENT, which means that the view wants to be just big enough 5229 * to enclose its content (plus padding) 5230 * <li> an exact number 5231 * </ul> 5232 * There are subclasses of LayoutParams for different subclasses of 5233 * ViewGroup. For example, AbsoluteLayout has its own subclass of 5234 * LayoutParams which adds an X and Y value.</p> 5235 * 5236 * <div class="special reference"> 5237 * <h3>Developer Guides</h3> 5238 * <p>For more information about creating user interface layouts, read the 5239 * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer 5240 * guide.</p></div> 5241 * 5242 * @attr ref android.R.styleable#ViewGroup_Layout_layout_height 5243 * @attr ref android.R.styleable#ViewGroup_Layout_layout_width 5244 */ 5245 public static class LayoutParams { 5246 /** 5247 * Special value for the height or width requested by a View. 5248 * FILL_PARENT means that the view wants to be as big as its parent, 5249 * minus the parent's padding, if any. This value is deprecated 5250 * starting in API Level 8 and replaced by {@link #MATCH_PARENT}. 5251 */ 5252 @SuppressWarnings({"UnusedDeclaration"}) 5253 @Deprecated 5254 public static final int FILL_PARENT = -1; 5255 5256 /** 5257 * Special value for the height or width requested by a View. 5258 * MATCH_PARENT means that the view wants to be as big as its parent, 5259 * minus the parent's padding, if any. Introduced in API Level 8. 5260 */ 5261 public static final int MATCH_PARENT = -1; 5262 5263 /** 5264 * Special value for the height or width requested by a View. 5265 * WRAP_CONTENT means that the view wants to be just large enough to fit 5266 * its own internal content, taking its own padding into account. 5267 */ 5268 public static final int WRAP_CONTENT = -2; 5269 5270 /** 5271 * Information about how wide the view wants to be. Can be one of the 5272 * constants FILL_PARENT (replaced by MATCH_PARENT , 5273 * in API Level 8) or WRAP_CONTENT. or an exact size. 5274 */ 5275 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5276 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5277 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5278 }) 5279 public int width; 5280 5281 /** 5282 * Information about how tall the view wants to be. Can be one of the 5283 * constants FILL_PARENT (replaced by MATCH_PARENT , 5284 * in API Level 8) or WRAP_CONTENT. or an exact size. 5285 */ 5286 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5287 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5288 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5289 }) 5290 public int height; 5291 5292 /** 5293 * Used to animate layouts. 5294 */ 5295 public LayoutAnimationController.AnimationParameters layoutAnimationParameters; 5296 5297 /** 5298 * Creates a new set of layout parameters. The values are extracted from 5299 * the supplied attributes set and context. The XML attributes mapped 5300 * to this set of layout parameters are: 5301 * 5302 * <ul> 5303 * <li><code>layout_width</code>: the width, either an exact value, 5304 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5305 * {@link #MATCH_PARENT} in API Level 8)</li> 5306 * <li><code>layout_height</code>: the height, either an exact value, 5307 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5308 * {@link #MATCH_PARENT} in API Level 8)</li> 5309 * </ul> 5310 * 5311 * @param c the application environment 5312 * @param attrs the set of attributes from which to extract the layout 5313 * parameters' values 5314 */ 5315 public LayoutParams(Context c, AttributeSet attrs) { 5316 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout); 5317 setBaseAttributes(a, 5318 R.styleable.ViewGroup_Layout_layout_width, 5319 R.styleable.ViewGroup_Layout_layout_height); 5320 a.recycle(); 5321 } 5322 5323 /** 5324 * Creates a new set of layout parameters with the specified width 5325 * and height. 5326 * 5327 * @param width the width, either {@link #WRAP_CONTENT}, 5328 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5329 * API Level 8), or a fixed size in pixels 5330 * @param height the height, either {@link #WRAP_CONTENT}, 5331 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5332 * API Level 8), or a fixed size in pixels 5333 */ 5334 public LayoutParams(int width, int height) { 5335 this.width = width; 5336 this.height = height; 5337 } 5338 5339 /** 5340 * Copy constructor. Clones the width and height values of the source. 5341 * 5342 * @param source The layout params to copy from. 5343 */ 5344 public LayoutParams(LayoutParams source) { 5345 this.width = source.width; 5346 this.height = source.height; 5347 } 5348 5349 /** 5350 * Used internally by MarginLayoutParams. 5351 * @hide 5352 */ 5353 LayoutParams() { 5354 } 5355 5356 /** 5357 * Extracts the layout parameters from the supplied attributes. 5358 * 5359 * @param a the style attributes to extract the parameters from 5360 * @param widthAttr the identifier of the width attribute 5361 * @param heightAttr the identifier of the height attribute 5362 */ 5363 protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { 5364 width = a.getLayoutDimension(widthAttr, "layout_width"); 5365 height = a.getLayoutDimension(heightAttr, "layout_height"); 5366 } 5367 5368 /** 5369 * Resolve layout parameters depending on the layout direction. Subclasses that care about 5370 * layoutDirection changes should override this method. The default implementation does 5371 * nothing. 5372 * 5373 * @param layoutDirection the direction of the layout 5374 * 5375 * {@link View#LAYOUT_DIRECTION_LTR} 5376 * {@link View#LAYOUT_DIRECTION_RTL} 5377 */ 5378 public void onResolveLayoutDirection(int layoutDirection) { 5379 } 5380 5381 /** 5382 * Returns a String representation of this set of layout parameters. 5383 * 5384 * @param output the String to prepend to the internal representation 5385 * @return a String with the following format: output + 5386 * "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }" 5387 * 5388 * @hide 5389 */ 5390 public String debug(String output) { 5391 return output + "ViewGroup.LayoutParams={ width=" 5392 + sizeToString(width) + ", height=" + sizeToString(height) + " }"; 5393 } 5394 5395 /** 5396 * Converts the specified size to a readable String. 5397 * 5398 * @param size the size to convert 5399 * @return a String instance representing the supplied size 5400 * 5401 * @hide 5402 */ 5403 protected static String sizeToString(int size) { 5404 if (size == WRAP_CONTENT) { 5405 return "wrap-content"; 5406 } 5407 if (size == MATCH_PARENT) { 5408 return "match-parent"; 5409 } 5410 return String.valueOf(size); 5411 } 5412 } 5413 5414 /** 5415 * Per-child layout information for layouts that support margins. 5416 * See 5417 * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes} 5418 * for a list of all child view attributes that this class supports. 5419 */ 5420 public static class MarginLayoutParams extends ViewGroup.LayoutParams { 5421 /** 5422 * The left margin in pixels of the child. 5423 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5424 * to this field. 5425 */ 5426 @ViewDebug.ExportedProperty(category = "layout") 5427 public int leftMargin; 5428 5429 /** 5430 * The top margin in pixels of the child. 5431 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5432 * to this field. 5433 */ 5434 @ViewDebug.ExportedProperty(category = "layout") 5435 public int topMargin; 5436 5437 /** 5438 * The right margin in pixels of the child. 5439 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5440 * to this field. 5441 */ 5442 @ViewDebug.ExportedProperty(category = "layout") 5443 public int rightMargin; 5444 5445 /** 5446 * The bottom margin in pixels of the child. 5447 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5448 * to this field. 5449 */ 5450 @ViewDebug.ExportedProperty(category = "layout") 5451 public int bottomMargin; 5452 5453 /** 5454 * The start margin in pixels of the child. 5455 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5456 * to this field. 5457 */ 5458 @ViewDebug.ExportedProperty(category = "layout") 5459 public int startMargin = DEFAULT_RELATIVE; 5460 5461 /** 5462 * The end margin in pixels of the child. 5463 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5464 * to this field. 5465 */ 5466 @ViewDebug.ExportedProperty(category = "layout") 5467 public int endMargin = DEFAULT_RELATIVE; 5468 5469 /** 5470 * The default start and end margin. 5471 */ 5472 static private final int DEFAULT_RELATIVE = Integer.MIN_VALUE; 5473 5474 /** 5475 * Creates a new set of layout parameters. The values are extracted from 5476 * the supplied attributes set and context. 5477 * 5478 * @param c the application environment 5479 * @param attrs the set of attributes from which to extract the layout 5480 * parameters' values 5481 */ 5482 public MarginLayoutParams(Context c, AttributeSet attrs) { 5483 super(); 5484 5485 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout); 5486 setBaseAttributes(a, 5487 R.styleable.ViewGroup_MarginLayout_layout_width, 5488 R.styleable.ViewGroup_MarginLayout_layout_height); 5489 5490 int margin = a.getDimensionPixelSize( 5491 com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1); 5492 if (margin >= 0) { 5493 leftMargin = margin; 5494 topMargin = margin; 5495 rightMargin= margin; 5496 bottomMargin = margin; 5497 } else { 5498 leftMargin = a.getDimensionPixelSize( 5499 R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0); 5500 topMargin = a.getDimensionPixelSize( 5501 R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0); 5502 rightMargin = a.getDimensionPixelSize( 5503 R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0); 5504 bottomMargin = a.getDimensionPixelSize( 5505 R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0); 5506 startMargin = a.getDimensionPixelSize( 5507 R.styleable.ViewGroup_MarginLayout_layout_marginStart, DEFAULT_RELATIVE); 5508 endMargin = a.getDimensionPixelSize( 5509 R.styleable.ViewGroup_MarginLayout_layout_marginEnd, DEFAULT_RELATIVE); 5510 } 5511 5512 a.recycle(); 5513 } 5514 5515 /** 5516 * {@inheritDoc} 5517 */ 5518 public MarginLayoutParams(int width, int height) { 5519 super(width, height); 5520 } 5521 5522 /** 5523 * Copy constructor. Clones the width, height and margin values of the source. 5524 * 5525 * @param source The layout params to copy from. 5526 */ 5527 public MarginLayoutParams(MarginLayoutParams source) { 5528 this.width = source.width; 5529 this.height = source.height; 5530 5531 this.leftMargin = source.leftMargin; 5532 this.topMargin = source.topMargin; 5533 this.rightMargin = source.rightMargin; 5534 this.bottomMargin = source.bottomMargin; 5535 this.startMargin = source.startMargin; 5536 this.endMargin = source.endMargin; 5537 } 5538 5539 /** 5540 * {@inheritDoc} 5541 */ 5542 public MarginLayoutParams(LayoutParams source) { 5543 super(source); 5544 } 5545 5546 /** 5547 * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs 5548 * to be done so that the new margins are taken into account. Left and right margins may be 5549 * overriden by {@link android.view.View#requestLayout()} depending on layout direction. 5550 * 5551 * @param left the left margin size 5552 * @param top the top margin size 5553 * @param right the right margin size 5554 * @param bottom the bottom margin size 5555 * 5556 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft 5557 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 5558 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight 5559 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 5560 */ 5561 public void setMargins(int left, int top, int right, int bottom) { 5562 leftMargin = left; 5563 topMargin = top; 5564 rightMargin = right; 5565 bottomMargin = bottom; 5566 } 5567 5568 /** 5569 * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()} 5570 * needs to be done so that the new relative margins are taken into account. Left and right 5571 * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout 5572 * direction. 5573 * 5574 * @param start the start margin size 5575 * @param top the top margin size 5576 * @param end the right margin size 5577 * @param bottom the bottom margin size 5578 * 5579 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5580 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 5581 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5582 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 5583 * 5584 * @hide 5585 */ 5586 public void setMarginsRelative(int start, int top, int end, int bottom) { 5587 startMargin = start; 5588 topMargin = top; 5589 endMargin = end; 5590 bottomMargin = bottom; 5591 } 5592 5593 /** 5594 * Returns the start margin in pixels. 5595 * 5596 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5597 * 5598 * @return the start margin in pixels. 5599 */ 5600 public int getMarginStart() { 5601 return startMargin; 5602 } 5603 5604 /** 5605 * Returns the end margin in pixels. 5606 * 5607 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5608 * 5609 * @return the end margin in pixels. 5610 */ 5611 public int getMarginEnd() { 5612 return endMargin; 5613 } 5614 5615 /** 5616 * Check if margins are relative. 5617 * 5618 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5619 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5620 * 5621 * @return true if either marginStart or marginEnd has been set 5622 */ 5623 public boolean isMarginRelative() { 5624 return (startMargin != DEFAULT_RELATIVE) || (endMargin != DEFAULT_RELATIVE); 5625 } 5626 5627 /** 5628 * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins 5629 * may be overridden depending on layout direction. 5630 */ 5631 @Override 5632 public void onResolveLayoutDirection(int layoutDirection) { 5633 switch(layoutDirection) { 5634 case View.LAYOUT_DIRECTION_RTL: 5635 leftMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : leftMargin; 5636 rightMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : rightMargin; 5637 break; 5638 case View.LAYOUT_DIRECTION_LTR: 5639 default: 5640 leftMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : leftMargin; 5641 rightMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : rightMargin; 5642 break; 5643 } 5644 } 5645 } 5646 5647 /* Describes a touched view and the ids of the pointers that it has captured. 5648 * 5649 * This code assumes that pointer ids are always in the range 0..31 such that 5650 * it can use a bitfield to track which pointer ids are present. 5651 * As it happens, the lower layers of the input dispatch pipeline also use the 5652 * same trick so the assumption should be safe here... 5653 */ 5654 private static final class TouchTarget { 5655 private static final int MAX_RECYCLED = 32; 5656 private static final Object sRecycleLock = new Object(); 5657 private static TouchTarget sRecycleBin; 5658 private static int sRecycledCount; 5659 5660 public static final int ALL_POINTER_IDS = -1; // all ones 5661 5662 // The touched child view. 5663 public View child; 5664 5665 // The combined bit mask of pointer ids for all pointers captured by the target. 5666 public int pointerIdBits; 5667 5668 // The next target in the target list. 5669 public TouchTarget next; 5670 5671 private TouchTarget() { 5672 } 5673 5674 public static TouchTarget obtain(View child, int pointerIdBits) { 5675 final TouchTarget target; 5676 synchronized (sRecycleLock) { 5677 if (sRecycleBin == null) { 5678 target = new TouchTarget(); 5679 } else { 5680 target = sRecycleBin; 5681 sRecycleBin = target.next; 5682 sRecycledCount--; 5683 target.next = null; 5684 } 5685 } 5686 target.child = child; 5687 target.pointerIdBits = pointerIdBits; 5688 return target; 5689 } 5690 5691 public void recycle() { 5692 synchronized (sRecycleLock) { 5693 if (sRecycledCount < MAX_RECYCLED) { 5694 next = sRecycleBin; 5695 sRecycleBin = this; 5696 sRecycledCount += 1; 5697 } else { 5698 next = null; 5699 } 5700 child = null; 5701 } 5702 } 5703 } 5704 5705 /* Describes a hovered view. */ 5706 private static final class HoverTarget { 5707 private static final int MAX_RECYCLED = 32; 5708 private static final Object sRecycleLock = new Object(); 5709 private static HoverTarget sRecycleBin; 5710 private static int sRecycledCount; 5711 5712 // The hovered child view. 5713 public View child; 5714 5715 // The next target in the target list. 5716 public HoverTarget next; 5717 5718 private HoverTarget() { 5719 } 5720 5721 public static HoverTarget obtain(View child) { 5722 final HoverTarget target; 5723 synchronized (sRecycleLock) { 5724 if (sRecycleBin == null) { 5725 target = new HoverTarget(); 5726 } else { 5727 target = sRecycleBin; 5728 sRecycleBin = target.next; 5729 sRecycledCount--; 5730 target.next = null; 5731 } 5732 } 5733 target.child = child; 5734 return target; 5735 } 5736 5737 public void recycle() { 5738 synchronized (sRecycleLock) { 5739 if (sRecycledCount < MAX_RECYCLED) { 5740 next = sRecycleBin; 5741 sRecycleBin = this; 5742 sRecycledCount += 1; 5743 } else { 5744 next = null; 5745 } 5746 child = null; 5747 } 5748 } 5749 } 5750 5751 /** 5752 * Pooled class that orderes the children of a ViewGroup from start 5753 * to end based on how they are laid out and the layout direction. 5754 */ 5755 static class ChildListForAccessibility { 5756 5757 private static final int MAX_POOL_SIZE = 32; 5758 5759 private static final Object sPoolLock = new Object(); 5760 5761 private static ChildListForAccessibility sPool; 5762 5763 private static int sPoolSize; 5764 5765 private boolean mIsPooled; 5766 5767 private ChildListForAccessibility mNext; 5768 5769 private final ArrayList<View> mChildren = new ArrayList<View>(); 5770 5771 private final ArrayList<ViewLocationHolder> mHolders = new ArrayList<ViewLocationHolder>(); 5772 5773 public static ChildListForAccessibility obtain(ViewGroup parent, boolean sort) { 5774 ChildListForAccessibility list = null; 5775 synchronized (sPoolLock) { 5776 if (sPool != null) { 5777 list = sPool; 5778 sPool = list.mNext; 5779 list.mNext = null; 5780 list.mIsPooled = false; 5781 sPoolSize--; 5782 } else { 5783 list = new ChildListForAccessibility(); 5784 } 5785 list.init(parent, sort); 5786 return list; 5787 } 5788 } 5789 5790 public void recycle() { 5791 if (mIsPooled) { 5792 throw new IllegalStateException("Instance already recycled."); 5793 } 5794 clear(); 5795 if (sPoolSize < MAX_POOL_SIZE) { 5796 mNext = sPool; 5797 mIsPooled = true; 5798 sPool = this; 5799 sPoolSize++; 5800 } 5801 } 5802 5803 public int getChildCount() { 5804 return mChildren.size(); 5805 } 5806 5807 public View getChildAt(int index) { 5808 return mChildren.get(index); 5809 } 5810 5811 public int getChildIndex(View child) { 5812 return mChildren.indexOf(child); 5813 } 5814 5815 private void init(ViewGroup parent, boolean sort) { 5816 ArrayList<View> children = mChildren; 5817 final int childCount = parent.getChildCount(); 5818 for (int i = 0; i < childCount; i++) { 5819 View child = parent.getChildAt(i); 5820 children.add(child); 5821 } 5822 if (sort) { 5823 ArrayList<ViewLocationHolder> holders = mHolders; 5824 for (int i = 0; i < childCount; i++) { 5825 View child = children.get(i); 5826 ViewLocationHolder holder = ViewLocationHolder.obtain(parent, child); 5827 holders.add(holder); 5828 } 5829 Collections.sort(holders); 5830 for (int i = 0; i < childCount; i++) { 5831 ViewLocationHolder holder = holders.get(i); 5832 children.set(i, holder.mView); 5833 holder.recycle(); 5834 } 5835 holders.clear(); 5836 } 5837 } 5838 5839 private void clear() { 5840 mChildren.clear(); 5841 } 5842 } 5843 5844 /** 5845 * Pooled class that holds a View and its location with respect to 5846 * a specified root. This enables sorting of views based on their 5847 * coordinates without recomputing the position relative to the root 5848 * on every comparison. 5849 */ 5850 static class ViewLocationHolder implements Comparable<ViewLocationHolder> { 5851 5852 private static final int MAX_POOL_SIZE = 32; 5853 5854 private static final Object sPoolLock = new Object(); 5855 5856 private static ViewLocationHolder sPool; 5857 5858 private static int sPoolSize; 5859 5860 private boolean mIsPooled; 5861 5862 private ViewLocationHolder mNext; 5863 5864 private final Rect mLocation = new Rect(); 5865 5866 public View mView; 5867 5868 private int mLayoutDirection; 5869 5870 public static ViewLocationHolder obtain(ViewGroup root, View view) { 5871 ViewLocationHolder holder = null; 5872 synchronized (sPoolLock) { 5873 if (sPool != null) { 5874 holder = sPool; 5875 sPool = holder.mNext; 5876 holder.mNext = null; 5877 holder.mIsPooled = false; 5878 sPoolSize--; 5879 } else { 5880 holder = new ViewLocationHolder(); 5881 } 5882 holder.init(root, view); 5883 return holder; 5884 } 5885 } 5886 5887 public void recycle() { 5888 if (mIsPooled) { 5889 throw new IllegalStateException("Instance already recycled."); 5890 } 5891 clear(); 5892 if (sPoolSize < MAX_POOL_SIZE) { 5893 mNext = sPool; 5894 mIsPooled = true; 5895 sPool = this; 5896 sPoolSize++; 5897 } 5898 } 5899 5900 @Override 5901 public int compareTo(ViewLocationHolder another) { 5902 // This instance is greater than an invalid argument. 5903 if (another == null) { 5904 return 1; 5905 } 5906 if (getClass() != another.getClass()) { 5907 return 1; 5908 } 5909 // First is above second. 5910 if (mLocation.bottom - another.mLocation.top <= 0) { 5911 return -1; 5912 } 5913 // First is below second. 5914 if (mLocation.top - another.mLocation.bottom >= 0) { 5915 return 1; 5916 } 5917 // LTR 5918 if (mLayoutDirection == LAYOUT_DIRECTION_LTR) { 5919 final int leftDifference = mLocation.left - another.mLocation.left; 5920 // First more to the left than second. 5921 if (leftDifference != 0) { 5922 return leftDifference; 5923 } 5924 } else { // RTL 5925 final int rightDifference = mLocation.right - another.mLocation.right; 5926 // First more to the right than second. 5927 if (rightDifference != 0) { 5928 return -rightDifference; 5929 } 5930 } 5931 // Break tie by top. 5932 final int topDiference = mLocation.top - another.mLocation.top; 5933 if (topDiference != 0) { 5934 return topDiference; 5935 } 5936 // Break tie by height. 5937 final int heightDiference = mLocation.height() - another.mLocation.height(); 5938 if (heightDiference != 0) { 5939 return -heightDiference; 5940 } 5941 // Break tie by width. 5942 final int widthDiference = mLocation.width() - another.mLocation.width(); 5943 if (widthDiference != 0) { 5944 return -widthDiference; 5945 } 5946 // Return nondeterministically one of them since we do 5947 // not want to ignore any views. 5948 return 1; 5949 } 5950 5951 private void init(ViewGroup root, View view) { 5952 Rect viewLocation = mLocation; 5953 view.getDrawingRect(viewLocation); 5954 root.offsetDescendantRectToMyCoords(view, viewLocation); 5955 mView = view; 5956 mLayoutDirection = root.getResolvedLayoutDirection(); 5957 } 5958 5959 private void clear() { 5960 mView = null; 5961 mLocation.set(0, 0, 0, 0); 5962 } 5963 } 5964} 5965