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