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