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