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