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