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