ViewGroup.java revision bc8a8e8c926115cb7b3910d016e5cff12b0f7b0a
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 final int scrollX = hasDisplayList ? 0 : sx; 2526 final int scrollY = hasDisplayList ? 0 : sy; 2527 canvas.saveLayerAlpha(scrollX, scrollY, scrollX + cr - cl, 2528 scrollY + cb - ct, multipliedAlpha, layerFlags); 2529 } 2530 } else { 2531 // Alpha is handled by the child directly, clobber the layer's alpha 2532 child.mPrivateFlags |= ALPHA_SET; 2533 } 2534 } 2535 } 2536 } else if ((child.mPrivateFlags & ALPHA_SET) == ALPHA_SET) { 2537 child.onSetAlpha(255); 2538 child.mPrivateFlags &= ~ALPHA_SET; 2539 } 2540 2541 if ((flags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) { 2542 if (offsetForScroll) { 2543 canvas.clipRect(sx, sy, sx + (cr - cl), sy + (cb - ct)); 2544 } else { 2545 if (!scalingRequired || cache == null) { 2546 canvas.clipRect(0, 0, cr - cl, cb - ct); 2547 } else { 2548 canvas.clipRect(0, 0, cache.getWidth(), cache.getHeight()); 2549 } 2550 } 2551 } 2552 2553 if (hasDisplayList) { 2554 displayList = child.getDisplayList(); 2555 } 2556 2557 if (hasNoCache) { 2558 boolean layerRendered = false; 2559 if (layerType == LAYER_TYPE_HARDWARE) { 2560 final HardwareLayer layer = child.getHardwareLayer(); 2561 if (layer != null && layer.isValid()) { 2562 child.mLayerPaint.setAlpha((int) (alpha * 255)); 2563 ((HardwareCanvas) canvas).drawHardwareLayer(layer, 0, 0, child.mLayerPaint); 2564 layerRendered = true; 2565 } else { 2566 final int scrollX = hasDisplayList ? 0 : sx; 2567 final int scrollY = hasDisplayList ? 0 : sy; 2568 canvas.saveLayer(scrollX, scrollY, 2569 scrollX + cr - cl, scrollY + cb - ct, child.mLayerPaint, 2570 Canvas.HAS_ALPHA_LAYER_SAVE_FLAG | Canvas.CLIP_TO_LAYER_SAVE_FLAG); 2571 } 2572 } 2573 2574 if (!layerRendered) { 2575 if (!hasDisplayList) { 2576 // Fast path for layouts with no backgrounds 2577 if ((child.mPrivateFlags & SKIP_DRAW) == SKIP_DRAW) { 2578 if (ViewDebug.TRACE_HIERARCHY) { 2579 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.DRAW); 2580 } 2581 child.mPrivateFlags &= ~DIRTY_MASK; 2582 child.dispatchDraw(canvas); 2583 } else { 2584 child.draw(canvas); 2585 } 2586 } else { 2587 child.mPrivateFlags &= ~DIRTY_MASK; 2588 ((HardwareCanvas) canvas).drawDisplayList(displayList, null); 2589 } 2590 } 2591 } else if (cache != null) { 2592 child.mPrivateFlags &= ~DIRTY_MASK; 2593 Paint cachePaint; 2594 2595 if (layerType == LAYER_TYPE_NONE) { 2596 cachePaint = mCachePaint; 2597 if (alpha < 1.0f) { 2598 cachePaint.setAlpha((int) (alpha * 255)); 2599 mGroupFlags |= FLAG_ALPHA_LOWER_THAN_ONE; 2600 } else if ((flags & FLAG_ALPHA_LOWER_THAN_ONE) == FLAG_ALPHA_LOWER_THAN_ONE) { 2601 cachePaint.setAlpha(255); 2602 mGroupFlags &= ~FLAG_ALPHA_LOWER_THAN_ONE; 2603 } 2604 } else { 2605 cachePaint = child.mLayerPaint; 2606 cachePaint.setAlpha((int) (alpha * 255)); 2607 } 2608 canvas.drawBitmap(cache, 0.0f, 0.0f, cachePaint); 2609 } 2610 2611 canvas.restoreToCount(restoreTo); 2612 2613 if (a != null && !more) { 2614 if (!hardwareAccelerated && !a.getFillAfter()) { 2615 child.onSetAlpha(255); 2616 } 2617 finishAnimatingView(child, a); 2618 } 2619 2620 if (more && hardwareAccelerated) { 2621 // invalidation is the trigger to recreate display lists, so if we're using 2622 // display lists to render, force an invalidate to allow the animation to 2623 // continue drawing another frame 2624 invalidate(true); 2625 if (a instanceof AlphaAnimation) { 2626 // alpha animations should cause the child to recreate its display list 2627 child.invalidate(true); 2628 } 2629 } 2630 2631 child.mRecreateDisplayList = false; 2632 2633 return more; 2634 } 2635 2636 /** 2637 * 2638 * @param enabled True if children should be drawn with layers, false otherwise. 2639 * 2640 * @hide 2641 */ 2642 public void setChildrenLayersEnabled(boolean enabled) { 2643 if (enabled != mDrawLayers) { 2644 mDrawLayers = enabled; 2645 invalidate(true); 2646 2647 // We need to invalidate any child with a layer. For instance, 2648 // if a child is backed by a hardware layer and we disable layers 2649 // the child is marked as not dirty (flags cleared the last time 2650 // the child was drawn inside its layer.) However, that child might 2651 // never have created its own display list or have an obsolete 2652 // display list. By invalidating the child we ensure the display 2653 // list is in sync with the content of the hardware layer. 2654 for (int i = 0; i < mChildrenCount; i++) { 2655 View child = mChildren[i]; 2656 if (child.mLayerType != LAYER_TYPE_NONE) { 2657 child.invalidate(true); 2658 } 2659 } 2660 } 2661 } 2662 2663 /** 2664 * By default, children are clipped to their bounds before drawing. This 2665 * allows view groups to override this behavior for animations, etc. 2666 * 2667 * @param clipChildren true to clip children to their bounds, 2668 * false otherwise 2669 * @attr ref android.R.styleable#ViewGroup_clipChildren 2670 */ 2671 public void setClipChildren(boolean clipChildren) { 2672 setBooleanFlag(FLAG_CLIP_CHILDREN, clipChildren); 2673 } 2674 2675 /** 2676 * By default, children are clipped to the padding of the ViewGroup. This 2677 * allows view groups to override this behavior 2678 * 2679 * @param clipToPadding true to clip children to the padding of the 2680 * group, false otherwise 2681 * @attr ref android.R.styleable#ViewGroup_clipToPadding 2682 */ 2683 public void setClipToPadding(boolean clipToPadding) { 2684 setBooleanFlag(FLAG_CLIP_TO_PADDING, clipToPadding); 2685 } 2686 2687 /** 2688 * {@inheritDoc} 2689 */ 2690 @Override 2691 public void dispatchSetSelected(boolean selected) { 2692 final View[] children = mChildren; 2693 final int count = mChildrenCount; 2694 for (int i = 0; i < count; i++) { 2695 children[i].setSelected(selected); 2696 } 2697 } 2698 2699 /** 2700 * {@inheritDoc} 2701 */ 2702 @Override 2703 public void dispatchSetActivated(boolean activated) { 2704 final View[] children = mChildren; 2705 final int count = mChildrenCount; 2706 for (int i = 0; i < count; i++) { 2707 children[i].setActivated(activated); 2708 } 2709 } 2710 2711 @Override 2712 protected void dispatchSetPressed(boolean pressed) { 2713 final View[] children = mChildren; 2714 final int count = mChildrenCount; 2715 for (int i = 0; i < count; i++) { 2716 children[i].setPressed(pressed); 2717 } 2718 } 2719 2720 /** 2721 * When this property is set to true, this ViewGroup supports static transformations on 2722 * children; this causes 2723 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be 2724 * invoked when a child is drawn. 2725 * 2726 * Any subclass overriding 2727 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should 2728 * set this property to true. 2729 * 2730 * @param enabled True to enable static transformations on children, false otherwise. 2731 * 2732 * @see #FLAG_SUPPORT_STATIC_TRANSFORMATIONS 2733 */ 2734 protected void setStaticTransformationsEnabled(boolean enabled) { 2735 setBooleanFlag(FLAG_SUPPORT_STATIC_TRANSFORMATIONS, enabled); 2736 } 2737 2738 /** 2739 * {@inheritDoc} 2740 * 2741 * @see #setStaticTransformationsEnabled(boolean) 2742 */ 2743 protected boolean getChildStaticTransformation(View child, Transformation t) { 2744 return false; 2745 } 2746 2747 /** 2748 * {@hide} 2749 */ 2750 @Override 2751 protected View findViewTraversal(int id) { 2752 if (id == mID) { 2753 return this; 2754 } 2755 2756 final View[] where = mChildren; 2757 final int len = mChildrenCount; 2758 2759 for (int i = 0; i < len; i++) { 2760 View v = where[i]; 2761 2762 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 2763 v = v.findViewById(id); 2764 2765 if (v != null) { 2766 return v; 2767 } 2768 } 2769 } 2770 2771 return null; 2772 } 2773 2774 /** 2775 * {@hide} 2776 */ 2777 @Override 2778 protected View findViewWithTagTraversal(Object tag) { 2779 if (tag != null && tag.equals(mTag)) { 2780 return this; 2781 } 2782 2783 final View[] where = mChildren; 2784 final int len = mChildrenCount; 2785 2786 for (int i = 0; i < len; i++) { 2787 View v = where[i]; 2788 2789 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 2790 v = v.findViewWithTag(tag); 2791 2792 if (v != null) { 2793 return v; 2794 } 2795 } 2796 } 2797 2798 return null; 2799 } 2800 2801 /** 2802 * {@hide} 2803 */ 2804 @Override 2805 protected View findViewByPredicateTraversal(Predicate<View> predicate) { 2806 if (predicate.apply(this)) { 2807 return this; 2808 } 2809 2810 final View[] where = mChildren; 2811 final int len = mChildrenCount; 2812 2813 for (int i = 0; i < len; i++) { 2814 View v = where[i]; 2815 2816 if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { 2817 v = v.findViewByPredicate(predicate); 2818 2819 if (v != null) { 2820 return v; 2821 } 2822 } 2823 } 2824 2825 return null; 2826 } 2827 2828 /** 2829 * Adds a child view. If no layout parameters are already set on the child, the 2830 * default parameters for this ViewGroup are set on the child. 2831 * 2832 * @param child the child view to add 2833 * 2834 * @see #generateDefaultLayoutParams() 2835 */ 2836 public void addView(View child) { 2837 addView(child, -1); 2838 } 2839 2840 /** 2841 * Adds a child view. If no layout parameters are already set on the child, the 2842 * default parameters for this ViewGroup are set on the child. 2843 * 2844 * @param child the child view to add 2845 * @param index the position at which to add the child 2846 * 2847 * @see #generateDefaultLayoutParams() 2848 */ 2849 public void addView(View child, int index) { 2850 LayoutParams params = child.getLayoutParams(); 2851 if (params == null) { 2852 params = generateDefaultLayoutParams(); 2853 if (params == null) { 2854 throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); 2855 } 2856 } 2857 addView(child, index, params); 2858 } 2859 2860 /** 2861 * Adds a child view with this ViewGroup's default layout parameters and the 2862 * specified width and height. 2863 * 2864 * @param child the child view to add 2865 */ 2866 public void addView(View child, int width, int height) { 2867 final LayoutParams params = generateDefaultLayoutParams(); 2868 params.width = width; 2869 params.height = height; 2870 addView(child, -1, params); 2871 } 2872 2873 /** 2874 * Adds a child view with the specified layout parameters. 2875 * 2876 * @param child the child view to add 2877 * @param params the layout parameters to set on the child 2878 */ 2879 public void addView(View child, LayoutParams params) { 2880 addView(child, -1, params); 2881 } 2882 2883 /** 2884 * Adds a child view with the specified layout parameters. 2885 * 2886 * @param child the child view to add 2887 * @param index the position at which to add the child 2888 * @param params the layout parameters to set on the child 2889 */ 2890 public void addView(View child, int index, LayoutParams params) { 2891 if (DBG) { 2892 System.out.println(this + " addView"); 2893 } 2894 2895 // addViewInner() will call child.requestLayout() when setting the new LayoutParams 2896 // therefore, we call requestLayout() on ourselves before, so that the child's request 2897 // will be blocked at our level 2898 requestLayout(); 2899 invalidate(true); 2900 addViewInner(child, index, params, false); 2901 } 2902 2903 /** 2904 * {@inheritDoc} 2905 */ 2906 public void updateViewLayout(View view, ViewGroup.LayoutParams params) { 2907 if (!checkLayoutParams(params)) { 2908 throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this); 2909 } 2910 if (view.mParent != this) { 2911 throw new IllegalArgumentException("Given view not a child of " + this); 2912 } 2913 view.setLayoutParams(params); 2914 } 2915 2916 /** 2917 * {@inheritDoc} 2918 */ 2919 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 2920 return p != null; 2921 } 2922 2923 /** 2924 * Interface definition for a callback to be invoked when the hierarchy 2925 * within this view changed. The hierarchy changes whenever a child is added 2926 * to or removed from this view. 2927 */ 2928 public interface OnHierarchyChangeListener { 2929 /** 2930 * Called when a new child is added to a parent view. 2931 * 2932 * @param parent the view in which a child was added 2933 * @param child the new child view added in the hierarchy 2934 */ 2935 void onChildViewAdded(View parent, View child); 2936 2937 /** 2938 * Called when a child is removed from a parent view. 2939 * 2940 * @param parent the view from which the child was removed 2941 * @param child the child removed from the hierarchy 2942 */ 2943 void onChildViewRemoved(View parent, View child); 2944 } 2945 2946 /** 2947 * Register a callback to be invoked when a child is added to or removed 2948 * from this view. 2949 * 2950 * @param listener the callback to invoke on hierarchy change 2951 */ 2952 public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) { 2953 mOnHierarchyChangeListener = listener; 2954 } 2955 2956 /** 2957 * Adds a view during layout. This is useful if in your onLayout() method, 2958 * you need to add more views (as does the list view for example). 2959 * 2960 * If index is negative, it means put it at the end of the list. 2961 * 2962 * @param child the view to add to the group 2963 * @param index the index at which the child must be added 2964 * @param params the layout parameters to associate with the child 2965 * @return true if the child was added, false otherwise 2966 */ 2967 protected boolean addViewInLayout(View child, int index, LayoutParams params) { 2968 return addViewInLayout(child, index, params, false); 2969 } 2970 2971 /** 2972 * Adds a view during layout. This is useful if in your onLayout() method, 2973 * you need to add more views (as does the list view for example). 2974 * 2975 * If index is negative, it means put it at the end of the list. 2976 * 2977 * @param child the view to add to the group 2978 * @param index the index at which the child must be added 2979 * @param params the layout parameters to associate with the child 2980 * @param preventRequestLayout if true, calling this method will not trigger a 2981 * layout request on child 2982 * @return true if the child was added, false otherwise 2983 */ 2984 protected boolean addViewInLayout(View child, int index, LayoutParams params, 2985 boolean preventRequestLayout) { 2986 child.mParent = null; 2987 addViewInner(child, index, params, preventRequestLayout); 2988 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK) | DRAWN; 2989 return true; 2990 } 2991 2992 /** 2993 * Prevents the specified child to be laid out during the next layout pass. 2994 * 2995 * @param child the child on which to perform the cleanup 2996 */ 2997 protected void cleanupLayoutState(View child) { 2998 child.mPrivateFlags &= ~View.FORCE_LAYOUT; 2999 } 3000 3001 private void addViewInner(View child, int index, LayoutParams params, 3002 boolean preventRequestLayout) { 3003 3004 if (mTransition != null) { 3005 // Don't prevent other add transitions from completing, but cancel remove 3006 // transitions to let them complete the process before we add to the container 3007 mTransition.cancel(LayoutTransition.DISAPPEARING); 3008 } 3009 3010 if (child.getParent() != null) { 3011 throw new IllegalStateException("The specified child already has a parent. " + 3012 "You must call removeView() on the child's parent first."); 3013 } 3014 3015 if (mTransition != null) { 3016 mTransition.addChild(this, child); 3017 } 3018 3019 if (!checkLayoutParams(params)) { 3020 params = generateLayoutParams(params); 3021 } 3022 3023 if (preventRequestLayout) { 3024 child.mLayoutParams = params; 3025 } else { 3026 child.setLayoutParams(params); 3027 } 3028 3029 if (index < 0) { 3030 index = mChildrenCount; 3031 } 3032 3033 addInArray(child, index); 3034 3035 // tell our children 3036 if (preventRequestLayout) { 3037 child.assignParent(this); 3038 } else { 3039 child.mParent = this; 3040 } 3041 3042 if (child.hasFocus()) { 3043 requestChildFocus(child, child.findFocus()); 3044 } 3045 3046 AttachInfo ai = mAttachInfo; 3047 if (ai != null) { 3048 boolean lastKeepOn = ai.mKeepScreenOn; 3049 ai.mKeepScreenOn = false; 3050 child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK)); 3051 if (ai.mKeepScreenOn) { 3052 needGlobalAttributesUpdate(true); 3053 } 3054 ai.mKeepScreenOn = lastKeepOn; 3055 } 3056 3057 if (mOnHierarchyChangeListener != null) { 3058 mOnHierarchyChangeListener.onChildViewAdded(this, child); 3059 } 3060 3061 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) { 3062 mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE; 3063 } 3064 } 3065 3066 private void addInArray(View child, int index) { 3067 View[] children = mChildren; 3068 final int count = mChildrenCount; 3069 final int size = children.length; 3070 if (index == count) { 3071 if (size == count) { 3072 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 3073 System.arraycopy(children, 0, mChildren, 0, size); 3074 children = mChildren; 3075 } 3076 children[mChildrenCount++] = child; 3077 } else if (index < count) { 3078 if (size == count) { 3079 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 3080 System.arraycopy(children, 0, mChildren, 0, index); 3081 System.arraycopy(children, index, mChildren, index + 1, count - index); 3082 children = mChildren; 3083 } else { 3084 System.arraycopy(children, index, children, index + 1, count - index); 3085 } 3086 children[index] = child; 3087 mChildrenCount++; 3088 if (mLastTouchDownIndex >= index) { 3089 mLastTouchDownIndex++; 3090 } 3091 } else { 3092 throw new IndexOutOfBoundsException("index=" + index + " count=" + count); 3093 } 3094 } 3095 3096 // This method also sets the child's mParent to null 3097 private void removeFromArray(int index) { 3098 final View[] children = mChildren; 3099 if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) { 3100 children[index].mParent = null; 3101 } 3102 final int count = mChildrenCount; 3103 if (index == count - 1) { 3104 children[--mChildrenCount] = null; 3105 } else if (index >= 0 && index < count) { 3106 System.arraycopy(children, index + 1, children, index, count - index - 1); 3107 children[--mChildrenCount] = null; 3108 } else { 3109 throw new IndexOutOfBoundsException(); 3110 } 3111 if (mLastTouchDownIndex == index) { 3112 mLastTouchDownTime = 0; 3113 mLastTouchDownIndex = -1; 3114 } else if (mLastTouchDownIndex > index) { 3115 mLastTouchDownIndex--; 3116 } 3117 } 3118 3119 // This method also sets the children's mParent to null 3120 private void removeFromArray(int start, int count) { 3121 final View[] children = mChildren; 3122 final int childrenCount = mChildrenCount; 3123 3124 start = Math.max(0, start); 3125 final int end = Math.min(childrenCount, start + count); 3126 3127 if (start == end) { 3128 return; 3129 } 3130 3131 if (end == childrenCount) { 3132 for (int i = start; i < end; i++) { 3133 children[i].mParent = null; 3134 children[i] = null; 3135 } 3136 } else { 3137 for (int i = start; i < end; i++) { 3138 children[i].mParent = null; 3139 } 3140 3141 // Since we're looping above, we might as well do the copy, but is arraycopy() 3142 // faster than the extra 2 bounds checks we would do in the loop? 3143 System.arraycopy(children, end, children, start, childrenCount - end); 3144 3145 for (int i = childrenCount - (end - start); i < childrenCount; i++) { 3146 children[i] = null; 3147 } 3148 } 3149 3150 mChildrenCount -= (end - start); 3151 } 3152 3153 private void bindLayoutAnimation(View child) { 3154 Animation a = mLayoutAnimationController.getAnimationForView(child); 3155 child.setAnimation(a); 3156 } 3157 3158 /** 3159 * Subclasses should override this method to set layout animation 3160 * parameters on the supplied child. 3161 * 3162 * @param child the child to associate with animation parameters 3163 * @param params the child's layout parameters which hold the animation 3164 * parameters 3165 * @param index the index of the child in the view group 3166 * @param count the number of children in the view group 3167 */ 3168 protected void attachLayoutAnimationParameters(View child, 3169 LayoutParams params, int index, int count) { 3170 LayoutAnimationController.AnimationParameters animationParams = 3171 params.layoutAnimationParameters; 3172 if (animationParams == null) { 3173 animationParams = new LayoutAnimationController.AnimationParameters(); 3174 params.layoutAnimationParameters = animationParams; 3175 } 3176 3177 animationParams.count = count; 3178 animationParams.index = index; 3179 } 3180 3181 /** 3182 * {@inheritDoc} 3183 */ 3184 public void removeView(View view) { 3185 removeViewInternal(view); 3186 requestLayout(); 3187 invalidate(true); 3188 } 3189 3190 /** 3191 * Removes a view during layout. This is useful if in your onLayout() method, 3192 * you need to remove more views. 3193 * 3194 * @param view the view to remove from the group 3195 */ 3196 public void removeViewInLayout(View view) { 3197 removeViewInternal(view); 3198 } 3199 3200 /** 3201 * Removes a range of views during layout. This is useful if in your onLayout() method, 3202 * you need to remove more views. 3203 * 3204 * @param start the index of the first view to remove from the group 3205 * @param count the number of views to remove from the group 3206 */ 3207 public void removeViewsInLayout(int start, int count) { 3208 removeViewsInternal(start, count); 3209 } 3210 3211 /** 3212 * Removes the view at the specified position in the group. 3213 * 3214 * @param index the position in the group of the view to remove 3215 */ 3216 public void removeViewAt(int index) { 3217 removeViewInternal(index, getChildAt(index)); 3218 requestLayout(); 3219 invalidate(true); 3220 } 3221 3222 /** 3223 * Removes the specified range of views from the group. 3224 * 3225 * @param start the first position in the group of the range of views to remove 3226 * @param count the number of views to remove 3227 */ 3228 public void removeViews(int start, int count) { 3229 removeViewsInternal(start, count); 3230 requestLayout(); 3231 invalidate(true); 3232 } 3233 3234 private void removeViewInternal(View view) { 3235 final int index = indexOfChild(view); 3236 if (index >= 0) { 3237 removeViewInternal(index, view); 3238 } 3239 } 3240 3241 private void removeViewInternal(int index, View view) { 3242 3243 if (mTransition != null) { 3244 mTransition.removeChild(this, view); 3245 } 3246 3247 boolean clearChildFocus = false; 3248 if (view == mFocused) { 3249 view.clearFocusForRemoval(); 3250 clearChildFocus = true; 3251 } 3252 3253 if (view.getAnimation() != null || 3254 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3255 addDisappearingView(view); 3256 } else if (view.mAttachInfo != null) { 3257 view.dispatchDetachedFromWindow(); 3258 } 3259 3260 if (mOnHierarchyChangeListener != null) { 3261 mOnHierarchyChangeListener.onChildViewRemoved(this, view); 3262 } 3263 3264 needGlobalAttributesUpdate(false); 3265 3266 removeFromArray(index); 3267 3268 if (clearChildFocus) { 3269 clearChildFocus(view); 3270 } 3271 } 3272 3273 /** 3274 * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3275 * not null, changes in layout which occur because of children being added to or removed from 3276 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3277 * object. By default, the transition object is null (so layout changes are not animated). 3278 * 3279 * @param transition The LayoutTransition object that will animated changes in layout. A value 3280 * of <code>null</code> means no transition will run on layout changes. 3281 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges 3282 */ 3283 public void setLayoutTransition(LayoutTransition transition) { 3284 if (mTransition != null) { 3285 mTransition.removeTransitionListener(mLayoutTransitionListener); 3286 } 3287 mTransition = transition; 3288 if (mTransition != null) { 3289 mTransition.addTransitionListener(mLayoutTransitionListener); 3290 } 3291 } 3292 3293 /** 3294 * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3295 * not null, changes in layout which occur because of children being added to or removed from 3296 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3297 * object. By default, the transition object is null (so layout changes are not animated). 3298 * 3299 * @return LayoutTranstion The LayoutTransition object that will animated changes in layout. 3300 * A value of <code>null</code> means no transition will run on layout changes. 3301 */ 3302 public LayoutTransition getLayoutTransition() { 3303 return mTransition; 3304 } 3305 3306 private void removeViewsInternal(int start, int count) { 3307 final OnHierarchyChangeListener onHierarchyChangeListener = mOnHierarchyChangeListener; 3308 final boolean notifyListener = onHierarchyChangeListener != null; 3309 final View focused = mFocused; 3310 final boolean detach = mAttachInfo != null; 3311 View clearChildFocus = null; 3312 3313 final View[] children = mChildren; 3314 final int end = start + count; 3315 3316 for (int i = start; i < end; i++) { 3317 final View view = children[i]; 3318 3319 if (mTransition != null) { 3320 mTransition.removeChild(this, view); 3321 } 3322 3323 if (view == focused) { 3324 view.clearFocusForRemoval(); 3325 clearChildFocus = view; 3326 } 3327 3328 if (view.getAnimation() != null || 3329 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3330 addDisappearingView(view); 3331 } else if (detach) { 3332 view.dispatchDetachedFromWindow(); 3333 } 3334 3335 needGlobalAttributesUpdate(false); 3336 3337 if (notifyListener) { 3338 onHierarchyChangeListener.onChildViewRemoved(this, view); 3339 } 3340 } 3341 3342 removeFromArray(start, count); 3343 3344 if (clearChildFocus != null) { 3345 clearChildFocus(clearChildFocus); 3346 } 3347 } 3348 3349 /** 3350 * Call this method to remove all child views from the 3351 * ViewGroup. 3352 */ 3353 public void removeAllViews() { 3354 removeAllViewsInLayout(); 3355 requestLayout(); 3356 invalidate(true); 3357 } 3358 3359 /** 3360 * Called by a ViewGroup subclass to remove child views from itself, 3361 * when it must first know its size on screen before it can calculate how many 3362 * child views it will render. An example is a Gallery or a ListView, which 3363 * may "have" 50 children, but actually only render the number of children 3364 * that can currently fit inside the object on screen. Do not call 3365 * this method unless you are extending ViewGroup and understand the 3366 * view measuring and layout pipeline. 3367 */ 3368 public void removeAllViewsInLayout() { 3369 final int count = mChildrenCount; 3370 if (count <= 0) { 3371 return; 3372 } 3373 3374 final View[] children = mChildren; 3375 mChildrenCount = 0; 3376 3377 final OnHierarchyChangeListener listener = mOnHierarchyChangeListener; 3378 final boolean notify = listener != null; 3379 final View focused = mFocused; 3380 final boolean detach = mAttachInfo != null; 3381 View clearChildFocus = null; 3382 3383 needGlobalAttributesUpdate(false); 3384 3385 for (int i = count - 1; i >= 0; i--) { 3386 final View view = children[i]; 3387 3388 if (mTransition != null) { 3389 mTransition.removeChild(this, view); 3390 } 3391 3392 if (view == focused) { 3393 view.clearFocusForRemoval(); 3394 clearChildFocus = view; 3395 } 3396 3397 if (view.getAnimation() != null || 3398 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3399 addDisappearingView(view); 3400 } else if (detach) { 3401 view.dispatchDetachedFromWindow(); 3402 } 3403 3404 if (notify) { 3405 listener.onChildViewRemoved(this, view); 3406 } 3407 3408 view.mParent = null; 3409 children[i] = null; 3410 } 3411 3412 if (clearChildFocus != null) { 3413 clearChildFocus(clearChildFocus); 3414 } 3415 } 3416 3417 /** 3418 * Finishes the removal of a detached view. This method will dispatch the detached from 3419 * window event and notify the hierarchy change listener. 3420 * 3421 * @param child the child to be definitely removed from the view hierarchy 3422 * @param animate if true and the view has an animation, the view is placed in the 3423 * disappearing views list, otherwise, it is detached from the window 3424 * 3425 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3426 * @see #detachAllViewsFromParent() 3427 * @see #detachViewFromParent(View) 3428 * @see #detachViewFromParent(int) 3429 */ 3430 protected void removeDetachedView(View child, boolean animate) { 3431 if (mTransition != null) { 3432 mTransition.removeChild(this, child); 3433 } 3434 3435 if (child == mFocused) { 3436 child.clearFocus(); 3437 } 3438 3439 if ((animate && child.getAnimation() != null) || 3440 (mTransitioningViews != null && mTransitioningViews.contains(child))) { 3441 addDisappearingView(child); 3442 } else if (child.mAttachInfo != null) { 3443 child.dispatchDetachedFromWindow(); 3444 } 3445 3446 if (mOnHierarchyChangeListener != null) { 3447 mOnHierarchyChangeListener.onChildViewRemoved(this, child); 3448 } 3449 } 3450 3451 /** 3452 * Attaches a view to this view group. Attaching a view assigns this group as the parent, 3453 * sets the layout parameters and puts the view in the list of children so it can be retrieved 3454 * by calling {@link #getChildAt(int)}. 3455 * 3456 * This method should be called only for view which were detached from their parent. 3457 * 3458 * @param child the child to attach 3459 * @param index the index at which the child should be attached 3460 * @param params the layout parameters of the child 3461 * 3462 * @see #removeDetachedView(View, boolean) 3463 * @see #detachAllViewsFromParent() 3464 * @see #detachViewFromParent(View) 3465 * @see #detachViewFromParent(int) 3466 */ 3467 protected void attachViewToParent(View child, int index, LayoutParams params) { 3468 child.mLayoutParams = params; 3469 3470 if (index < 0) { 3471 index = mChildrenCount; 3472 } 3473 3474 addInArray(child, index); 3475 3476 child.mParent = this; 3477 child.mPrivateFlags = (child.mPrivateFlags & ~DIRTY_MASK & ~DRAWING_CACHE_VALID) | 3478 DRAWN | INVALIDATED; 3479 this.mPrivateFlags |= INVALIDATED; 3480 3481 if (child.hasFocus()) { 3482 requestChildFocus(child, child.findFocus()); 3483 } 3484 } 3485 3486 /** 3487 * Detaches a view from its parent. Detaching a view should be temporary and followed 3488 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3489 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3490 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3491 * 3492 * @param child the child to detach 3493 * 3494 * @see #detachViewFromParent(int) 3495 * @see #detachViewsFromParent(int, int) 3496 * @see #detachAllViewsFromParent() 3497 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3498 * @see #removeDetachedView(View, boolean) 3499 */ 3500 protected void detachViewFromParent(View child) { 3501 removeFromArray(indexOfChild(child)); 3502 } 3503 3504 /** 3505 * Detaches a view from its parent. Detaching a view should be temporary and followed 3506 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3507 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3508 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3509 * 3510 * @param index the index of the child to detach 3511 * 3512 * @see #detachViewFromParent(View) 3513 * @see #detachAllViewsFromParent() 3514 * @see #detachViewsFromParent(int, int) 3515 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3516 * @see #removeDetachedView(View, boolean) 3517 */ 3518 protected void detachViewFromParent(int index) { 3519 removeFromArray(index); 3520 } 3521 3522 /** 3523 * Detaches a range of view from their parent. Detaching a view should be temporary and followed 3524 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3525 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, its 3526 * parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3527 * 3528 * @param start the first index of the childrend range to detach 3529 * @param count the number of children to detach 3530 * 3531 * @see #detachViewFromParent(View) 3532 * @see #detachViewFromParent(int) 3533 * @see #detachAllViewsFromParent() 3534 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3535 * @see #removeDetachedView(View, boolean) 3536 */ 3537 protected void detachViewsFromParent(int start, int count) { 3538 removeFromArray(start, count); 3539 } 3540 3541 /** 3542 * Detaches all views from the parent. Detaching a view should be temporary and followed 3543 * either by a call to {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 3544 * or a call to {@link #removeDetachedView(View, boolean)}. When a view is detached, 3545 * its parent is null and cannot be retrieved by a call to {@link #getChildAt(int)}. 3546 * 3547 * @see #detachViewFromParent(View) 3548 * @see #detachViewFromParent(int) 3549 * @see #detachViewsFromParent(int, int) 3550 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 3551 * @see #removeDetachedView(View, boolean) 3552 */ 3553 protected void detachAllViewsFromParent() { 3554 final int count = mChildrenCount; 3555 if (count <= 0) { 3556 return; 3557 } 3558 3559 final View[] children = mChildren; 3560 mChildrenCount = 0; 3561 3562 for (int i = count - 1; i >= 0; i--) { 3563 children[i].mParent = null; 3564 children[i] = null; 3565 } 3566 } 3567 3568 /** 3569 * Don't call or override this method. It is used for the implementation of 3570 * the view hierarchy. 3571 */ 3572 public final void invalidateChild(View child, final Rect dirty) { 3573 if (ViewDebug.TRACE_HIERARCHY) { 3574 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD); 3575 } 3576 3577 ViewParent parent = this; 3578 3579 final AttachInfo attachInfo = mAttachInfo; 3580 if (attachInfo != null) { 3581 // If the child is drawing an animation, we want to copy this flag onto 3582 // ourselves and the parent to make sure the invalidate request goes 3583 // through 3584 final boolean drawAnimation = (child.mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION; 3585 3586 if (dirty == null) { 3587 if (child.mLayerType != LAYER_TYPE_NONE) { 3588 mPrivateFlags |= INVALIDATED; 3589 mPrivateFlags &= ~DRAWING_CACHE_VALID; 3590 child.mLocalDirtyRect.setEmpty(); 3591 } 3592 do { 3593 View view = null; 3594 if (parent instanceof View) { 3595 view = (View) parent; 3596 if (view.mLayerType != LAYER_TYPE_NONE) { 3597 view.mLocalDirtyRect.setEmpty(); 3598 if (view.getParent() instanceof View) { 3599 final View grandParent = (View) view.getParent(); 3600 grandParent.mPrivateFlags |= INVALIDATED; 3601 grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID; 3602 } 3603 } 3604 if ((view.mPrivateFlags & DIRTY_MASK) != 0) { 3605 // already marked dirty - we're done 3606 break; 3607 } 3608 } 3609 3610 if (drawAnimation) { 3611 if (view != null) { 3612 view.mPrivateFlags |= DRAW_ANIMATION; 3613 } else if (parent instanceof ViewRoot) { 3614 ((ViewRoot) parent).mIsAnimating = true; 3615 } 3616 } 3617 3618 if (parent instanceof ViewRoot) { 3619 ((ViewRoot) parent).invalidate(); 3620 parent = null; 3621 } else if (view != null) { 3622 if ((view.mPrivateFlags & DRAWN) == DRAWN || 3623 (view.mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 3624 view.mPrivateFlags &= ~DRAWING_CACHE_VALID; 3625 view.mPrivateFlags |= DIRTY; 3626 parent = view.mParent; 3627 } else { 3628 parent = null; 3629 } 3630 } 3631 } while (parent != null); 3632 } else { 3633 // Check whether the child that requests the invalidate is fully opaque 3634 final boolean isOpaque = child.isOpaque() && !drawAnimation && 3635 child.getAnimation() == null; 3636 // Mark the child as dirty, using the appropriate flag 3637 // Make sure we do not set both flags at the same time 3638 int opaqueFlag = isOpaque ? DIRTY_OPAQUE : DIRTY; 3639 3640 if (child.mLayerType != LAYER_TYPE_NONE) { 3641 mPrivateFlags |= INVALIDATED; 3642 mPrivateFlags &= ~DRAWING_CACHE_VALID; 3643 child.mLocalDirtyRect.union(dirty); 3644 } 3645 3646 final int[] location = attachInfo.mInvalidateChildLocation; 3647 location[CHILD_LEFT_INDEX] = child.mLeft; 3648 location[CHILD_TOP_INDEX] = child.mTop; 3649 Matrix childMatrix = child.getMatrix(); 3650 if (!childMatrix.isIdentity()) { 3651 RectF boundingRect = attachInfo.mTmpTransformRect; 3652 boundingRect.set(dirty); 3653 childMatrix.mapRect(boundingRect); 3654 dirty.set((int) boundingRect.left, (int) boundingRect.top, 3655 (int) (boundingRect.right + 0.5f), 3656 (int) (boundingRect.bottom + 0.5f)); 3657 } 3658 3659 do { 3660 View view = null; 3661 if (parent instanceof View) { 3662 view = (View) parent; 3663 if (view.mLayerType != LAYER_TYPE_NONE && 3664 view.getParent() instanceof View) { 3665 final View grandParent = (View) view.getParent(); 3666 grandParent.mPrivateFlags |= INVALIDATED; 3667 grandParent.mPrivateFlags &= ~DRAWING_CACHE_VALID; 3668 } 3669 } 3670 3671 if (drawAnimation) { 3672 if (view != null) { 3673 view.mPrivateFlags |= DRAW_ANIMATION; 3674 } else if (parent instanceof ViewRoot) { 3675 ((ViewRoot) parent).mIsAnimating = true; 3676 } 3677 } 3678 3679 // If the parent is dirty opaque or not dirty, mark it dirty with the opaque 3680 // flag coming from the child that initiated the invalidate 3681 if (view != null) { 3682 if ((view.mViewFlags & FADING_EDGE_MASK) != 0 && 3683 view.getSolidColor() == 0 && !view.isOpaque()) { 3684 opaqueFlag = DIRTY; 3685 } 3686 if ((view.mPrivateFlags & DIRTY_MASK) != DIRTY) { 3687 view.mPrivateFlags = (view.mPrivateFlags & ~DIRTY_MASK) | opaqueFlag; 3688 } 3689 } 3690 3691 parent = parent.invalidateChildInParent(location, dirty); 3692 if (view != null) { 3693 // Account for transform on current parent 3694 Matrix m = view.getMatrix(); 3695 if (!m.isIdentity()) { 3696 RectF boundingRect = attachInfo.mTmpTransformRect; 3697 boundingRect.set(dirty); 3698 m.mapRect(boundingRect); 3699 dirty.set((int) boundingRect.left, (int) boundingRect.top, 3700 (int) (boundingRect.right + 0.5f), 3701 (int) (boundingRect.bottom + 0.5f)); 3702 } 3703 } 3704 } while (parent != null); 3705 } 3706 } 3707 } 3708 3709 /** 3710 * Don't call or override this method. It is used for the implementation of 3711 * the view hierarchy. 3712 * 3713 * This implementation returns null if this ViewGroup does not have a parent, 3714 * if this ViewGroup is already fully invalidated or if the dirty rectangle 3715 * does not intersect with this ViewGroup's bounds. 3716 */ 3717 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) { 3718 if (ViewDebug.TRACE_HIERARCHY) { 3719 ViewDebug.trace(this, ViewDebug.HierarchyTraceType.INVALIDATE_CHILD_IN_PARENT); 3720 } 3721 3722 if ((mPrivateFlags & DRAWN) == DRAWN || 3723 (mPrivateFlags & DRAWING_CACHE_VALID) == DRAWING_CACHE_VALID) { 3724 if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) != 3725 FLAG_OPTIMIZE_INVALIDATE) { 3726 dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX, 3727 location[CHILD_TOP_INDEX] - mScrollY); 3728 3729 final int left = mLeft; 3730 final int top = mTop; 3731 3732 if (dirty.intersect(0, 0, mRight - left, mBottom - top) || 3733 (mPrivateFlags & DRAW_ANIMATION) == DRAW_ANIMATION) { 3734 mPrivateFlags &= ~DRAWING_CACHE_VALID; 3735 3736 location[CHILD_LEFT_INDEX] = left; 3737 location[CHILD_TOP_INDEX] = top; 3738 3739 if (mLayerType != LAYER_TYPE_NONE) { 3740 mLocalDirtyRect.union(dirty); 3741 } 3742 3743 return mParent; 3744 } 3745 } else { 3746 mPrivateFlags &= ~DRAWN & ~DRAWING_CACHE_VALID; 3747 3748 location[CHILD_LEFT_INDEX] = mLeft; 3749 location[CHILD_TOP_INDEX] = mTop; 3750 3751 dirty.set(0, 0, mRight - mLeft, mBottom - mTop); 3752 3753 if (mLayerType != LAYER_TYPE_NONE) { 3754 mLocalDirtyRect.union(dirty); 3755 } 3756 3757 return mParent; 3758 } 3759 } 3760 3761 return null; 3762 } 3763 3764 /** 3765 * Offset a rectangle that is in a descendant's coordinate 3766 * space into our coordinate space. 3767 * @param descendant A descendant of this view 3768 * @param rect A rectangle defined in descendant's coordinate space. 3769 */ 3770 public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) { 3771 offsetRectBetweenParentAndChild(descendant, rect, true, false); 3772 } 3773 3774 /** 3775 * Offset a rectangle that is in our coordinate space into an ancestor's 3776 * coordinate space. 3777 * @param descendant A descendant of this view 3778 * @param rect A rectangle defined in descendant's coordinate space. 3779 */ 3780 public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) { 3781 offsetRectBetweenParentAndChild(descendant, rect, false, false); 3782 } 3783 3784 /** 3785 * Helper method that offsets a rect either from parent to descendant or 3786 * descendant to parent. 3787 */ 3788 void offsetRectBetweenParentAndChild(View descendant, Rect rect, 3789 boolean offsetFromChildToParent, boolean clipToBounds) { 3790 3791 // already in the same coord system :) 3792 if (descendant == this) { 3793 return; 3794 } 3795 3796 ViewParent theParent = descendant.mParent; 3797 3798 // search and offset up to the parent 3799 while ((theParent != null) 3800 && (theParent instanceof View) 3801 && (theParent != this)) { 3802 3803 if (offsetFromChildToParent) { 3804 rect.offset(descendant.mLeft - descendant.mScrollX, 3805 descendant.mTop - descendant.mScrollY); 3806 if (clipToBounds) { 3807 View p = (View) theParent; 3808 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 3809 } 3810 } else { 3811 if (clipToBounds) { 3812 View p = (View) theParent; 3813 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 3814 } 3815 rect.offset(descendant.mScrollX - descendant.mLeft, 3816 descendant.mScrollY - descendant.mTop); 3817 } 3818 3819 descendant = (View) theParent; 3820 theParent = descendant.mParent; 3821 } 3822 3823 // now that we are up to this view, need to offset one more time 3824 // to get into our coordinate space 3825 if (theParent == this) { 3826 if (offsetFromChildToParent) { 3827 rect.offset(descendant.mLeft - descendant.mScrollX, 3828 descendant.mTop - descendant.mScrollY); 3829 } else { 3830 rect.offset(descendant.mScrollX - descendant.mLeft, 3831 descendant.mScrollY - descendant.mTop); 3832 } 3833 } else { 3834 throw new IllegalArgumentException("parameter must be a descendant of this view"); 3835 } 3836 } 3837 3838 /** 3839 * Offset the vertical location of all children of this view by the specified number of pixels. 3840 * 3841 * @param offset the number of pixels to offset 3842 * 3843 * @hide 3844 */ 3845 public void offsetChildrenTopAndBottom(int offset) { 3846 final int count = mChildrenCount; 3847 final View[] children = mChildren; 3848 3849 for (int i = 0; i < count; i++) { 3850 final View v = children[i]; 3851 v.mTop += offset; 3852 v.mBottom += offset; 3853 } 3854 } 3855 3856 /** 3857 * {@inheritDoc} 3858 */ 3859 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 3860 int dx = child.mLeft - mScrollX; 3861 int dy = child.mTop - mScrollY; 3862 if (offset != null) { 3863 offset.x += dx; 3864 offset.y += dy; 3865 } 3866 r.offset(dx, dy); 3867 return r.intersect(0, 0, mRight - mLeft, mBottom - mTop) && 3868 (mParent == null || mParent.getChildVisibleRect(this, r, offset)); 3869 } 3870 3871 /** 3872 * {@inheritDoc} 3873 */ 3874 @Override 3875 public final void layout(int l, int t, int r, int b) { 3876 if (mTransition == null || !mTransition.isChangingLayout()) { 3877 super.layout(l, t, r, b); 3878 } else { 3879 // record the fact that we noop'd it; request layout when transition finishes 3880 mLayoutSuppressed = true; 3881 } 3882 } 3883 3884 /** 3885 * {@inheritDoc} 3886 */ 3887 @Override 3888 protected abstract void onLayout(boolean changed, 3889 int l, int t, int r, int b); 3890 3891 /** 3892 * Indicates whether the view group has the ability to animate its children 3893 * after the first layout. 3894 * 3895 * @return true if the children can be animated, false otherwise 3896 */ 3897 protected boolean canAnimate() { 3898 return mLayoutAnimationController != null; 3899 } 3900 3901 /** 3902 * Runs the layout animation. Calling this method triggers a relayout of 3903 * this view group. 3904 */ 3905 public void startLayoutAnimation() { 3906 if (mLayoutAnimationController != null) { 3907 mGroupFlags |= FLAG_RUN_ANIMATION; 3908 requestLayout(); 3909 } 3910 } 3911 3912 /** 3913 * Schedules the layout animation to be played after the next layout pass 3914 * of this view group. This can be used to restart the layout animation 3915 * when the content of the view group changes or when the activity is 3916 * paused and resumed. 3917 */ 3918 public void scheduleLayoutAnimation() { 3919 mGroupFlags |= FLAG_RUN_ANIMATION; 3920 } 3921 3922 /** 3923 * Sets the layout animation controller used to animate the group's 3924 * children after the first layout. 3925 * 3926 * @param controller the animation controller 3927 */ 3928 public void setLayoutAnimation(LayoutAnimationController controller) { 3929 mLayoutAnimationController = controller; 3930 if (mLayoutAnimationController != null) { 3931 mGroupFlags |= FLAG_RUN_ANIMATION; 3932 } 3933 } 3934 3935 /** 3936 * Returns the layout animation controller used to animate the group's 3937 * children. 3938 * 3939 * @return the current animation controller 3940 */ 3941 public LayoutAnimationController getLayoutAnimation() { 3942 return mLayoutAnimationController; 3943 } 3944 3945 /** 3946 * Indicates whether the children's drawing cache is used during a layout 3947 * animation. By default, the drawing cache is enabled but this will prevent 3948 * nested layout animations from working. To nest animations, you must disable 3949 * the cache. 3950 * 3951 * @return true if the animation cache is enabled, false otherwise 3952 * 3953 * @see #setAnimationCacheEnabled(boolean) 3954 * @see View#setDrawingCacheEnabled(boolean) 3955 */ 3956 @ViewDebug.ExportedProperty 3957 public boolean isAnimationCacheEnabled() { 3958 return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE; 3959 } 3960 3961 /** 3962 * Enables or disables the children's drawing cache during a layout animation. 3963 * By default, the drawing cache is enabled but this will prevent nested 3964 * layout animations from working. To nest animations, you must disable the 3965 * cache. 3966 * 3967 * @param enabled true to enable the animation cache, false otherwise 3968 * 3969 * @see #isAnimationCacheEnabled() 3970 * @see View#setDrawingCacheEnabled(boolean) 3971 */ 3972 public void setAnimationCacheEnabled(boolean enabled) { 3973 setBooleanFlag(FLAG_ANIMATION_CACHE, enabled); 3974 } 3975 3976 /** 3977 * Indicates whether this ViewGroup will always try to draw its children using their 3978 * drawing cache. By default this property is enabled. 3979 * 3980 * @return true if the animation cache is enabled, false otherwise 3981 * 3982 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 3983 * @see #setChildrenDrawnWithCacheEnabled(boolean) 3984 * @see View#setDrawingCacheEnabled(boolean) 3985 */ 3986 @ViewDebug.ExportedProperty(category = "drawing") 3987 public boolean isAlwaysDrawnWithCacheEnabled() { 3988 return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE; 3989 } 3990 3991 /** 3992 * Indicates whether this ViewGroup will always try to draw its children using their 3993 * drawing cache. This property can be set to true when the cache rendering is 3994 * slightly different from the children's normal rendering. Renderings can be different, 3995 * for instance, when the cache's quality is set to low. 3996 * 3997 * When this property is disabled, the ViewGroup will use the drawing cache of its 3998 * children only when asked to. It's usually the task of subclasses to tell ViewGroup 3999 * when to start using the drawing cache and when to stop using it. 4000 * 4001 * @param always true to always draw with the drawing cache, false otherwise 4002 * 4003 * @see #isAlwaysDrawnWithCacheEnabled() 4004 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4005 * @see View#setDrawingCacheEnabled(boolean) 4006 * @see View#setDrawingCacheQuality(int) 4007 */ 4008 public void setAlwaysDrawnWithCacheEnabled(boolean always) { 4009 setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always); 4010 } 4011 4012 /** 4013 * Indicates whether the ViewGroup is currently drawing its children using 4014 * their drawing cache. 4015 * 4016 * @return true if children should be drawn with their cache, false otherwise 4017 * 4018 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4019 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4020 */ 4021 @ViewDebug.ExportedProperty(category = "drawing") 4022 protected boolean isChildrenDrawnWithCacheEnabled() { 4023 return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE; 4024 } 4025 4026 /** 4027 * Tells the ViewGroup to draw its children using their drawing cache. This property 4028 * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache 4029 * will be used only if it has been enabled. 4030 * 4031 * Subclasses should call this method to start and stop using the drawing cache when 4032 * they perform performance sensitive operations, like scrolling or animating. 4033 * 4034 * @param enabled true if children should be drawn with their cache, false otherwise 4035 * 4036 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4037 * @see #isChildrenDrawnWithCacheEnabled() 4038 */ 4039 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) { 4040 setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled); 4041 } 4042 4043 /** 4044 * Indicates whether the ViewGroup is drawing its children in the order defined by 4045 * {@link #getChildDrawingOrder(int, int)}. 4046 * 4047 * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)}, 4048 * false otherwise 4049 * 4050 * @see #setChildrenDrawingOrderEnabled(boolean) 4051 * @see #getChildDrawingOrder(int, int) 4052 */ 4053 @ViewDebug.ExportedProperty(category = "drawing") 4054 protected boolean isChildrenDrawingOrderEnabled() { 4055 return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER; 4056 } 4057 4058 /** 4059 * Tells the ViewGroup whether to draw its children in the order defined by the method 4060 * {@link #getChildDrawingOrder(int, int)}. 4061 * 4062 * @param enabled true if the order of the children when drawing is determined by 4063 * {@link #getChildDrawingOrder(int, int)}, false otherwise 4064 * 4065 * @see #isChildrenDrawingOrderEnabled() 4066 * @see #getChildDrawingOrder(int, int) 4067 */ 4068 protected void setChildrenDrawingOrderEnabled(boolean enabled) { 4069 setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled); 4070 } 4071 4072 private void setBooleanFlag(int flag, boolean value) { 4073 if (value) { 4074 mGroupFlags |= flag; 4075 } else { 4076 mGroupFlags &= ~flag; 4077 } 4078 } 4079 4080 /** 4081 * Returns an integer indicating what types of drawing caches are kept in memory. 4082 * 4083 * @see #setPersistentDrawingCache(int) 4084 * @see #setAnimationCacheEnabled(boolean) 4085 * 4086 * @return one or a combination of {@link #PERSISTENT_NO_CACHE}, 4087 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4088 * and {@link #PERSISTENT_ALL_CACHES} 4089 */ 4090 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 4091 @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE, to = "NONE"), 4092 @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"), 4093 @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"), 4094 @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES, to = "ALL") 4095 }) 4096 public int getPersistentDrawingCache() { 4097 return mPersistentDrawingCache; 4098 } 4099 4100 /** 4101 * Indicates what types of drawing caches should be kept in memory after 4102 * they have been created. 4103 * 4104 * @see #getPersistentDrawingCache() 4105 * @see #setAnimationCacheEnabled(boolean) 4106 * 4107 * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE}, 4108 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4109 * and {@link #PERSISTENT_ALL_CACHES} 4110 */ 4111 public void setPersistentDrawingCache(int drawingCacheToKeep) { 4112 mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES; 4113 } 4114 4115 /** 4116 * Returns a new set of layout parameters based on the supplied attributes set. 4117 * 4118 * @param attrs the attributes to build the layout parameters from 4119 * 4120 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4121 * of its descendants 4122 */ 4123 public LayoutParams generateLayoutParams(AttributeSet attrs) { 4124 return new LayoutParams(getContext(), attrs); 4125 } 4126 4127 /** 4128 * Returns a safe set of layout parameters based on the supplied layout params. 4129 * When a ViewGroup is passed a View whose layout params do not pass the test of 4130 * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method 4131 * is invoked. This method should return a new set of layout params suitable for 4132 * this ViewGroup, possibly by copying the appropriate attributes from the 4133 * specified set of layout params. 4134 * 4135 * @param p The layout parameters to convert into a suitable set of layout parameters 4136 * for this ViewGroup. 4137 * 4138 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4139 * of its descendants 4140 */ 4141 protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 4142 return p; 4143 } 4144 4145 /** 4146 * Returns a set of default layout parameters. These parameters are requested 4147 * when the View passed to {@link #addView(View)} has no layout parameters 4148 * already set. If null is returned, an exception is thrown from addView. 4149 * 4150 * @return a set of default layout parameters or null 4151 */ 4152 protected LayoutParams generateDefaultLayoutParams() { 4153 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 4154 } 4155 4156 /** 4157 * @hide 4158 */ 4159 @Override 4160 protected boolean dispatchConsistencyCheck(int consistency) { 4161 boolean result = super.dispatchConsistencyCheck(consistency); 4162 4163 final int count = mChildrenCount; 4164 final View[] children = mChildren; 4165 for (int i = 0; i < count; i++) { 4166 if (!children[i].dispatchConsistencyCheck(consistency)) result = false; 4167 } 4168 4169 return result; 4170 } 4171 4172 /** 4173 * @hide 4174 */ 4175 @Override 4176 protected boolean onConsistencyCheck(int consistency) { 4177 boolean result = super.onConsistencyCheck(consistency); 4178 4179 final boolean checkLayout = (consistency & ViewDebug.CONSISTENCY_LAYOUT) != 0; 4180 final boolean checkDrawing = (consistency & ViewDebug.CONSISTENCY_DRAWING) != 0; 4181 4182 if (checkLayout) { 4183 final int count = mChildrenCount; 4184 final View[] children = mChildren; 4185 for (int i = 0; i < count; i++) { 4186 if (children[i].getParent() != this) { 4187 result = false; 4188 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 4189 "View " + children[i] + " has no parent/a parent that is not " + this); 4190 } 4191 } 4192 } 4193 4194 if (checkDrawing) { 4195 // If this group is dirty, check that the parent is dirty as well 4196 if ((mPrivateFlags & DIRTY_MASK) != 0) { 4197 final ViewParent parent = getParent(); 4198 if (parent != null && !(parent instanceof ViewRoot)) { 4199 if ((((View) parent).mPrivateFlags & DIRTY_MASK) == 0) { 4200 result = false; 4201 android.util.Log.d(ViewDebug.CONSISTENCY_LOG_TAG, 4202 "ViewGroup " + this + " is dirty but its parent is not: " + this); 4203 } 4204 } 4205 } 4206 } 4207 4208 return result; 4209 } 4210 4211 /** 4212 * {@inheritDoc} 4213 */ 4214 @Override 4215 protected void debug(int depth) { 4216 super.debug(depth); 4217 String output; 4218 4219 if (mFocused != null) { 4220 output = debugIndent(depth); 4221 output += "mFocused"; 4222 Log.d(VIEW_LOG_TAG, output); 4223 } 4224 if (mChildrenCount != 0) { 4225 output = debugIndent(depth); 4226 output += "{"; 4227 Log.d(VIEW_LOG_TAG, output); 4228 } 4229 int count = mChildrenCount; 4230 for (int i = 0; i < count; i++) { 4231 View child = mChildren[i]; 4232 child.debug(depth + 1); 4233 } 4234 4235 if (mChildrenCount != 0) { 4236 output = debugIndent(depth); 4237 output += "}"; 4238 Log.d(VIEW_LOG_TAG, output); 4239 } 4240 } 4241 4242 /** 4243 * Returns the position in the group of the specified child view. 4244 * 4245 * @param child the view for which to get the position 4246 * @return a positive integer representing the position of the view in the 4247 * group, or -1 if the view does not exist in the group 4248 */ 4249 public int indexOfChild(View child) { 4250 final int count = mChildrenCount; 4251 final View[] children = mChildren; 4252 for (int i = 0; i < count; i++) { 4253 if (children[i] == child) { 4254 return i; 4255 } 4256 } 4257 return -1; 4258 } 4259 4260 /** 4261 * Returns the number of children in the group. 4262 * 4263 * @return a positive integer representing the number of children in 4264 * the group 4265 */ 4266 public int getChildCount() { 4267 return mChildrenCount; 4268 } 4269 4270 /** 4271 * Returns the view at the specified position in the group. 4272 * 4273 * @param index the position at which to get the view from 4274 * @return the view at the specified position or null if the position 4275 * does not exist within the group 4276 */ 4277 public View getChildAt(int index) { 4278 if (index < 0 || index >= mChildrenCount) { 4279 return null; 4280 } 4281 return mChildren[index]; 4282 } 4283 4284 /** 4285 * Ask all of the children of this view to measure themselves, taking into 4286 * account both the MeasureSpec requirements for this view and its padding. 4287 * We skip children that are in the GONE state The heavy lifting is done in 4288 * getChildMeasureSpec. 4289 * 4290 * @param widthMeasureSpec The width requirements for this view 4291 * @param heightMeasureSpec The height requirements for this view 4292 */ 4293 protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) { 4294 final int size = mChildrenCount; 4295 final View[] children = mChildren; 4296 for (int i = 0; i < size; ++i) { 4297 final View child = children[i]; 4298 if ((child.mViewFlags & VISIBILITY_MASK) != GONE) { 4299 measureChild(child, widthMeasureSpec, heightMeasureSpec); 4300 } 4301 } 4302 } 4303 4304 /** 4305 * Ask one of the children of this view to measure itself, taking into 4306 * account both the MeasureSpec requirements for this view and its padding. 4307 * The heavy lifting is done in getChildMeasureSpec. 4308 * 4309 * @param child The child to measure 4310 * @param parentWidthMeasureSpec The width requirements for this view 4311 * @param parentHeightMeasureSpec The height requirements for this view 4312 */ 4313 protected void measureChild(View child, int parentWidthMeasureSpec, 4314 int parentHeightMeasureSpec) { 4315 final LayoutParams lp = child.getLayoutParams(); 4316 4317 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4318 mPaddingLeft + mPaddingRight, lp.width); 4319 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4320 mPaddingTop + mPaddingBottom, lp.height); 4321 4322 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4323 } 4324 4325 /** 4326 * Ask one of the children of this view to measure itself, taking into 4327 * account both the MeasureSpec requirements for this view and its padding 4328 * and margins. The child must have MarginLayoutParams The heavy lifting is 4329 * done in getChildMeasureSpec. 4330 * 4331 * @param child The child to measure 4332 * @param parentWidthMeasureSpec The width requirements for this view 4333 * @param widthUsed Extra space that has been used up by the parent 4334 * horizontally (possibly by other children of the parent) 4335 * @param parentHeightMeasureSpec The height requirements for this view 4336 * @param heightUsed Extra space that has been used up by the parent 4337 * vertically (possibly by other children of the parent) 4338 */ 4339 protected void measureChildWithMargins(View child, 4340 int parentWidthMeasureSpec, int widthUsed, 4341 int parentHeightMeasureSpec, int heightUsed) { 4342 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 4343 4344 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 4345 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 4346 + widthUsed, lp.width); 4347 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 4348 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin 4349 + heightUsed, lp.height); 4350 4351 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 4352 } 4353 4354 /** 4355 * Does the hard part of measureChildren: figuring out the MeasureSpec to 4356 * pass to a particular child. This method figures out the right MeasureSpec 4357 * for one dimension (height or width) of one child view. 4358 * 4359 * The goal is to combine information from our MeasureSpec with the 4360 * LayoutParams of the child to get the best possible results. For example, 4361 * if the this view knows its size (because its MeasureSpec has a mode of 4362 * EXACTLY), and the child has indicated in its LayoutParams that it wants 4363 * to be the same size as the parent, the parent should ask the child to 4364 * layout given an exact size. 4365 * 4366 * @param spec The requirements for this view 4367 * @param padding The padding of this view for the current dimension and 4368 * margins, if applicable 4369 * @param childDimension How big the child wants to be in the current 4370 * dimension 4371 * @return a MeasureSpec integer for the child 4372 */ 4373 public static int getChildMeasureSpec(int spec, int padding, int childDimension) { 4374 int specMode = MeasureSpec.getMode(spec); 4375 int specSize = MeasureSpec.getSize(spec); 4376 4377 int size = Math.max(0, specSize - padding); 4378 4379 int resultSize = 0; 4380 int resultMode = 0; 4381 4382 switch (specMode) { 4383 // Parent has imposed an exact size on us 4384 case MeasureSpec.EXACTLY: 4385 if (childDimension >= 0) { 4386 resultSize = childDimension; 4387 resultMode = MeasureSpec.EXACTLY; 4388 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4389 // Child wants to be our size. So be it. 4390 resultSize = size; 4391 resultMode = MeasureSpec.EXACTLY; 4392 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4393 // Child wants to determine its own size. It can't be 4394 // bigger than us. 4395 resultSize = size; 4396 resultMode = MeasureSpec.AT_MOST; 4397 } 4398 break; 4399 4400 // Parent has imposed a maximum size on us 4401 case MeasureSpec.AT_MOST: 4402 if (childDimension >= 0) { 4403 // Child wants a specific size... so be it 4404 resultSize = childDimension; 4405 resultMode = MeasureSpec.EXACTLY; 4406 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4407 // Child wants to be our size, but our size is not fixed. 4408 // Constrain child to not be bigger than us. 4409 resultSize = size; 4410 resultMode = MeasureSpec.AT_MOST; 4411 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4412 // Child wants to determine its own size. It can't be 4413 // bigger than us. 4414 resultSize = size; 4415 resultMode = MeasureSpec.AT_MOST; 4416 } 4417 break; 4418 4419 // Parent asked to see how big we want to be 4420 case MeasureSpec.UNSPECIFIED: 4421 if (childDimension >= 0) { 4422 // Child wants a specific size... let him have it 4423 resultSize = childDimension; 4424 resultMode = MeasureSpec.EXACTLY; 4425 } else if (childDimension == LayoutParams.MATCH_PARENT) { 4426 // Child wants to be our size... find out how big it should 4427 // be 4428 resultSize = 0; 4429 resultMode = MeasureSpec.UNSPECIFIED; 4430 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 4431 // Child wants to determine its own size.... find out how 4432 // big it should be 4433 resultSize = 0; 4434 resultMode = MeasureSpec.UNSPECIFIED; 4435 } 4436 break; 4437 } 4438 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 4439 } 4440 4441 4442 /** 4443 * Removes any pending animations for views that have been removed. Call 4444 * this if you don't want animations for exiting views to stack up. 4445 */ 4446 public void clearDisappearingChildren() { 4447 if (mDisappearingChildren != null) { 4448 mDisappearingChildren.clear(); 4449 } 4450 } 4451 4452 /** 4453 * Add a view which is removed from mChildren but still needs animation 4454 * 4455 * @param v View to add 4456 */ 4457 private void addDisappearingView(View v) { 4458 ArrayList<View> disappearingChildren = mDisappearingChildren; 4459 4460 if (disappearingChildren == null) { 4461 disappearingChildren = mDisappearingChildren = new ArrayList<View>(); 4462 } 4463 4464 disappearingChildren.add(v); 4465 } 4466 4467 /** 4468 * Cleanup a view when its animation is done. This may mean removing it from 4469 * the list of disappearing views. 4470 * 4471 * @param view The view whose animation has finished 4472 * @param animation The animation, cannot be null 4473 */ 4474 private void finishAnimatingView(final View view, Animation animation) { 4475 final ArrayList<View> disappearingChildren = mDisappearingChildren; 4476 if (disappearingChildren != null) { 4477 if (disappearingChildren.contains(view)) { 4478 disappearingChildren.remove(view); 4479 4480 if (view.mAttachInfo != null) { 4481 view.dispatchDetachedFromWindow(); 4482 } 4483 4484 view.clearAnimation(); 4485 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4486 } 4487 } 4488 4489 if (animation != null && !animation.getFillAfter()) { 4490 view.clearAnimation(); 4491 } 4492 4493 if ((view.mPrivateFlags & ANIMATION_STARTED) == ANIMATION_STARTED) { 4494 view.onAnimationEnd(); 4495 // Should be performed by onAnimationEnd() but this avoid an infinite loop, 4496 // so we'd rather be safe than sorry 4497 view.mPrivateFlags &= ~ANIMATION_STARTED; 4498 // Draw one more frame after the animation is done 4499 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4500 } 4501 } 4502 4503 /** 4504 * This method tells the ViewGroup that the given View object, which should have this 4505 * ViewGroup as its parent, 4506 * should be kept around (re-displayed when the ViewGroup draws its children) even if it 4507 * is removed from its parent. This allows animations, such as those used by 4508 * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate 4509 * the removal of views. A call to this method should always be accompanied by a later call 4510 * to {@link #endViewTransition(View)}, such as after an animation on the View has finished, 4511 * so that the View finally gets removed. 4512 * 4513 * @param view The View object to be kept visible even if it gets removed from its parent. 4514 */ 4515 public void startViewTransition(View view) { 4516 if (view.mParent == this) { 4517 if (mTransitioningViews == null) { 4518 mTransitioningViews = new ArrayList<View>(); 4519 } 4520 mTransitioningViews.add(view); 4521 } 4522 } 4523 4524 /** 4525 * This method should always be called following an earlier call to 4526 * {@link #startViewTransition(View)}. The given View is finally removed from its parent 4527 * and will no longer be displayed. Note that this method does not perform the functionality 4528 * of removing a view from its parent; it just discontinues the display of a View that 4529 * has previously been removed. 4530 * 4531 * @return view The View object that has been removed but is being kept around in the visible 4532 * hierarchy by an earlier call to {@link #startViewTransition(View)}. 4533 */ 4534 public void endViewTransition(View view) { 4535 if (mTransitioningViews != null) { 4536 mTransitioningViews.remove(view); 4537 final ArrayList<View> disappearingChildren = mDisappearingChildren; 4538 if (disappearingChildren != null && disappearingChildren.contains(view)) { 4539 disappearingChildren.remove(view); 4540 if (mVisibilityChangingChildren != null && 4541 mVisibilityChangingChildren.contains(view)) { 4542 mVisibilityChangingChildren.remove(view); 4543 } else { 4544 if (view.mAttachInfo != null) { 4545 view.dispatchDetachedFromWindow(); 4546 } 4547 if (view.mParent != null) { 4548 view.mParent = null; 4549 } 4550 } 4551 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 4552 } 4553 } 4554 } 4555 4556 private LayoutTransition.TransitionListener mLayoutTransitionListener = 4557 new LayoutTransition.TransitionListener() { 4558 @Override 4559 public void startTransition(LayoutTransition transition, ViewGroup container, 4560 View view, int transitionType) { 4561 // We only care about disappearing items, since we need special logic to keep 4562 // those items visible after they've been 'removed' 4563 if (transitionType == LayoutTransition.DISAPPEARING) { 4564 startViewTransition(view); 4565 } 4566 } 4567 4568 @Override 4569 public void endTransition(LayoutTransition transition, ViewGroup container, 4570 View view, int transitionType) { 4571 if (mLayoutSuppressed && !transition.isChangingLayout()) { 4572 requestLayout(); 4573 mLayoutSuppressed = false; 4574 } 4575 if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) { 4576 endViewTransition(view); 4577 } 4578 } 4579 }; 4580 4581 /** 4582 * {@inheritDoc} 4583 */ 4584 @Override 4585 public boolean gatherTransparentRegion(Region region) { 4586 // If no transparent regions requested, we are always opaque. 4587 final boolean meOpaque = (mPrivateFlags & View.REQUEST_TRANSPARENT_REGIONS) == 0; 4588 if (meOpaque && region == null) { 4589 // The caller doesn't care about the region, so stop now. 4590 return true; 4591 } 4592 super.gatherTransparentRegion(region); 4593 final View[] children = mChildren; 4594 final int count = mChildrenCount; 4595 boolean noneOfTheChildrenAreTransparent = true; 4596 for (int i = 0; i < count; i++) { 4597 final View child = children[i]; 4598 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 4599 if (!child.gatherTransparentRegion(region)) { 4600 noneOfTheChildrenAreTransparent = false; 4601 } 4602 } 4603 } 4604 return meOpaque || noneOfTheChildrenAreTransparent; 4605 } 4606 4607 /** 4608 * {@inheritDoc} 4609 */ 4610 public void requestTransparentRegion(View child) { 4611 if (child != null) { 4612 child.mPrivateFlags |= View.REQUEST_TRANSPARENT_REGIONS; 4613 if (mParent != null) { 4614 mParent.requestTransparentRegion(this); 4615 } 4616 } 4617 } 4618 4619 4620 @Override 4621 protected boolean fitSystemWindows(Rect insets) { 4622 boolean done = super.fitSystemWindows(insets); 4623 if (!done) { 4624 final int count = mChildrenCount; 4625 final View[] children = mChildren; 4626 for (int i = 0; i < count; i++) { 4627 done = children[i].fitSystemWindows(insets); 4628 if (done) { 4629 break; 4630 } 4631 } 4632 } 4633 return done; 4634 } 4635 4636 /** 4637 * Returns the animation listener to which layout animation events are 4638 * sent. 4639 * 4640 * @return an {@link android.view.animation.Animation.AnimationListener} 4641 */ 4642 public Animation.AnimationListener getLayoutAnimationListener() { 4643 return mAnimationListener; 4644 } 4645 4646 @Override 4647 protected void drawableStateChanged() { 4648 super.drawableStateChanged(); 4649 4650 if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) { 4651 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 4652 throw new IllegalStateException("addStateFromChildren cannot be enabled if a" 4653 + " child has duplicateParentState set to true"); 4654 } 4655 4656 final View[] children = mChildren; 4657 final int count = mChildrenCount; 4658 4659 for (int i = 0; i < count; i++) { 4660 final View child = children[i]; 4661 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) { 4662 child.refreshDrawableState(); 4663 } 4664 } 4665 } 4666 } 4667 4668 @Override 4669 public void jumpDrawablesToCurrentState() { 4670 super.jumpDrawablesToCurrentState(); 4671 final View[] children = mChildren; 4672 final int count = mChildrenCount; 4673 for (int i = 0; i < count; i++) { 4674 children[i].jumpDrawablesToCurrentState(); 4675 } 4676 } 4677 4678 @Override 4679 protected int[] onCreateDrawableState(int extraSpace) { 4680 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) { 4681 return super.onCreateDrawableState(extraSpace); 4682 } 4683 4684 int need = 0; 4685 int n = getChildCount(); 4686 for (int i = 0; i < n; i++) { 4687 int[] childState = getChildAt(i).getDrawableState(); 4688 4689 if (childState != null) { 4690 need += childState.length; 4691 } 4692 } 4693 4694 int[] state = super.onCreateDrawableState(extraSpace + need); 4695 4696 for (int i = 0; i < n; i++) { 4697 int[] childState = getChildAt(i).getDrawableState(); 4698 4699 if (childState != null) { 4700 state = mergeDrawableStates(state, childState); 4701 } 4702 } 4703 4704 return state; 4705 } 4706 4707 /** 4708 * Sets whether this ViewGroup's drawable states also include 4709 * its children's drawable states. This is used, for example, to 4710 * make a group appear to be focused when its child EditText or button 4711 * is focused. 4712 */ 4713 public void setAddStatesFromChildren(boolean addsStates) { 4714 if (addsStates) { 4715 mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN; 4716 } else { 4717 mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN; 4718 } 4719 4720 refreshDrawableState(); 4721 } 4722 4723 /** 4724 * Returns whether this ViewGroup's drawable states also include 4725 * its children's drawable states. This is used, for example, to 4726 * make a group appear to be focused when its child EditText or button 4727 * is focused. 4728 */ 4729 public boolean addStatesFromChildren() { 4730 return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0; 4731 } 4732 4733 /** 4734 * If {link #addStatesFromChildren} is true, refreshes this group's 4735 * drawable state (to include the states from its children). 4736 */ 4737 public void childDrawableStateChanged(View child) { 4738 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 4739 refreshDrawableState(); 4740 } 4741 } 4742 4743 /** 4744 * Specifies the animation listener to which layout animation events must 4745 * be sent. Only 4746 * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)} 4747 * and 4748 * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)} 4749 * are invoked. 4750 * 4751 * @param animationListener the layout animation listener 4752 */ 4753 public void setLayoutAnimationListener(Animation.AnimationListener animationListener) { 4754 mAnimationListener = animationListener; 4755 } 4756 4757 /** 4758 * LayoutParams are used by views to tell their parents how they want to be 4759 * laid out. See 4760 * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes} 4761 * for a list of all child view attributes that this class supports. 4762 * 4763 * <p> 4764 * The base LayoutParams class just describes how big the view wants to be 4765 * for both width and height. For each dimension, it can specify one of: 4766 * <ul> 4767 * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which 4768 * means that the view wants to be as big as its parent (minus padding) 4769 * <li> WRAP_CONTENT, which means that the view wants to be just big enough 4770 * to enclose its content (plus padding) 4771 * <li> an exact number 4772 * </ul> 4773 * There are subclasses of LayoutParams for different subclasses of 4774 * ViewGroup. For example, AbsoluteLayout has its own subclass of 4775 * LayoutParams which adds an X and Y value. 4776 * 4777 * @attr ref android.R.styleable#ViewGroup_Layout_layout_height 4778 * @attr ref android.R.styleable#ViewGroup_Layout_layout_width 4779 */ 4780 public static class LayoutParams { 4781 /** 4782 * Special value for the height or width requested by a View. 4783 * FILL_PARENT means that the view wants to be as big as its parent, 4784 * minus the parent's padding, if any. This value is deprecated 4785 * starting in API Level 8 and replaced by {@link #MATCH_PARENT}. 4786 */ 4787 @SuppressWarnings({"UnusedDeclaration"}) 4788 @Deprecated 4789 public static final int FILL_PARENT = -1; 4790 4791 /** 4792 * Special value for the height or width requested by a View. 4793 * MATCH_PARENT means that the view wants to be as big as its parent, 4794 * minus the parent's padding, if any. Introduced in API Level 8. 4795 */ 4796 public static final int MATCH_PARENT = -1; 4797 4798 /** 4799 * Special value for the height or width requested by a View. 4800 * WRAP_CONTENT means that the view wants to be just large enough to fit 4801 * its own internal content, taking its own padding into account. 4802 */ 4803 public static final int WRAP_CONTENT = -2; 4804 4805 /** 4806 * Information about how wide the view wants to be. Can be one of the 4807 * constants FILL_PARENT (replaced by MATCH_PARENT , 4808 * in API Level 8) or WRAP_CONTENT. or an exact size. 4809 */ 4810 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4811 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 4812 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 4813 }) 4814 public int width; 4815 4816 /** 4817 * Information about how tall the view wants to be. Can be one of the 4818 * constants FILL_PARENT (replaced by MATCH_PARENT , 4819 * in API Level 8) or WRAP_CONTENT. or an exact size. 4820 */ 4821 @ViewDebug.ExportedProperty(category = "layout", mapping = { 4822 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 4823 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 4824 }) 4825 public int height; 4826 4827 /** 4828 * Used to animate layouts. 4829 */ 4830 public LayoutAnimationController.AnimationParameters layoutAnimationParameters; 4831 4832 /** 4833 * Creates a new set of layout parameters. The values are extracted from 4834 * the supplied attributes set and context. The XML attributes mapped 4835 * to this set of layout parameters are: 4836 * 4837 * <ul> 4838 * <li><code>layout_width</code>: the width, either an exact value, 4839 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 4840 * {@link #MATCH_PARENT} in API Level 8)</li> 4841 * <li><code>layout_height</code>: the height, either an exact value, 4842 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 4843 * {@link #MATCH_PARENT} in API Level 8)</li> 4844 * </ul> 4845 * 4846 * @param c the application environment 4847 * @param attrs the set of attributes from which to extract the layout 4848 * parameters' values 4849 */ 4850 public LayoutParams(Context c, AttributeSet attrs) { 4851 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout); 4852 setBaseAttributes(a, 4853 R.styleable.ViewGroup_Layout_layout_width, 4854 R.styleable.ViewGroup_Layout_layout_height); 4855 a.recycle(); 4856 } 4857 4858 /** 4859 * Creates a new set of layout parameters with the specified width 4860 * and height. 4861 * 4862 * @param width the width, either {@link #WRAP_CONTENT}, 4863 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 4864 * API Level 8), or a fixed size in pixels 4865 * @param height the height, either {@link #WRAP_CONTENT}, 4866 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 4867 * API Level 8), or a fixed size in pixels 4868 */ 4869 public LayoutParams(int width, int height) { 4870 this.width = width; 4871 this.height = height; 4872 } 4873 4874 /** 4875 * Copy constructor. Clones the width and height values of the source. 4876 * 4877 * @param source The layout params to copy from. 4878 */ 4879 public LayoutParams(LayoutParams source) { 4880 this.width = source.width; 4881 this.height = source.height; 4882 } 4883 4884 /** 4885 * Used internally by MarginLayoutParams. 4886 * @hide 4887 */ 4888 LayoutParams() { 4889 } 4890 4891 /** 4892 * Extracts the layout parameters from the supplied attributes. 4893 * 4894 * @param a the style attributes to extract the parameters from 4895 * @param widthAttr the identifier of the width attribute 4896 * @param heightAttr the identifier of the height attribute 4897 */ 4898 protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { 4899 width = a.getLayoutDimension(widthAttr, "layout_width"); 4900 height = a.getLayoutDimension(heightAttr, "layout_height"); 4901 } 4902 4903 /** 4904 * Returns a String representation of this set of layout parameters. 4905 * 4906 * @param output the String to prepend to the internal representation 4907 * @return a String with the following format: output + 4908 * "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }" 4909 * 4910 * @hide 4911 */ 4912 public String debug(String output) { 4913 return output + "ViewGroup.LayoutParams={ width=" 4914 + sizeToString(width) + ", height=" + sizeToString(height) + " }"; 4915 } 4916 4917 /** 4918 * Converts the specified size to a readable String. 4919 * 4920 * @param size the size to convert 4921 * @return a String instance representing the supplied size 4922 * 4923 * @hide 4924 */ 4925 protected static String sizeToString(int size) { 4926 if (size == WRAP_CONTENT) { 4927 return "wrap-content"; 4928 } 4929 if (size == MATCH_PARENT) { 4930 return "match-parent"; 4931 } 4932 return String.valueOf(size); 4933 } 4934 } 4935 4936 /** 4937 * Per-child layout information for layouts that support margins. 4938 * See 4939 * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes} 4940 * for a list of all child view attributes that this class supports. 4941 */ 4942 public static class MarginLayoutParams extends ViewGroup.LayoutParams { 4943 /** 4944 * The left margin in pixels of the child. 4945 */ 4946 @ViewDebug.ExportedProperty(category = "layout") 4947 public int leftMargin; 4948 4949 /** 4950 * The top margin in pixels of the child. 4951 */ 4952 @ViewDebug.ExportedProperty(category = "layout") 4953 public int topMargin; 4954 4955 /** 4956 * The right margin in pixels of the child. 4957 */ 4958 @ViewDebug.ExportedProperty(category = "layout") 4959 public int rightMargin; 4960 4961 /** 4962 * The bottom margin in pixels of the child. 4963 */ 4964 @ViewDebug.ExportedProperty(category = "layout") 4965 public int bottomMargin; 4966 4967 /** 4968 * Creates a new set of layout parameters. The values are extracted from 4969 * the supplied attributes set and context. 4970 * 4971 * @param c the application environment 4972 * @param attrs the set of attributes from which to extract the layout 4973 * parameters' values 4974 */ 4975 public MarginLayoutParams(Context c, AttributeSet attrs) { 4976 super(); 4977 4978 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout); 4979 setBaseAttributes(a, 4980 R.styleable.ViewGroup_MarginLayout_layout_width, 4981 R.styleable.ViewGroup_MarginLayout_layout_height); 4982 4983 int margin = a.getDimensionPixelSize( 4984 com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1); 4985 if (margin >= 0) { 4986 leftMargin = margin; 4987 topMargin = margin; 4988 rightMargin= margin; 4989 bottomMargin = margin; 4990 } else { 4991 leftMargin = a.getDimensionPixelSize( 4992 R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0); 4993 topMargin = a.getDimensionPixelSize( 4994 R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0); 4995 rightMargin = a.getDimensionPixelSize( 4996 R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0); 4997 bottomMargin = a.getDimensionPixelSize( 4998 R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0); 4999 } 5000 5001 a.recycle(); 5002 } 5003 5004 /** 5005 * {@inheritDoc} 5006 */ 5007 public MarginLayoutParams(int width, int height) { 5008 super(width, height); 5009 } 5010 5011 /** 5012 * Copy constructor. Clones the width, height and margin values of the source. 5013 * 5014 * @param source The layout params to copy from. 5015 */ 5016 public MarginLayoutParams(MarginLayoutParams source) { 5017 this.width = source.width; 5018 this.height = source.height; 5019 5020 this.leftMargin = source.leftMargin; 5021 this.topMargin = source.topMargin; 5022 this.rightMargin = source.rightMargin; 5023 this.bottomMargin = source.bottomMargin; 5024 } 5025 5026 /** 5027 * {@inheritDoc} 5028 */ 5029 public MarginLayoutParams(LayoutParams source) { 5030 super(source); 5031 } 5032 5033 /** 5034 * Sets the margins, in pixels. 5035 * 5036 * @param left the left margin size 5037 * @param top the top margin size 5038 * @param right the right margin size 5039 * @param bottom the bottom margin size 5040 * 5041 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft 5042 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 5043 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight 5044 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 5045 */ 5046 public void setMargins(int left, int top, int right, int bottom) { 5047 leftMargin = left; 5048 topMargin = top; 5049 rightMargin = right; 5050 bottomMargin = bottom; 5051 } 5052 } 5053 5054 /* Describes a touched view and the ids of the pointers that it has captured. 5055 * 5056 * This code assumes that pointer ids are always in the range 0..31 such that 5057 * it can use a bitfield to track which pointer ids are present. 5058 * As it happens, the lower layers of the input dispatch pipeline also use the 5059 * same trick so the assumption should be safe here... 5060 */ 5061 private static final class TouchTarget { 5062 private static final int MAX_RECYCLED = 32; 5063 private static final Object sRecycleLock = new Object(); 5064 private static TouchTarget sRecycleBin; 5065 private static int sRecycledCount; 5066 5067 public static final int ALL_POINTER_IDS = -1; // all ones 5068 5069 // The touched child view. 5070 public View child; 5071 5072 // The combined bit mask of pointer ids for all pointers captured by the target. 5073 public int pointerIdBits; 5074 5075 // The next target in the target list. 5076 public TouchTarget next; 5077 5078 private TouchTarget() { 5079 } 5080 5081 public static TouchTarget obtain(View child, int pointerIdBits) { 5082 final TouchTarget target; 5083 synchronized (sRecycleLock) { 5084 if (sRecycleBin == null) { 5085 target = new TouchTarget(); 5086 } else { 5087 target = sRecycleBin; 5088 sRecycleBin = target.next; 5089 sRecycledCount--; 5090 target.next = null; 5091 } 5092 } 5093 target.child = child; 5094 target.pointerIdBits = pointerIdBits; 5095 return target; 5096 } 5097 5098 public void recycle() { 5099 synchronized (sRecycleLock) { 5100 if (sRecycledCount < MAX_RECYCLED) { 5101 next = sRecycleBin; 5102 sRecycleBin = this; 5103 sRecycledCount += 1; 5104 } else { 5105 next = null; 5106 } 5107 child = null; 5108 } 5109 } 5110 } 5111} 5112