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