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