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