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