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