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