ViewGroup.java revision 222688682e6e072076489d8203d01bdf2366101a
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; 49import java.util.Locale; 50 51/** 52 * <p> 53 * A <code>ViewGroup</code> is a special view that can contain other views 54 * (called children.) The view group is the base class for layouts and views 55 * containers. This class also defines the 56 * {@link android.view.ViewGroup.LayoutParams} class which serves as the base 57 * class for layouts parameters. 58 * </p> 59 * 60 * <p> 61 * Also see {@link LayoutParams} for layout attributes. 62 * </p> 63 * 64 * @attr ref android.R.styleable#ViewGroup_clipChildren 65 * @attr ref android.R.styleable#ViewGroup_clipToPadding 66 * @attr ref android.R.styleable#ViewGroup_layoutAnimation 67 * @attr ref android.R.styleable#ViewGroup_animationCache 68 * @attr ref android.R.styleable#ViewGroup_persistentDrawingCache 69 * @attr ref android.R.styleable#ViewGroup_alwaysDrawnWithCache 70 * @attr ref android.R.styleable#ViewGroup_addStatesFromChildren 71 * @attr ref android.R.styleable#ViewGroup_descendantFocusability 72 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges 73 */ 74public abstract class ViewGroup extends View implements ViewParent, ViewManager { 75 76 private static final boolean DBG = false; 77 78 /** 79 * Views which have been hidden or removed which need to be animated on 80 * their way out. 81 * This field should be made private, so it is hidden from the SDK. 82 * {@hide} 83 */ 84 protected ArrayList<View> mDisappearingChildren; 85 86 /** 87 * Listener used to propagate events indicating when children are added 88 * and/or removed from a view group. 89 * This field should be made private, so it is hidden from the SDK. 90 * {@hide} 91 */ 92 protected OnHierarchyChangeListener mOnHierarchyChangeListener; 93 94 // The view contained within this ViewGroup that has or contains focus. 95 private View mFocused; 96 97 /** 98 * A Transformation used when drawing children, to 99 * apply on the child being drawn. 100 */ 101 private final Transformation mChildTransformation = new Transformation(); 102 103 /** 104 * Used to track the current invalidation region. 105 */ 106 private RectF mInvalidateRegion; 107 108 /** 109 * A Transformation used to calculate a correct 110 * invalidation area when the application is autoscaled. 111 */ 112 private Transformation mInvalidationTransformation; 113 114 // View currently under an ongoing drag 115 private View mCurrentDragView; 116 117 // Metadata about the ongoing drag 118 private DragEvent mCurrentDrag; 119 private HashSet<View> mDragNotifiedChildren; 120 121 // Does this group have a child that can accept the current drag payload? 122 private boolean mChildAcceptsDrag; 123 124 // Used during drag dispatch 125 private final PointF mLocalPoint = new PointF(); 126 127 // Layout animation 128 private LayoutAnimationController mLayoutAnimationController; 129 private Animation.AnimationListener mAnimationListener; 130 131 // First touch target in the linked list of touch targets. 132 private TouchTarget mFirstTouchTarget; 133 134 // For debugging only. You can see these in hierarchyviewer. 135 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 136 @ViewDebug.ExportedProperty(category = "events") 137 private long mLastTouchDownTime; 138 @ViewDebug.ExportedProperty(category = "events") 139 private int mLastTouchDownIndex = -1; 140 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 141 @ViewDebug.ExportedProperty(category = "events") 142 private float mLastTouchDownX; 143 @SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) 144 @ViewDebug.ExportedProperty(category = "events") 145 private float mLastTouchDownY; 146 147 // First hover target in the linked list of hover targets. 148 // The hover targets are children which have received ACTION_HOVER_ENTER. 149 // They might not have actually handled the hover event, but we will 150 // continue sending hover events to them as long as the pointer remains over 151 // their bounds and the view group does not intercept hover. 152 private HoverTarget mFirstHoverTarget; 153 154 // True if the view group itself received a hover event. 155 // It might not have actually handled the hover event. 156 private boolean mHoveredSelf; 157 158 /** 159 * Internal flags. 160 * 161 * This field should be made private, so it is hidden from the SDK. 162 * {@hide} 163 */ 164 protected int mGroupFlags; 165 166 // When set, ViewGroup invalidates only the child's rectangle 167 // Set by default 168 private static final int FLAG_CLIP_CHILDREN = 0x1; 169 170 // When set, ViewGroup excludes the padding area from the invalidate rectangle 171 // Set by default 172 private static final int FLAG_CLIP_TO_PADDING = 0x2; 173 174 // When set, dispatchDraw() will invoke invalidate(); this is set by drawChild() when 175 // a child needs to be invalidated and FLAG_OPTIMIZE_INVALIDATE is set 176 private static final int FLAG_INVALIDATE_REQUIRED = 0x4; 177 178 // When set, dispatchDraw() will run the layout animation and unset the flag 179 private static final int FLAG_RUN_ANIMATION = 0x8; 180 181 // When set, there is either no layout animation on the ViewGroup or the layout 182 // animation is over 183 // Set by default 184 private static final int FLAG_ANIMATION_DONE = 0x10; 185 186 // If set, this ViewGroup has padding; if unset there is no padding and we don't need 187 // to clip it, even if FLAG_CLIP_TO_PADDING is set 188 private static final int FLAG_PADDING_NOT_NULL = 0x20; 189 190 // When set, this ViewGroup caches its children in a Bitmap before starting a layout animation 191 // Set by default 192 private static final int FLAG_ANIMATION_CACHE = 0x40; 193 194 // When set, this ViewGroup converts calls to invalidate(Rect) to invalidate() during a 195 // layout animation; this avoid clobbering the hierarchy 196 // Automatically set when the layout animation starts, depending on the animation's 197 // characteristics 198 private static final int FLAG_OPTIMIZE_INVALIDATE = 0x80; 199 200 // When set, the next call to drawChild() will clear mChildTransformation's matrix 201 private static final int FLAG_CLEAR_TRANSFORMATION = 0x100; 202 203 // When set, this ViewGroup invokes mAnimationListener.onAnimationEnd() and removes 204 // the children's Bitmap caches if necessary 205 // This flag is set when the layout animation is over (after FLAG_ANIMATION_DONE is set) 206 private static final int FLAG_NOTIFY_ANIMATION_LISTENER = 0x200; 207 208 /** 209 * When set, the drawing method will call {@link #getChildDrawingOrder(int, int)} 210 * to get the index of the child to draw for that iteration. 211 * 212 * @hide 213 */ 214 protected static final int FLAG_USE_CHILD_DRAWING_ORDER = 0x400; 215 216 /** 217 * When set, this ViewGroup supports static transformations on children; this causes 218 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} to be 219 * invoked when a child is drawn. 220 * 221 * Any subclass overriding 222 * {@link #getChildStaticTransformation(View, android.view.animation.Transformation)} should 223 * set this flags in {@link #mGroupFlags}. 224 * 225 * {@hide} 226 */ 227 protected static final int FLAG_SUPPORT_STATIC_TRANSFORMATIONS = 0x800; 228 229 // When the previous drawChild() invocation used an alpha value that was lower than 230 // 1.0 and set it in mCachePaint 231 private static final int FLAG_ALPHA_LOWER_THAN_ONE = 0x1000; 232 233 /** 234 * When set, this ViewGroup's drawable states also include those 235 * of its children. 236 */ 237 private static final int FLAG_ADD_STATES_FROM_CHILDREN = 0x2000; 238 239 /** 240 * When set, this ViewGroup tries to always draw its children using their drawing cache. 241 */ 242 private static final int FLAG_ALWAYS_DRAWN_WITH_CACHE = 0x4000; 243 244 /** 245 * When set, and if FLAG_ALWAYS_DRAWN_WITH_CACHE is not set, this ViewGroup will try to 246 * draw its children with their drawing cache. 247 */ 248 private static final int FLAG_CHILDREN_DRAWN_WITH_CACHE = 0x8000; 249 250 /** 251 * When set, this group will go through its list of children to notify them of 252 * any drawable state change. 253 */ 254 private static final int FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE = 0x10000; 255 256 private static final int FLAG_MASK_FOCUSABILITY = 0x60000; 257 258 /** 259 * This view will get focus before any of its descendants. 260 */ 261 public static final int FOCUS_BEFORE_DESCENDANTS = 0x20000; 262 263 /** 264 * This view will get focus only if none of its descendants want it. 265 */ 266 public static final int FOCUS_AFTER_DESCENDANTS = 0x40000; 267 268 /** 269 * This view will block any of its descendants from getting focus, even 270 * if they are focusable. 271 */ 272 public static final int FOCUS_BLOCK_DESCENDANTS = 0x60000; 273 274 /** 275 * Used to map between enum in attrubutes and flag values. 276 */ 277 private static final int[] DESCENDANT_FOCUSABILITY_FLAGS = 278 {FOCUS_BEFORE_DESCENDANTS, FOCUS_AFTER_DESCENDANTS, 279 FOCUS_BLOCK_DESCENDANTS}; 280 281 /** 282 * When set, this ViewGroup should not intercept touch events. 283 * {@hide} 284 */ 285 protected static final int FLAG_DISALLOW_INTERCEPT = 0x80000; 286 287 /** 288 * When set, this ViewGroup will split MotionEvents to multiple child Views when appropriate. 289 */ 290 private static final int FLAG_SPLIT_MOTION_EVENTS = 0x200000; 291 292 /** 293 * Indicates which types of drawing caches are to be kept in memory. 294 * This field should be made private, so it is hidden from the SDK. 295 * {@hide} 296 */ 297 protected int mPersistentDrawingCache; 298 299 /** 300 * Used to indicate that no drawing cache should be kept in memory. 301 */ 302 public static final int PERSISTENT_NO_CACHE = 0x0; 303 304 /** 305 * Used to indicate that the animation drawing cache should be kept in memory. 306 */ 307 public static final int PERSISTENT_ANIMATION_CACHE = 0x1; 308 309 /** 310 * Used to indicate that the scrolling drawing cache should be kept in memory. 311 */ 312 public static final int PERSISTENT_SCROLLING_CACHE = 0x2; 313 314 /** 315 * Used to indicate that all drawing caches should be kept in memory. 316 */ 317 public static final int PERSISTENT_ALL_CACHES = 0x3; 318 319 /** 320 * We clip to padding when FLAG_CLIP_TO_PADDING and FLAG_PADDING_NOT_NULL 321 * are set at the same time. 322 */ 323 protected static final int CLIP_TO_PADDING_MASK = FLAG_CLIP_TO_PADDING | FLAG_PADDING_NOT_NULL; 324 325 // Index of the child's left position in the mLocation array 326 private static final int CHILD_LEFT_INDEX = 0; 327 // Index of the child's top position in the mLocation array 328 private static final int CHILD_TOP_INDEX = 1; 329 330 // Child views of this ViewGroup 331 private View[] mChildren; 332 // Number of valid children in the mChildren array, the rest should be null or not 333 // considered as children 334 335 private boolean mLayoutSuppressed = false; 336 337 private int mChildrenCount; 338 339 private static final int ARRAY_INITIAL_CAPACITY = 12; 340 private static final int ARRAY_CAPACITY_INCREMENT = 12; 341 342 // Used to draw cached views 343 private final Paint mCachePaint = new Paint(); 344 345 // Used to animate add/remove changes in layout 346 private LayoutTransition mTransition; 347 348 // The set of views that are currently being transitioned. This list is used to track views 349 // being removed that should not actually be removed from the parent yet because they are 350 // being animated. 351 private ArrayList<View> mTransitioningViews; 352 353 // List of children changing visibility. This is used to potentially keep rendering 354 // views during a transition when they otherwise would have become gone/invisible 355 private ArrayList<View> mVisibilityChangingChildren; 356 357 // Indicates whether this container will use its children layers to draw 358 @ViewDebug.ExportedProperty(category = "drawing") 359 private boolean mDrawLayers = true; 360 361 public ViewGroup(Context context) { 362 super(context); 363 initViewGroup(); 364 } 365 366 public ViewGroup(Context context, AttributeSet attrs) { 367 super(context, attrs); 368 initViewGroup(); 369 initFromAttributes(context, attrs); 370 } 371 372 public ViewGroup(Context context, AttributeSet attrs, int defStyle) { 373 super(context, attrs, defStyle); 374 initViewGroup(); 375 initFromAttributes(context, attrs); 376 } 377 378 private void initViewGroup() { 379 // ViewGroup doesn't draw by default 380 setFlags(WILL_NOT_DRAW, DRAW_MASK); 381 mGroupFlags |= FLAG_CLIP_CHILDREN; 382 mGroupFlags |= FLAG_CLIP_TO_PADDING; 383 mGroupFlags |= FLAG_ANIMATION_DONE; 384 mGroupFlags |= FLAG_ANIMATION_CACHE; 385 mGroupFlags |= FLAG_ALWAYS_DRAWN_WITH_CACHE; 386 387 if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB) { 388 mGroupFlags |= FLAG_SPLIT_MOTION_EVENTS; 389 } 390 391 setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS); 392 393 mChildren = new View[ARRAY_INITIAL_CAPACITY]; 394 mChildrenCount = 0; 395 396 mCachePaint.setDither(false); 397 398 mPersistentDrawingCache = PERSISTENT_SCROLLING_CACHE; 399 } 400 401 private void initFromAttributes(Context context, AttributeSet attrs) { 402 TypedArray a = context.obtainStyledAttributes(attrs, 403 R.styleable.ViewGroup); 404 405 final int N = a.getIndexCount(); 406 for (int i = 0; i < N; i++) { 407 int attr = a.getIndex(i); 408 switch (attr) { 409 case R.styleable.ViewGroup_clipChildren: 410 setClipChildren(a.getBoolean(attr, true)); 411 break; 412 case R.styleable.ViewGroup_clipToPadding: 413 setClipToPadding(a.getBoolean(attr, true)); 414 break; 415 case R.styleable.ViewGroup_animationCache: 416 setAnimationCacheEnabled(a.getBoolean(attr, true)); 417 break; 418 case R.styleable.ViewGroup_persistentDrawingCache: 419 setPersistentDrawingCache(a.getInt(attr, PERSISTENT_SCROLLING_CACHE)); 420 break; 421 case R.styleable.ViewGroup_addStatesFromChildren: 422 setAddStatesFromChildren(a.getBoolean(attr, false)); 423 break; 424 case R.styleable.ViewGroup_alwaysDrawnWithCache: 425 setAlwaysDrawnWithCacheEnabled(a.getBoolean(attr, true)); 426 break; 427 case R.styleable.ViewGroup_layoutAnimation: 428 int id = a.getResourceId(attr, -1); 429 if (id > 0) { 430 setLayoutAnimation(AnimationUtils.loadLayoutAnimation(mContext, id)); 431 } 432 break; 433 case R.styleable.ViewGroup_descendantFocusability: 434 setDescendantFocusability(DESCENDANT_FOCUSABILITY_FLAGS[a.getInt(attr, 0)]); 435 break; 436 case R.styleable.ViewGroup_splitMotionEvents: 437 setMotionEventSplittingEnabled(a.getBoolean(attr, false)); 438 break; 439 case R.styleable.ViewGroup_animateLayoutChanges: 440 boolean animateLayoutChanges = a.getBoolean(attr, false); 441 if (animateLayoutChanges) { 442 setLayoutTransition(new LayoutTransition()); 443 } 444 break; 445 } 446 } 447 448 a.recycle(); 449 } 450 451 /** 452 * Gets the descendant focusability of this view group. The descendant 453 * focusability defines the relationship between this view group and its 454 * descendants when looking for a view to take focus in 455 * {@link #requestFocus(int, android.graphics.Rect)}. 456 * 457 * @return one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS}, 458 * {@link #FOCUS_BLOCK_DESCENDANTS}. 459 */ 460 @ViewDebug.ExportedProperty(category = "focus", mapping = { 461 @ViewDebug.IntToString(from = FOCUS_BEFORE_DESCENDANTS, to = "FOCUS_BEFORE_DESCENDANTS"), 462 @ViewDebug.IntToString(from = FOCUS_AFTER_DESCENDANTS, to = "FOCUS_AFTER_DESCENDANTS"), 463 @ViewDebug.IntToString(from = FOCUS_BLOCK_DESCENDANTS, to = "FOCUS_BLOCK_DESCENDANTS") 464 }) 465 public int getDescendantFocusability() { 466 return mGroupFlags & FLAG_MASK_FOCUSABILITY; 467 } 468 469 /** 470 * Set the descendant focusability of this view group. This defines the relationship 471 * between this view group and its descendants when looking for a view to 472 * take focus in {@link #requestFocus(int, android.graphics.Rect)}. 473 * 474 * @param focusability one of {@link #FOCUS_BEFORE_DESCENDANTS}, {@link #FOCUS_AFTER_DESCENDANTS}, 475 * {@link #FOCUS_BLOCK_DESCENDANTS}. 476 */ 477 public void setDescendantFocusability(int focusability) { 478 switch (focusability) { 479 case FOCUS_BEFORE_DESCENDANTS: 480 case FOCUS_AFTER_DESCENDANTS: 481 case FOCUS_BLOCK_DESCENDANTS: 482 break; 483 default: 484 throw new IllegalArgumentException("must be one of FOCUS_BEFORE_DESCENDANTS, " 485 + "FOCUS_AFTER_DESCENDANTS, FOCUS_BLOCK_DESCENDANTS"); 486 } 487 mGroupFlags &= ~FLAG_MASK_FOCUSABILITY; 488 mGroupFlags |= (focusability & FLAG_MASK_FOCUSABILITY); 489 } 490 491 /** 492 * {@inheritDoc} 493 */ 494 @Override 495 void handleFocusGainInternal(int direction, Rect previouslyFocusedRect) { 496 if (mFocused != null) { 497 mFocused.unFocus(); 498 mFocused = null; 499 } 500 super.handleFocusGainInternal(direction, previouslyFocusedRect); 501 } 502 503 /** 504 * {@inheritDoc} 505 */ 506 public void requestChildFocus(View child, View focused) { 507 if (DBG) { 508 System.out.println(this + " requestChildFocus()"); 509 } 510 if (getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS) { 511 return; 512 } 513 514 // Unfocus us, if necessary 515 super.unFocus(); 516 517 // We had a previous notion of who had focus. Clear it. 518 if (mFocused != child) { 519 if (mFocused != null) { 520 mFocused.unFocus(); 521 } 522 523 mFocused = child; 524 } 525 if (mParent != null) { 526 mParent.requestChildFocus(this, focused); 527 } 528 } 529 530 /** 531 * {@inheritDoc} 532 */ 533 public void focusableViewAvailable(View v) { 534 if (mParent != null 535 // shortcut: don't report a new focusable view if we block our descendants from 536 // getting focus 537 && (getDescendantFocusability() != FOCUS_BLOCK_DESCENDANTS) 538 // shortcut: don't report a new focusable view if we already are focused 539 // (and we don't prefer our descendants) 540 // 541 // note: knowing that mFocused is non-null is not a good enough reason 542 // to break the traversal since in that case we'd actually have to find 543 // the focused view and make sure it wasn't FOCUS_AFTER_DESCENDANTS and 544 // an ancestor of v; this will get checked for at ViewAncestor 545 && !(isFocused() && getDescendantFocusability() != FOCUS_AFTER_DESCENDANTS)) { 546 mParent.focusableViewAvailable(v); 547 } 548 } 549 550 /** 551 * {@inheritDoc} 552 */ 553 public boolean showContextMenuForChild(View originalView) { 554 return mParent != null && mParent.showContextMenuForChild(originalView); 555 } 556 557 /** 558 * {@inheritDoc} 559 */ 560 public ActionMode startActionModeForChild(View originalView, ActionMode.Callback callback) { 561 return mParent != null ? mParent.startActionModeForChild(originalView, callback) : null; 562 } 563 564 /** 565 * Find the nearest view in the specified direction that wants to take 566 * focus. 567 * 568 * @param focused The view that currently has focus 569 * @param direction One of FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, and 570 * FOCUS_RIGHT, or 0 for not applicable. 571 */ 572 public View focusSearch(View focused, int direction) { 573 if (isRootNamespace()) { 574 // root namespace means we should consider ourselves the top of the 575 // tree for focus searching; otherwise we could be focus searching 576 // into other tabs. see LocalActivityManager and TabHost for more info 577 return FocusFinder.getInstance().findNextFocus(this, focused, direction); 578 } else if (mParent != null) { 579 return mParent.focusSearch(focused, direction); 580 } 581 return null; 582 } 583 584 /** 585 * {@inheritDoc} 586 */ 587 public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) { 588 return false; 589 } 590 591 /** 592 * {@inheritDoc} 593 */ 594 public boolean requestSendAccessibilityEvent(View child, AccessibilityEvent event) { 595 ViewParent parent = getParent(); 596 if (parent == null) { 597 return false; 598 } 599 final boolean propagate = onRequestSendAccessibilityEvent(child, event); 600 //noinspection SimplifiableIfStatement 601 if (!propagate) { 602 return false; 603 } 604 return parent.requestSendAccessibilityEvent(this, event); 605 } 606 607 /** 608 * Called when a child has requested sending an {@link AccessibilityEvent} and 609 * gives an opportunity to its parent to augment the event. 610 * 611 * @param child The child which requests sending the event. 612 * @param event The event to be sent. 613 * @return True if the event should be sent. 614 * 615 * @see #requestSendAccessibilityEvent(View, AccessibilityEvent) 616 */ 617 public boolean onRequestSendAccessibilityEvent(View child, AccessibilityEvent event) { 618 return true; 619 } 620 621 /** 622 * {@inheritDoc} 623 */ 624 @Override 625 public boolean dispatchUnhandledMove(View focused, int direction) { 626 return mFocused != null && 627 mFocused.dispatchUnhandledMove(focused, direction); 628 } 629 630 /** 631 * {@inheritDoc} 632 */ 633 public void clearChildFocus(View child) { 634 if (DBG) { 635 System.out.println(this + " clearChildFocus()"); 636 } 637 638 mFocused = null; 639 if (mParent != null) { 640 mParent.clearChildFocus(this); 641 } 642 } 643 644 /** 645 * {@inheritDoc} 646 */ 647 @Override 648 public void clearFocus() { 649 super.clearFocus(); 650 651 // clear any child focus if it exists 652 if (mFocused != null) { 653 mFocused.clearFocus(); 654 } 655 } 656 657 /** 658 * {@inheritDoc} 659 */ 660 @Override 661 void unFocus() { 662 if (DBG) { 663 System.out.println(this + " unFocus()"); 664 } 665 666 super.unFocus(); 667 if (mFocused != null) { 668 mFocused.unFocus(); 669 } 670 mFocused = null; 671 } 672 673 /** 674 * Returns the focused child of this view, if any. The child may have focus 675 * or contain focus. 676 * 677 * @return the focused child or null. 678 */ 679 public View getFocusedChild() { 680 return mFocused; 681 } 682 683 /** 684 * Returns true if this view has or contains focus 685 * 686 * @return true if this view has or contains focus 687 */ 688 @Override 689 public boolean hasFocus() { 690 return (mPrivateFlags & FOCUSED) != 0 || mFocused != null; 691 } 692 693 /* 694 * (non-Javadoc) 695 * 696 * @see android.view.View#findFocus() 697 */ 698 @Override 699 public View findFocus() { 700 if (DBG) { 701 System.out.println("Find focus in " + this + ": flags=" 702 + isFocused() + ", child=" + mFocused); 703 } 704 705 if (isFocused()) { 706 return this; 707 } 708 709 if (mFocused != null) { 710 return mFocused.findFocus(); 711 } 712 return null; 713 } 714 715 /** 716 * {@inheritDoc} 717 */ 718 @Override 719 public boolean hasFocusable() { 720 if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) { 721 return false; 722 } 723 724 if (isFocusable()) { 725 return true; 726 } 727 728 final int descendantFocusability = getDescendantFocusability(); 729 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { 730 final int count = mChildrenCount; 731 final View[] children = mChildren; 732 733 for (int i = 0; i < count; i++) { 734 final View child = children[i]; 735 if (child.hasFocusable()) { 736 return true; 737 } 738 } 739 } 740 741 return false; 742 } 743 744 /** 745 * {@inheritDoc} 746 */ 747 @Override 748 public void addFocusables(ArrayList<View> views, int direction) { 749 addFocusables(views, direction, FOCUSABLES_TOUCH_MODE); 750 } 751 752 /** 753 * {@inheritDoc} 754 */ 755 @Override 756 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 757 final int focusableCount = views.size(); 758 759 final int descendantFocusability = getDescendantFocusability(); 760 761 if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) { 762 final int count = mChildrenCount; 763 final View[] children = mChildren; 764 765 for (int i = 0; i < count; i++) { 766 final View child = children[i]; 767 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 768 child.addFocusables(views, direction, focusableMode); 769 } 770 } 771 } 772 773 // we add ourselves (if focusable) in all cases except for when we are 774 // FOCUS_AFTER_DESCENDANTS and there are some descendants focusable. this is 775 // to avoid the focus search finding layouts when a more precise search 776 // among the focusable children would be more interesting. 777 if ( 778 descendantFocusability != FOCUS_AFTER_DESCENDANTS || 779 // No focusable descendants 780 (focusableCount == views.size())) { 781 super.addFocusables(views, direction, focusableMode); 782 } 783 } 784 785 @Override 786 public void findViewsWithText(ArrayList<View> outViews, CharSequence text) { 787 final int childrenCount = mChildrenCount; 788 final View[] children = mChildren; 789 for (int i = 0; i < childrenCount; i++) { 790 View child = children[i]; 791 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 792 child.findViewsWithText(outViews, text); 793 } 794 } 795 } 796 797 /** 798 * {@inheritDoc} 799 */ 800 @Override 801 public void dispatchWindowFocusChanged(boolean hasFocus) { 802 super.dispatchWindowFocusChanged(hasFocus); 803 final int count = mChildrenCount; 804 final View[] children = mChildren; 805 for (int i = 0; i < count; i++) { 806 children[i].dispatchWindowFocusChanged(hasFocus); 807 } 808 } 809 810 /** 811 * {@inheritDoc} 812 */ 813 @Override 814 public void addTouchables(ArrayList<View> views) { 815 super.addTouchables(views); 816 817 final int count = mChildrenCount; 818 final View[] children = mChildren; 819 820 for (int i = 0; i < count; i++) { 821 final View child = children[i]; 822 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) { 823 child.addTouchables(views); 824 } 825 } 826 } 827 828 /** 829 * {@inheritDoc} 830 */ 831 @Override 832 public void dispatchDisplayHint(int hint) { 833 super.dispatchDisplayHint(hint); 834 final int count = mChildrenCount; 835 final View[] children = mChildren; 836 for (int i = 0; i < count; i++) { 837 children[i].dispatchDisplayHint(hint); 838 } 839 } 840 841 /** 842 * @hide 843 * @param child 844 * @param visibility 845 */ 846 void onChildVisibilityChanged(View child, int visibility) { 847 if (mTransition != null) { 848 if (visibility == VISIBLE) { 849 mTransition.showChild(this, child); 850 } else { 851 mTransition.hideChild(this, child); 852 } 853 if (visibility != VISIBLE) { 854 // Only track this on disappearing views - appearing views are already visible 855 // and don't need special handling during drawChild() 856 if (mVisibilityChangingChildren == null) { 857 mVisibilityChangingChildren = new ArrayList<View>(); 858 } 859 mVisibilityChangingChildren.add(child); 860 if (mTransitioningViews != null && mTransitioningViews.contains(child)) { 861 addDisappearingView(child); 862 } 863 } 864 } 865 866 // in all cases, for drags 867 if (mCurrentDrag != null) { 868 if (visibility == VISIBLE) { 869 notifyChildOfDrag(child); 870 } 871 } 872 } 873 874 /** 875 * {@inheritDoc} 876 */ 877 @Override 878 protected void dispatchVisibilityChanged(View changedView, int visibility) { 879 super.dispatchVisibilityChanged(changedView, visibility); 880 final int count = mChildrenCount; 881 final View[] children = mChildren; 882 for (int i = 0; i < count; i++) { 883 children[i].dispatchVisibilityChanged(changedView, visibility); 884 } 885 } 886 887 /** 888 * {@inheritDoc} 889 */ 890 @Override 891 public void dispatchWindowVisibilityChanged(int visibility) { 892 super.dispatchWindowVisibilityChanged(visibility); 893 final int count = mChildrenCount; 894 final View[] children = mChildren; 895 for (int i = 0; i < count; i++) { 896 children[i].dispatchWindowVisibilityChanged(visibility); 897 } 898 } 899 900 /** 901 * {@inheritDoc} 902 */ 903 @Override 904 public void dispatchConfigurationChanged(Configuration newConfig) { 905 super.dispatchConfigurationChanged(newConfig); 906 final int count = mChildrenCount; 907 final View[] children = mChildren; 908 for (int i = 0; i < count; i++) { 909 children[i].dispatchConfigurationChanged(newConfig); 910 } 911 } 912 913 /** 914 * {@inheritDoc} 915 */ 916 public void recomputeViewAttributes(View child) { 917 if (mAttachInfo != null && !mAttachInfo.mRecomputeGlobalAttributes) { 918 ViewParent parent = mParent; 919 if (parent != null) parent.recomputeViewAttributes(this); 920 } 921 } 922 923 @Override 924 void dispatchCollectViewAttributes(int visibility) { 925 visibility |= mViewFlags&VISIBILITY_MASK; 926 super.dispatchCollectViewAttributes(visibility); 927 final int count = mChildrenCount; 928 final View[] children = mChildren; 929 for (int i = 0; i < count; i++) { 930 children[i].dispatchCollectViewAttributes(visibility); 931 } 932 } 933 934 /** 935 * {@inheritDoc} 936 */ 937 public void bringChildToFront(View child) { 938 int index = indexOfChild(child); 939 if (index >= 0) { 940 removeFromArray(index); 941 addInArray(child, mChildrenCount); 942 child.mParent = this; 943 } 944 } 945 946 /** 947 * {@inheritDoc} 948 * 949 * !!! TODO: write real docs 950 */ 951 @Override 952 public boolean dispatchDragEvent(DragEvent event) { 953 boolean retval = false; 954 final float tx = event.mX; 955 final float ty = event.mY; 956 957 ViewAncestor root = getViewAncestor(); 958 959 // Dispatch down the view hierarchy 960 switch (event.mAction) { 961 case DragEvent.ACTION_DRAG_STARTED: { 962 // clear state to recalculate which views we drag over 963 mCurrentDragView = null; 964 965 // Set up our tracking of drag-started notifications 966 mCurrentDrag = DragEvent.obtain(event); 967 if (mDragNotifiedChildren == null) { 968 mDragNotifiedChildren = new HashSet<View>(); 969 } else { 970 mDragNotifiedChildren.clear(); 971 } 972 973 // Now dispatch down to our children, caching the responses 974 mChildAcceptsDrag = false; 975 final int count = mChildrenCount; 976 final View[] children = mChildren; 977 for (int i = 0; i < count; i++) { 978 final View child = children[i]; 979 child.mPrivateFlags2 &= ~View.DRAG_MASK; 980 if (child.getVisibility() == VISIBLE) { 981 final boolean handled = notifyChildOfDrag(children[i]); 982 if (handled) { 983 mChildAcceptsDrag = true; 984 } 985 } 986 } 987 988 // Return HANDLED if one of our children can accept the drag 989 if (mChildAcceptsDrag) { 990 retval = true; 991 } 992 } break; 993 994 case DragEvent.ACTION_DRAG_ENDED: { 995 // Release the bookkeeping now that the drag lifecycle has ended 996 if (mDragNotifiedChildren != null) { 997 for (View child : mDragNotifiedChildren) { 998 // If a child was notified about an ongoing drag, it's told that it's over 999 child.dispatchDragEvent(event); 1000 child.mPrivateFlags2 &= ~View.DRAG_MASK; 1001 child.refreshDrawableState(); 1002 } 1003 1004 mDragNotifiedChildren.clear(); 1005 mCurrentDrag.recycle(); 1006 mCurrentDrag = null; 1007 } 1008 1009 // We consider drag-ended to have been handled if one of our children 1010 // had offered to handle the drag. 1011 if (mChildAcceptsDrag) { 1012 retval = true; 1013 } 1014 } break; 1015 1016 case DragEvent.ACTION_DRAG_LOCATION: { 1017 // Find the [possibly new] drag target 1018 final View target = findFrontmostDroppableChildAt(event.mX, event.mY, mLocalPoint); 1019 1020 // If we've changed apparent drag target, tell the view root which view 1021 // we're over now [for purposes of the eventual drag-recipient-changed 1022 // notifications to the framework] and tell the new target that the drag 1023 // has entered its bounds. The root will see setDragFocus() calls all 1024 // the way down to the final leaf view that is handling the LOCATION event 1025 // before reporting the new potential recipient to the framework. 1026 if (mCurrentDragView != target) { 1027 root.setDragFocus(target); 1028 1029 final int action = event.mAction; 1030 // If we've dragged off of a child view, send it the EXITED message 1031 if (mCurrentDragView != null) { 1032 final View view = mCurrentDragView; 1033 event.mAction = DragEvent.ACTION_DRAG_EXITED; 1034 view.dispatchDragEvent(event); 1035 view.mPrivateFlags2 &= ~View.DRAG_HOVERED; 1036 view.refreshDrawableState(); 1037 } 1038 mCurrentDragView = target; 1039 1040 // If we've dragged over a new child view, send it the ENTERED message 1041 if (target != null) { 1042 event.mAction = DragEvent.ACTION_DRAG_ENTERED; 1043 target.dispatchDragEvent(event); 1044 target.mPrivateFlags2 |= View.DRAG_HOVERED; 1045 target.refreshDrawableState(); 1046 } 1047 event.mAction = action; // restore the event's original state 1048 } 1049 1050 // Dispatch the actual drag location notice, localized into its coordinates 1051 if (target != null) { 1052 event.mX = mLocalPoint.x; 1053 event.mY = mLocalPoint.y; 1054 1055 retval = target.dispatchDragEvent(event); 1056 1057 event.mX = tx; 1058 event.mY = ty; 1059 } 1060 } break; 1061 1062 /* Entered / exited dispatch 1063 * 1064 * DRAG_ENTERED is not dispatched downwards from ViewGroup. The reason for this is 1065 * that we're about to get the corresponding LOCATION event, which we will use to 1066 * determine which of our children is the new target; at that point we will 1067 * push a DRAG_ENTERED down to the new target child [which may itself be a ViewGroup]. 1068 * 1069 * DRAG_EXITED *is* dispatched all the way down immediately: once we know the 1070 * drag has left this ViewGroup, we know by definition that every contained subview 1071 * is also no longer under the drag point. 1072 */ 1073 1074 case DragEvent.ACTION_DRAG_EXITED: { 1075 if (mCurrentDragView != null) { 1076 final View view = mCurrentDragView; 1077 view.dispatchDragEvent(event); 1078 view.mPrivateFlags2 &= ~View.DRAG_HOVERED; 1079 view.refreshDrawableState(); 1080 1081 mCurrentDragView = null; 1082 } 1083 } break; 1084 1085 case DragEvent.ACTION_DROP: { 1086 if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, "Drop event: " + event); 1087 View target = findFrontmostDroppableChildAt(event.mX, event.mY, mLocalPoint); 1088 if (target != null) { 1089 if (ViewDebug.DEBUG_DRAG) Log.d(View.VIEW_LOG_TAG, " dispatch drop to " + target); 1090 event.mX = mLocalPoint.x; 1091 event.mY = mLocalPoint.y; 1092 retval = target.dispatchDragEvent(event); 1093 event.mX = tx; 1094 event.mY = ty; 1095 } else { 1096 if (ViewDebug.DEBUG_DRAG) { 1097 Log.d(View.VIEW_LOG_TAG, " not dropped on an accepting view"); 1098 } 1099 } 1100 } break; 1101 } 1102 1103 // If none of our children could handle the event, try here 1104 if (!retval) { 1105 // Call up to the View implementation that dispatches to installed listeners 1106 retval = super.dispatchDragEvent(event); 1107 } 1108 return retval; 1109 } 1110 1111 // Find the frontmost child view that lies under the given point, and calculate 1112 // the position within its own local coordinate system. 1113 View findFrontmostDroppableChildAt(float x, float y, PointF outLocalPoint) { 1114 final int count = mChildrenCount; 1115 final View[] children = mChildren; 1116 for (int i = count - 1; i >= 0; i--) { 1117 final View child = children[i]; 1118 if (!child.canAcceptDrag()) { 1119 continue; 1120 } 1121 1122 if (isTransformedTouchPointInView(x, y, child, outLocalPoint)) { 1123 return child; 1124 } 1125 } 1126 return null; 1127 } 1128 1129 boolean notifyChildOfDrag(View child) { 1130 if (ViewDebug.DEBUG_DRAG) { 1131 Log.d(View.VIEW_LOG_TAG, "Sending drag-started to view: " + child); 1132 } 1133 1134 boolean canAccept = false; 1135 if (! mDragNotifiedChildren.contains(child)) { 1136 mDragNotifiedChildren.add(child); 1137 canAccept = child.dispatchDragEvent(mCurrentDrag); 1138 if (canAccept && !child.canAcceptDrag()) { 1139 child.mPrivateFlags2 |= View.DRAG_CAN_ACCEPT; 1140 child.refreshDrawableState(); 1141 } 1142 } 1143 return canAccept; 1144 } 1145 1146 @Override 1147 public void dispatchSystemUiVisibilityChanged(int visible) { 1148 super.dispatchSystemUiVisibilityChanged(visible); 1149 1150 final int count = mChildrenCount; 1151 final View[] children = mChildren; 1152 for (int i=0; i <count; i++) { 1153 final View child = children[i]; 1154 child.dispatchSystemUiVisibilityChanged(visible); 1155 } 1156 } 1157 1158 /** 1159 * {@inheritDoc} 1160 */ 1161 @Override 1162 public boolean dispatchKeyEventPreIme(KeyEvent event) { 1163 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1164 return super.dispatchKeyEventPreIme(event); 1165 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1166 return mFocused.dispatchKeyEventPreIme(event); 1167 } 1168 return false; 1169 } 1170 1171 /** 1172 * {@inheritDoc} 1173 */ 1174 @Override 1175 public boolean dispatchKeyEvent(KeyEvent event) { 1176 if (mInputEventConsistencyVerifier != null) { 1177 mInputEventConsistencyVerifier.onKeyEvent(event, 1); 1178 } 1179 1180 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1181 if (super.dispatchKeyEvent(event)) { 1182 return true; 1183 } 1184 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1185 if (mFocused.dispatchKeyEvent(event)) { 1186 return true; 1187 } 1188 } 1189 1190 if (mInputEventConsistencyVerifier != null) { 1191 mInputEventConsistencyVerifier.onUnhandledEvent(event, 1); 1192 } 1193 return false; 1194 } 1195 1196 /** 1197 * {@inheritDoc} 1198 */ 1199 @Override 1200 public boolean dispatchKeyShortcutEvent(KeyEvent event) { 1201 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1202 return super.dispatchKeyShortcutEvent(event); 1203 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1204 return mFocused.dispatchKeyShortcutEvent(event); 1205 } 1206 return false; 1207 } 1208 1209 /** 1210 * {@inheritDoc} 1211 */ 1212 @Override 1213 public boolean dispatchTrackballEvent(MotionEvent event) { 1214 if (mInputEventConsistencyVerifier != null) { 1215 mInputEventConsistencyVerifier.onTrackballEvent(event, 1); 1216 } 1217 1218 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1219 if (super.dispatchTrackballEvent(event)) { 1220 return true; 1221 } 1222 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1223 if (mFocused.dispatchTrackballEvent(event)) { 1224 return true; 1225 } 1226 } 1227 1228 if (mInputEventConsistencyVerifier != null) { 1229 mInputEventConsistencyVerifier.onUnhandledEvent(event, 1); 1230 } 1231 return false; 1232 } 1233 1234 /** 1235 * {@inheritDoc} 1236 */ 1237 @SuppressWarnings({"ConstantConditions"}) 1238 @Override 1239 protected boolean dispatchHoverEvent(MotionEvent event) { 1240 final int action = event.getAction(); 1241 1242 // First check whether the view group wants to intercept the hover event. 1243 final boolean interceptHover = onInterceptHoverEvent(event); 1244 event.setAction(action); // restore action in case it was changed 1245 1246 MotionEvent eventNoHistory = event; 1247 boolean handled = false; 1248 1249 // Send events to the hovered children and build a new list of hover targets until 1250 // one is found that handles the event. 1251 HoverTarget firstOldHoverTarget = mFirstHoverTarget; 1252 mFirstHoverTarget = null; 1253 if (!interceptHover && action != MotionEvent.ACTION_HOVER_EXIT) { 1254 final float x = event.getX(); 1255 final float y = event.getY(); 1256 final int childrenCount = mChildrenCount; 1257 if (childrenCount != 0) { 1258 final View[] children = mChildren; 1259 HoverTarget lastHoverTarget = null; 1260 for (int i = childrenCount - 1; i >= 0; i--) { 1261 final View child = children[i]; 1262 if (!canViewReceivePointerEvents(child) 1263 || !isTransformedTouchPointInView(x, y, child, null)) { 1264 continue; 1265 } 1266 1267 // Obtain a hover target for this child. Dequeue it from the 1268 // old hover target list if the child was previously hovered. 1269 HoverTarget hoverTarget = firstOldHoverTarget; 1270 final boolean wasHovered; 1271 for (HoverTarget predecessor = null; ;) { 1272 if (hoverTarget == null) { 1273 hoverTarget = HoverTarget.obtain(child); 1274 wasHovered = false; 1275 break; 1276 } 1277 1278 if (hoverTarget.child == child) { 1279 if (predecessor != null) { 1280 predecessor.next = hoverTarget.next; 1281 } else { 1282 firstOldHoverTarget = hoverTarget.next; 1283 } 1284 hoverTarget.next = null; 1285 wasHovered = true; 1286 break; 1287 } 1288 1289 predecessor = hoverTarget; 1290 hoverTarget = hoverTarget.next; 1291 } 1292 1293 // Enqueue the hover target onto the new hover target list. 1294 if (lastHoverTarget != null) { 1295 lastHoverTarget.next = hoverTarget; 1296 } else { 1297 lastHoverTarget = hoverTarget; 1298 mFirstHoverTarget = hoverTarget; 1299 } 1300 1301 // Dispatch the event to the child. 1302 if (action == MotionEvent.ACTION_HOVER_ENTER) { 1303 if (!wasHovered) { 1304 // Send the enter as is. 1305 handled |= dispatchTransformedGenericPointerEvent( 1306 event, child); // enter 1307 } 1308 } else if (action == MotionEvent.ACTION_HOVER_MOVE) { 1309 if (!wasHovered) { 1310 // Synthesize an enter from a move. 1311 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1312 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER); 1313 handled |= dispatchTransformedGenericPointerEvent( 1314 eventNoHistory, child); // enter 1315 eventNoHistory.setAction(action); 1316 1317 handled |= dispatchTransformedGenericPointerEvent( 1318 eventNoHistory, child); // move 1319 } else { 1320 // Send the move as is. 1321 handled |= dispatchTransformedGenericPointerEvent(event, child); 1322 } 1323 } 1324 if (handled) { 1325 break; 1326 } 1327 } 1328 } 1329 } 1330 1331 // Send exit events to all previously hovered children that are no longer hovered. 1332 while (firstOldHoverTarget != null) { 1333 final View child = firstOldHoverTarget.child; 1334 1335 // Exit the old hovered child. 1336 if (action == MotionEvent.ACTION_HOVER_EXIT) { 1337 // Send the exit as is. 1338 handled |= dispatchTransformedGenericPointerEvent( 1339 event, child); // exit 1340 } else { 1341 // Synthesize an exit from a move or enter. 1342 // Ignore the result because hover focus has moved to a different view. 1343 if (action == MotionEvent.ACTION_HOVER_MOVE) { 1344 dispatchTransformedGenericPointerEvent( 1345 event, child); // move 1346 } 1347 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1348 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT); 1349 dispatchTransformedGenericPointerEvent( 1350 eventNoHistory, child); // exit 1351 eventNoHistory.setAction(action); 1352 } 1353 1354 final HoverTarget nextOldHoverTarget = firstOldHoverTarget.next; 1355 firstOldHoverTarget.recycle(); 1356 firstOldHoverTarget = nextOldHoverTarget; 1357 } 1358 1359 // Send events to the view group itself if no children have handled it. 1360 boolean newHoveredSelf = !handled; 1361 if (newHoveredSelf == mHoveredSelf) { 1362 if (newHoveredSelf) { 1363 // Send event to the view group as before. 1364 handled |= super.dispatchHoverEvent(event); 1365 } 1366 } else { 1367 if (mHoveredSelf) { 1368 // Exit the view group. 1369 if (action == MotionEvent.ACTION_HOVER_EXIT) { 1370 // Send the exit as is. 1371 handled |= super.dispatchHoverEvent(event); // exit 1372 } else { 1373 // Synthesize an exit from a move or enter. 1374 // Ignore the result because hover focus is moving to a different view. 1375 if (action == MotionEvent.ACTION_HOVER_MOVE) { 1376 super.dispatchHoverEvent(event); // move 1377 } 1378 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1379 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_EXIT); 1380 super.dispatchHoverEvent(eventNoHistory); // exit 1381 eventNoHistory.setAction(action); 1382 } 1383 mHoveredSelf = false; 1384 } 1385 1386 if (newHoveredSelf) { 1387 // Enter the view group. 1388 if (action == MotionEvent.ACTION_HOVER_ENTER) { 1389 // Send the enter as is. 1390 handled |= super.dispatchHoverEvent(event); // enter 1391 mHoveredSelf = true; 1392 } else if (action == MotionEvent.ACTION_HOVER_MOVE) { 1393 // Synthesize an enter from a move. 1394 eventNoHistory = obtainMotionEventNoHistoryOrSelf(eventNoHistory); 1395 eventNoHistory.setAction(MotionEvent.ACTION_HOVER_ENTER); 1396 handled |= super.dispatchHoverEvent(eventNoHistory); // enter 1397 eventNoHistory.setAction(action); 1398 1399 handled |= super.dispatchHoverEvent(eventNoHistory); // move 1400 mHoveredSelf = true; 1401 } 1402 } 1403 } 1404 1405 // Recycle the copy of the event that we made. 1406 if (eventNoHistory != event) { 1407 eventNoHistory.recycle(); 1408 } 1409 1410 // Done. 1411 return handled; 1412 } 1413 1414 /** @hide */ 1415 @Override 1416 protected boolean hasHoveredChild() { 1417 return mFirstHoverTarget != null; 1418 } 1419 1420 /** 1421 * Implement this method to intercept hover events before they are handled 1422 * by child views. 1423 * <p> 1424 * This method is called before dispatching a hover event to a child of 1425 * the view group or to the view group's own {@link #onHoverEvent} to allow 1426 * the view group a chance to intercept the hover event. 1427 * This method can also be used to watch all pointer motions that occur within 1428 * the bounds of the view group even when the pointer is hovering over 1429 * a child of the view group rather than over the view group itself. 1430 * </p><p> 1431 * The view group can prevent its children from receiving hover events by 1432 * implementing this method and returning <code>true</code> to indicate 1433 * that it would like to intercept hover events. The view group must 1434 * continuously return <code>true</code> from {@link #onInterceptHoverEvent} 1435 * for as long as it wishes to continue intercepting hover events from 1436 * its children. 1437 * </p><p> 1438 * Interception preserves the invariant that at most one view can be 1439 * hovered at a time by transferring hover focus from the currently hovered 1440 * child to the view group or vice-versa as needed. 1441 * </p><p> 1442 * If this method returns <code>true</code> and a child is already hovered, then the 1443 * child view will first receive a hover exit event and then the view group 1444 * itself will receive a hover enter event in {@link #onHoverEvent}. 1445 * Likewise, if this method had previously returned <code>true</code> to intercept hover 1446 * events and instead returns <code>false</code> while the pointer is hovering 1447 * within the bounds of one of a child, then the view group will first receive a 1448 * hover exit event in {@link #onHoverEvent} and then the hovered child will 1449 * receive a hover enter event. 1450 * </p><p> 1451 * The default implementation always returns false. 1452 * </p> 1453 * 1454 * @param event The motion event that describes the hover. 1455 * @return True if the view group would like to intercept the hover event 1456 * and prevent its children from receiving it. 1457 */ 1458 public boolean onInterceptHoverEvent(MotionEvent event) { 1459 return false; 1460 } 1461 1462 private static MotionEvent obtainMotionEventNoHistoryOrSelf(MotionEvent event) { 1463 if (event.getHistorySize() == 0) { 1464 return event; 1465 } 1466 return MotionEvent.obtainNoHistory(event); 1467 } 1468 1469 /** 1470 * {@inheritDoc} 1471 */ 1472 @Override 1473 protected boolean dispatchGenericPointerEvent(MotionEvent event) { 1474 // Send the event to the child under the pointer. 1475 final int childrenCount = mChildrenCount; 1476 if (childrenCount != 0) { 1477 final View[] children = mChildren; 1478 final float x = event.getX(); 1479 final float y = event.getY(); 1480 1481 for (int i = childrenCount - 1; i >= 0; i--) { 1482 final View child = children[i]; 1483 if (!canViewReceivePointerEvents(child) 1484 || !isTransformedTouchPointInView(x, y, child, null)) { 1485 continue; 1486 } 1487 1488 if (dispatchTransformedGenericPointerEvent(event, child)) { 1489 return true; 1490 } 1491 } 1492 } 1493 1494 // No child handled the event. Send it to this view group. 1495 return super.dispatchGenericPointerEvent(event); 1496 } 1497 1498 /** 1499 * {@inheritDoc} 1500 */ 1501 @Override 1502 protected boolean dispatchGenericFocusedEvent(MotionEvent event) { 1503 // Send the event to the focused child or to this view group if it has focus. 1504 if ((mPrivateFlags & (FOCUSED | HAS_BOUNDS)) == (FOCUSED | HAS_BOUNDS)) { 1505 return super.dispatchGenericFocusedEvent(event); 1506 } else if (mFocused != null && (mFocused.mPrivateFlags & HAS_BOUNDS) == HAS_BOUNDS) { 1507 return mFocused.dispatchGenericMotionEvent(event); 1508 } 1509 return false; 1510 } 1511 1512 /** 1513 * Dispatches a generic pointer event to a child, taking into account 1514 * transformations that apply to the child. 1515 * 1516 * @param event The event to send. 1517 * @param child The view to send the event to. 1518 * @return {@code true} if the child handled the event. 1519 */ 1520 private boolean dispatchTransformedGenericPointerEvent(MotionEvent event, View child) { 1521 final float offsetX = mScrollX - child.mLeft; 1522 final float offsetY = mScrollY - child.mTop; 1523 1524 boolean handled; 1525 if (!child.hasIdentityMatrix()) { 1526 MotionEvent transformedEvent = MotionEvent.obtain(event); 1527 transformedEvent.offsetLocation(offsetX, offsetY); 1528 transformedEvent.transform(child.getInverseMatrix()); 1529 handled = child.dispatchGenericMotionEvent(transformedEvent); 1530 transformedEvent.recycle(); 1531 } else { 1532 event.offsetLocation(offsetX, offsetY); 1533 handled = child.dispatchGenericMotionEvent(event); 1534 event.offsetLocation(-offsetX, -offsetY); 1535 } 1536 return handled; 1537 } 1538 1539 /** 1540 * {@inheritDoc} 1541 */ 1542 @Override 1543 public boolean dispatchTouchEvent(MotionEvent ev) { 1544 if (mInputEventConsistencyVerifier != null) { 1545 mInputEventConsistencyVerifier.onTouchEvent(ev, 1); 1546 } 1547 1548 boolean handled = false; 1549 if (onFilterTouchEventForSecurity(ev)) { 1550 final int action = ev.getAction(); 1551 final int actionMasked = action & MotionEvent.ACTION_MASK; 1552 1553 // Handle an initial down. 1554 if (actionMasked == MotionEvent.ACTION_DOWN) { 1555 // Throw away all previous state when starting a new touch gesture. 1556 // The framework may have dropped the up or cancel event for the previous gesture 1557 // due to an app switch, ANR, or some other state change. 1558 cancelAndClearTouchTargets(ev); 1559 resetTouchState(); 1560 } 1561 1562 // Check for interception. 1563 final boolean intercepted; 1564 if (actionMasked == MotionEvent.ACTION_DOWN 1565 || mFirstTouchTarget != null) { 1566 final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0; 1567 if (!disallowIntercept) { 1568 intercepted = onInterceptTouchEvent(ev); 1569 ev.setAction(action); // restore action in case it was changed 1570 } else { 1571 intercepted = false; 1572 } 1573 } else { 1574 // There are no touch targets and this action is not an initial down 1575 // so this view group continues to intercept touches. 1576 intercepted = true; 1577 } 1578 1579 // Check for cancelation. 1580 final boolean canceled = resetCancelNextUpFlag(this) 1581 || actionMasked == MotionEvent.ACTION_CANCEL; 1582 1583 // Update list of touch targets for pointer down, if needed. 1584 final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0; 1585 TouchTarget newTouchTarget = null; 1586 boolean alreadyDispatchedToNewTouchTarget = false; 1587 if (!canceled && !intercepted) { 1588 if (actionMasked == MotionEvent.ACTION_DOWN 1589 || (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN) 1590 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { 1591 final int actionIndex = ev.getActionIndex(); // always 0 for down 1592 final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex) 1593 : TouchTarget.ALL_POINTER_IDS; 1594 1595 // Clean up earlier touch targets for this pointer id in case they 1596 // have become out of sync. 1597 removePointersFromTouchTargets(idBitsToAssign); 1598 1599 final int childrenCount = mChildrenCount; 1600 if (childrenCount != 0) { 1601 // Find a child that can receive the event. 1602 // Scan children from front to back. 1603 final View[] children = mChildren; 1604 final float x = ev.getX(actionIndex); 1605 final float y = ev.getY(actionIndex); 1606 1607 for (int i = childrenCount - 1; i >= 0; i--) { 1608 final View child = children[i]; 1609 if (!canViewReceivePointerEvents(child) 1610 || !isTransformedTouchPointInView(x, y, child, null)) { 1611 continue; 1612 } 1613 1614 newTouchTarget = getTouchTarget(child); 1615 if (newTouchTarget != null) { 1616 // Child is already receiving touch within its bounds. 1617 // Give it the new pointer in addition to the ones it is handling. 1618 newTouchTarget.pointerIdBits |= idBitsToAssign; 1619 break; 1620 } 1621 1622 resetCancelNextUpFlag(child); 1623 if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) { 1624 // Child wants to receive touch within its bounds. 1625 mLastTouchDownTime = ev.getDownTime(); 1626 mLastTouchDownIndex = i; 1627 mLastTouchDownX = ev.getX(); 1628 mLastTouchDownY = ev.getY(); 1629 newTouchTarget = addTouchTarget(child, idBitsToAssign); 1630 alreadyDispatchedToNewTouchTarget = true; 1631 break; 1632 } 1633 } 1634 } 1635 1636 if (newTouchTarget == null && mFirstTouchTarget != null) { 1637 // Did not find a child to receive the event. 1638 // Assign the pointer to the least recently added target. 1639 newTouchTarget = mFirstTouchTarget; 1640 while (newTouchTarget.next != null) { 1641 newTouchTarget = newTouchTarget.next; 1642 } 1643 newTouchTarget.pointerIdBits |= idBitsToAssign; 1644 } 1645 } 1646 } 1647 1648 // Dispatch to touch targets. 1649 if (mFirstTouchTarget == null) { 1650 // No touch targets so treat this as an ordinary view. 1651 handled = dispatchTransformedTouchEvent(ev, canceled, null, 1652 TouchTarget.ALL_POINTER_IDS); 1653 } else { 1654 // Dispatch to touch targets, excluding the new touch target if we already 1655 // dispatched to it. Cancel touch targets if necessary. 1656 TouchTarget predecessor = null; 1657 TouchTarget target = mFirstTouchTarget; 1658 while (target != null) { 1659 final TouchTarget next = target.next; 1660 if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) { 1661 handled = true; 1662 } else { 1663 final boolean cancelChild = resetCancelNextUpFlag(target.child) 1664 || intercepted; 1665 if (dispatchTransformedTouchEvent(ev, cancelChild, 1666 target.child, target.pointerIdBits)) { 1667 handled = true; 1668 } 1669 if (cancelChild) { 1670 if (predecessor == null) { 1671 mFirstTouchTarget = next; 1672 } else { 1673 predecessor.next = next; 1674 } 1675 target.recycle(); 1676 target = next; 1677 continue; 1678 } 1679 } 1680 predecessor = target; 1681 target = next; 1682 } 1683 } 1684 1685 // Update list of touch targets for pointer up or cancel, if needed. 1686 if (canceled 1687 || actionMasked == MotionEvent.ACTION_UP 1688 || actionMasked == MotionEvent.ACTION_HOVER_MOVE) { 1689 resetTouchState(); 1690 } else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) { 1691 final int actionIndex = ev.getActionIndex(); 1692 final int idBitsToRemove = 1 << ev.getPointerId(actionIndex); 1693 removePointersFromTouchTargets(idBitsToRemove); 1694 } 1695 } 1696 1697 if (!handled && mInputEventConsistencyVerifier != null) { 1698 mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1); 1699 } 1700 return handled; 1701 } 1702 1703 /** 1704 * Resets all touch state in preparation for a new cycle. 1705 */ 1706 private void resetTouchState() { 1707 clearTouchTargets(); 1708 resetCancelNextUpFlag(this); 1709 mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT; 1710 } 1711 1712 /** 1713 * Resets the cancel next up flag. 1714 * Returns true if the flag was previously set. 1715 */ 1716 private boolean resetCancelNextUpFlag(View view) { 1717 if ((view.mPrivateFlags & CANCEL_NEXT_UP_EVENT) != 0) { 1718 view.mPrivateFlags &= ~CANCEL_NEXT_UP_EVENT; 1719 return true; 1720 } 1721 return false; 1722 } 1723 1724 /** 1725 * Clears all touch targets. 1726 */ 1727 private void clearTouchTargets() { 1728 TouchTarget target = mFirstTouchTarget; 1729 if (target != null) { 1730 do { 1731 TouchTarget next = target.next; 1732 target.recycle(); 1733 target = next; 1734 } while (target != null); 1735 mFirstTouchTarget = null; 1736 } 1737 } 1738 1739 /** 1740 * Cancels and clears all touch targets. 1741 */ 1742 private void cancelAndClearTouchTargets(MotionEvent event) { 1743 if (mFirstTouchTarget != null) { 1744 boolean syntheticEvent = false; 1745 if (event == null) { 1746 final long now = SystemClock.uptimeMillis(); 1747 event = MotionEvent.obtain(now, now, 1748 MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); 1749 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 /** 5002 * This method will be called when we need to reset the layout direction resolution flag 5003 * 5004 */ 5005 @Override 5006 void resetLayoutDirectionResolution() { 5007 super.resetLayoutDirectionResolution(); 5008 5009 // Take care of resetting the children resolution too 5010 final int count = getChildCount(); 5011 for (int i = 0; i < count; i++) { 5012 final View child = getChildAt(i); 5013 if (child.getLayoutDirection() == LAYOUT_DIRECTION_INHERIT) { 5014 child.resetLayoutDirectionResolution(); 5015 } 5016 } 5017 } 5018 5019 /** 5020 * This method will be called during text direction resolution (text direction resolution 5021 * inheritance) 5022 */ 5023 @Override 5024 protected void resolveTextDirection() { 5025 int resolvedTextDirection = TEXT_DIRECTION_UNDEFINED; 5026 switch(mTextDirection) { 5027 default: 5028 case TEXT_DIRECTION_INHERIT: 5029 // Try to the text direction from the parent layout 5030 if (mParent != null && mParent instanceof ViewGroup) { 5031 resolvedTextDirection = ((ViewGroup) mParent).getResolvedTextDirection(); 5032 } else { 5033 // We reached the top of the View hierarchy, so get the direction from 5034 // the Locale 5035 resolvedTextDirection = isLayoutDirectionRtl(Locale.getDefault()) ? 5036 TEXT_DIRECTION_RTL : TEXT_DIRECTION_LTR; 5037 } 5038 break; 5039 // Pass down the hierarchy the following text direction values 5040 case TEXT_DIRECTION_FIRST_STRONG: 5041 case TEXT_DIRECTION_ANY_RTL: 5042 case TEXT_DIRECTION_LTR: 5043 case TEXT_DIRECTION_RTL: 5044 resolvedTextDirection = mTextDirection; 5045 break; 5046 } 5047 mResolvedTextDirection = resolvedTextDirection; 5048 } 5049 5050 @Override 5051 protected void resetResolvedTextDirection() { 5052 super.resetResolvedTextDirection(); 5053 5054 // Take care of resetting the children resolution too 5055 final int count = getChildCount(); 5056 for (int i = 0; i < count; i++) { 5057 final View child = getChildAt(i); 5058 if (child.getTextDirection() == TEXT_DIRECTION_INHERIT) { 5059 child.resetResolvedTextDirection(); 5060 } 5061 } 5062 } 5063 5064 /** 5065 * Return true if the pressed state should be delayed for children or descendants of this 5066 * ViewGroup. Generally, this should be done for containers that can scroll, such as a List. 5067 * This prevents the pressed state from appearing when the user is actually trying to scroll 5068 * the content. 5069 * 5070 * The default implementation returns true for compatibility reasons. Subclasses that do 5071 * not scroll should generally override this method and return false. 5072 */ 5073 public boolean shouldDelayChildPressedState() { 5074 return true; 5075 } 5076 5077 /** 5078 * LayoutParams are used by views to tell their parents how they want to be 5079 * laid out. See 5080 * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes} 5081 * for a list of all child view attributes that this class supports. 5082 * 5083 * <p> 5084 * The base LayoutParams class just describes how big the view wants to be 5085 * for both width and height. For each dimension, it can specify one of: 5086 * <ul> 5087 * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which 5088 * means that the view wants to be as big as its parent (minus padding) 5089 * <li> WRAP_CONTENT, which means that the view wants to be just big enough 5090 * to enclose its content (plus padding) 5091 * <li> an exact number 5092 * </ul> 5093 * There are subclasses of LayoutParams for different subclasses of 5094 * ViewGroup. For example, AbsoluteLayout has its own subclass of 5095 * LayoutParams which adds an X and Y value. 5096 * 5097 * @attr ref android.R.styleable#ViewGroup_Layout_layout_height 5098 * @attr ref android.R.styleable#ViewGroup_Layout_layout_width 5099 */ 5100 public static class LayoutParams { 5101 /** 5102 * Special value for the height or width requested by a View. 5103 * FILL_PARENT means that the view wants to be as big as its parent, 5104 * minus the parent's padding, if any. This value is deprecated 5105 * starting in API Level 8 and replaced by {@link #MATCH_PARENT}. 5106 */ 5107 @SuppressWarnings({"UnusedDeclaration"}) 5108 @Deprecated 5109 public static final int FILL_PARENT = -1; 5110 5111 /** 5112 * Special value for the height or width requested by a View. 5113 * MATCH_PARENT means that the view wants to be as big as its parent, 5114 * minus the parent's padding, if any. Introduced in API Level 8. 5115 */ 5116 public static final int MATCH_PARENT = -1; 5117 5118 /** 5119 * Special value for the height or width requested by a View. 5120 * WRAP_CONTENT means that the view wants to be just large enough to fit 5121 * its own internal content, taking its own padding into account. 5122 */ 5123 public static final int WRAP_CONTENT = -2; 5124 5125 /** 5126 * Information about how wide the view wants to be. Can be one of the 5127 * constants FILL_PARENT (replaced by MATCH_PARENT , 5128 * in API Level 8) or WRAP_CONTENT. or an exact size. 5129 */ 5130 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5131 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5132 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5133 }) 5134 public int width; 5135 5136 /** 5137 * Information about how tall the view wants to be. Can be one of the 5138 * constants FILL_PARENT (replaced by MATCH_PARENT , 5139 * in API Level 8) or WRAP_CONTENT. or an exact size. 5140 */ 5141 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5142 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5143 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5144 }) 5145 public int height; 5146 5147 /** 5148 * Used to animate layouts. 5149 */ 5150 public LayoutAnimationController.AnimationParameters layoutAnimationParameters; 5151 5152 /** 5153 * Creates a new set of layout parameters. The values are extracted from 5154 * the supplied attributes set and context. The XML attributes mapped 5155 * to this set of layout parameters are: 5156 * 5157 * <ul> 5158 * <li><code>layout_width</code>: the width, either an exact value, 5159 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5160 * {@link #MATCH_PARENT} in API Level 8)</li> 5161 * <li><code>layout_height</code>: the height, either an exact value, 5162 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5163 * {@link #MATCH_PARENT} in API Level 8)</li> 5164 * </ul> 5165 * 5166 * @param c the application environment 5167 * @param attrs the set of attributes from which to extract the layout 5168 * parameters' values 5169 */ 5170 public LayoutParams(Context c, AttributeSet attrs) { 5171 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout); 5172 setBaseAttributes(a, 5173 R.styleable.ViewGroup_Layout_layout_width, 5174 R.styleable.ViewGroup_Layout_layout_height); 5175 a.recycle(); 5176 } 5177 5178 /** 5179 * Creates a new set of layout parameters with the specified width 5180 * and height. 5181 * 5182 * @param width the width, either {@link #WRAP_CONTENT}, 5183 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5184 * API Level 8), or a fixed size in pixels 5185 * @param height the height, either {@link #WRAP_CONTENT}, 5186 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5187 * API Level 8), or a fixed size in pixels 5188 */ 5189 public LayoutParams(int width, int height) { 5190 this.width = width; 5191 this.height = height; 5192 } 5193 5194 /** 5195 * Copy constructor. Clones the width and height values of the source. 5196 * 5197 * @param source The layout params to copy from. 5198 */ 5199 public LayoutParams(LayoutParams source) { 5200 this.width = source.width; 5201 this.height = source.height; 5202 } 5203 5204 /** 5205 * Used internally by MarginLayoutParams. 5206 * @hide 5207 */ 5208 LayoutParams() { 5209 } 5210 5211 /** 5212 * Extracts the layout parameters from the supplied attributes. 5213 * 5214 * @param a the style attributes to extract the parameters from 5215 * @param widthAttr the identifier of the width attribute 5216 * @param heightAttr the identifier of the height attribute 5217 */ 5218 protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { 5219 width = a.getLayoutDimension(widthAttr, "layout_width"); 5220 height = a.getLayoutDimension(heightAttr, "layout_height"); 5221 } 5222 5223 /** 5224 * Resolve layout parameters depending on the layout direction. Subclasses that care about 5225 * layoutDirection changes should override this method. The default implementation does 5226 * nothing. 5227 * 5228 * @param layoutDirection the direction of the layout 5229 * 5230 * {@link View#LAYOUT_DIRECTION_LTR} 5231 * {@link View#LAYOUT_DIRECTION_RTL} 5232 * 5233 * @hide 5234 */ 5235 protected void resolveWithDirection(int layoutDirection) { 5236 } 5237 5238 /** 5239 * Returns a String representation of this set of layout parameters. 5240 * 5241 * @param output the String to prepend to the internal representation 5242 * @return a String with the following format: output + 5243 * "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }" 5244 * 5245 * @hide 5246 */ 5247 public String debug(String output) { 5248 return output + "ViewGroup.LayoutParams={ width=" 5249 + sizeToString(width) + ", height=" + sizeToString(height) + " }"; 5250 } 5251 5252 /** 5253 * Converts the specified size to a readable String. 5254 * 5255 * @param size the size to convert 5256 * @return a String instance representing the supplied size 5257 * 5258 * @hide 5259 */ 5260 protected static String sizeToString(int size) { 5261 if (size == WRAP_CONTENT) { 5262 return "wrap-content"; 5263 } 5264 if (size == MATCH_PARENT) { 5265 return "match-parent"; 5266 } 5267 return String.valueOf(size); 5268 } 5269 } 5270 5271 /** 5272 * Per-child layout information for layouts that support margins. 5273 * See 5274 * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes} 5275 * for a list of all child view attributes that this class supports. 5276 */ 5277 public static class MarginLayoutParams extends ViewGroup.LayoutParams { 5278 /** 5279 * The left margin in pixels of the child. Whenever this value is changed, a call to 5280 * {@link android.view.View#requestLayout()} needs to be done. 5281 */ 5282 @ViewDebug.ExportedProperty(category = "layout") 5283 public int leftMargin; 5284 5285 /** 5286 * The top margin in pixels of the child. Whenever this value is changed, a call to 5287 * {@link android.view.View#requestLayout()} needs to be done. 5288 */ 5289 @ViewDebug.ExportedProperty(category = "layout") 5290 public int topMargin; 5291 5292 /** 5293 * The right margin in pixels of the child. Whenever this value is changed, a call to 5294 * {@link android.view.View#requestLayout()} needs to be done. 5295 */ 5296 @ViewDebug.ExportedProperty(category = "layout") 5297 public int rightMargin; 5298 5299 /** 5300 * The bottom margin in pixels of the child. Whenever this value is changed, a call to 5301 * {@link android.view.View#requestLayout()} needs to be done. 5302 */ 5303 @ViewDebug.ExportedProperty(category = "layout") 5304 public int bottomMargin; 5305 5306 /** 5307 * The start margin in pixels of the child. 5308 * 5309 * @hide 5310 * 5311 */ 5312 @ViewDebug.ExportedProperty(category = "layout") 5313 protected int startMargin = DEFAULT_RELATIVE; 5314 5315 /** 5316 * The end margin in pixels of the child. 5317 * 5318 * @hide 5319 */ 5320 @ViewDebug.ExportedProperty(category = "layout") 5321 protected int endMargin = DEFAULT_RELATIVE; 5322 5323 /** 5324 * The default start and end margin. 5325 */ 5326 static private final int DEFAULT_RELATIVE = Integer.MIN_VALUE; 5327 5328 /** 5329 * Creates a new set of layout parameters. The values are extracted from 5330 * the supplied attributes set and context. 5331 * 5332 * @param c the application environment 5333 * @param attrs the set of attributes from which to extract the layout 5334 * parameters' values 5335 */ 5336 public MarginLayoutParams(Context c, AttributeSet attrs) { 5337 super(); 5338 5339 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout); 5340 setBaseAttributes(a, 5341 R.styleable.ViewGroup_MarginLayout_layout_width, 5342 R.styleable.ViewGroup_MarginLayout_layout_height); 5343 5344 int margin = a.getDimensionPixelSize( 5345 com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1); 5346 if (margin >= 0) { 5347 leftMargin = margin; 5348 topMargin = margin; 5349 rightMargin= margin; 5350 bottomMargin = margin; 5351 } else { 5352 leftMargin = a.getDimensionPixelSize( 5353 R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 0); 5354 topMargin = a.getDimensionPixelSize( 5355 R.styleable.ViewGroup_MarginLayout_layout_marginTop, 0); 5356 rightMargin = a.getDimensionPixelSize( 5357 R.styleable.ViewGroup_MarginLayout_layout_marginRight, 0); 5358 bottomMargin = a.getDimensionPixelSize( 5359 R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 0); 5360 startMargin = a.getDimensionPixelSize( 5361 R.styleable.ViewGroup_MarginLayout_layout_marginStart, DEFAULT_RELATIVE); 5362 endMargin = a.getDimensionPixelSize( 5363 R.styleable.ViewGroup_MarginLayout_layout_marginEnd, DEFAULT_RELATIVE); 5364 } 5365 5366 a.recycle(); 5367 } 5368 5369 /** 5370 * {@inheritDoc} 5371 */ 5372 public MarginLayoutParams(int width, int height) { 5373 super(width, height); 5374 } 5375 5376 /** 5377 * Copy constructor. Clones the width, height and margin values of the source. 5378 * 5379 * @param source The layout params to copy from. 5380 */ 5381 public MarginLayoutParams(MarginLayoutParams source) { 5382 this.width = source.width; 5383 this.height = source.height; 5384 5385 this.leftMargin = source.leftMargin; 5386 this.topMargin = source.topMargin; 5387 this.rightMargin = source.rightMargin; 5388 this.bottomMargin = source.bottomMargin; 5389 this.startMargin = source.startMargin; 5390 this.endMargin = source.endMargin; 5391 } 5392 5393 /** 5394 * {@inheritDoc} 5395 */ 5396 public MarginLayoutParams(LayoutParams source) { 5397 super(source); 5398 } 5399 5400 /** 5401 * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs 5402 * to be done so that the new margins are taken into account. Left and right margins may be 5403 * overriden by {@link android.view.View#requestLayout()} depending on layout direction. 5404 * 5405 * @param left the left margin size 5406 * @param top the top margin size 5407 * @param right the right margin size 5408 * @param bottom the bottom margin size 5409 * 5410 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft 5411 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 5412 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight 5413 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 5414 */ 5415 public void setMargins(int left, int top, int right, int bottom) { 5416 leftMargin = left; 5417 topMargin = top; 5418 rightMargin = right; 5419 bottomMargin = bottom; 5420 } 5421 5422 /** 5423 * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()} 5424 * needs to be done so that the new relative margins are taken into account. Left and right 5425 * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout 5426 * direction. 5427 * 5428 * @param start the start margin size 5429 * @param top the top margin size 5430 * @param end the right margin size 5431 * @param bottom the bottom margin size 5432 * 5433 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5434 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 5435 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5436 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 5437 * 5438 * @hide 5439 */ 5440 public void setMarginsRelative(int start, int top, int end, int bottom) { 5441 startMargin = start; 5442 topMargin = top; 5443 endMargin = end; 5444 bottomMargin = bottom; 5445 } 5446 5447 /** 5448 * Returns the start margin in pixels. 5449 * 5450 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5451 * 5452 * @return the start margin in pixels. 5453 * 5454 * @hide 5455 */ 5456 public int getMarginStart() { 5457 return startMargin; 5458 } 5459 5460 /** 5461 * Returns the end margin in pixels. 5462 * 5463 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5464 * 5465 * @return the end margin in pixels. 5466 * 5467 * @hide 5468 */ 5469 public int getMarginEnd() { 5470 return endMargin; 5471 } 5472 5473 /** 5474 * Check if margins are relative. 5475 * 5476 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 5477 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 5478 * 5479 * @return true if either marginStart or marginEnd has been set 5480 * 5481 * @hide 5482 */ 5483 public boolean isMarginRelative() { 5484 return (startMargin != DEFAULT_RELATIVE) || (endMargin != DEFAULT_RELATIVE); 5485 } 5486 5487 /** 5488 * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins 5489 * maybe overriden depending on layout direction. 5490 * 5491 * @hide 5492 */ 5493 @Override 5494 protected void resolveWithDirection(int layoutDirection) { 5495 switch(layoutDirection) { 5496 case View.LAYOUT_DIRECTION_RTL: 5497 leftMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : leftMargin; 5498 rightMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : rightMargin; 5499 break; 5500 case View.LAYOUT_DIRECTION_LTR: 5501 default: 5502 leftMargin = (startMargin > DEFAULT_RELATIVE) ? startMargin : leftMargin; 5503 rightMargin = (endMargin > DEFAULT_RELATIVE) ? endMargin : rightMargin; 5504 break; 5505 } 5506 } 5507 } 5508 5509 /* Describes a touched view and the ids of the pointers that it has captured. 5510 * 5511 * This code assumes that pointer ids are always in the range 0..31 such that 5512 * it can use a bitfield to track which pointer ids are present. 5513 * As it happens, the lower layers of the input dispatch pipeline also use the 5514 * same trick so the assumption should be safe here... 5515 */ 5516 private static final class TouchTarget { 5517 private static final int MAX_RECYCLED = 32; 5518 private static final Object sRecycleLock = new Object(); 5519 private static TouchTarget sRecycleBin; 5520 private static int sRecycledCount; 5521 5522 public static final int ALL_POINTER_IDS = -1; // all ones 5523 5524 // The touched child view. 5525 public View child; 5526 5527 // The combined bit mask of pointer ids for all pointers captured by the target. 5528 public int pointerIdBits; 5529 5530 // The next target in the target list. 5531 public TouchTarget next; 5532 5533 private TouchTarget() { 5534 } 5535 5536 public static TouchTarget obtain(View child, int pointerIdBits) { 5537 final TouchTarget target; 5538 synchronized (sRecycleLock) { 5539 if (sRecycleBin == null) { 5540 target = new TouchTarget(); 5541 } else { 5542 target = sRecycleBin; 5543 sRecycleBin = target.next; 5544 sRecycledCount--; 5545 target.next = null; 5546 } 5547 } 5548 target.child = child; 5549 target.pointerIdBits = pointerIdBits; 5550 return target; 5551 } 5552 5553 public void recycle() { 5554 synchronized (sRecycleLock) { 5555 if (sRecycledCount < MAX_RECYCLED) { 5556 next = sRecycleBin; 5557 sRecycleBin = this; 5558 sRecycledCount += 1; 5559 } else { 5560 next = null; 5561 } 5562 child = null; 5563 } 5564 } 5565 } 5566 5567 /* Describes a hovered view. */ 5568 private static final class HoverTarget { 5569 private static final int MAX_RECYCLED = 32; 5570 private static final Object sRecycleLock = new Object(); 5571 private static HoverTarget sRecycleBin; 5572 private static int sRecycledCount; 5573 5574 // The hovered child view. 5575 public View child; 5576 5577 // The next target in the target list. 5578 public HoverTarget next; 5579 5580 private HoverTarget() { 5581 } 5582 5583 public static HoverTarget obtain(View child) { 5584 final HoverTarget target; 5585 synchronized (sRecycleLock) { 5586 if (sRecycleBin == null) { 5587 target = new HoverTarget(); 5588 } else { 5589 target = sRecycleBin; 5590 sRecycleBin = target.next; 5591 sRecycledCount--; 5592 target.next = null; 5593 } 5594 } 5595 target.child = child; 5596 return target; 5597 } 5598 5599 public void recycle() { 5600 synchronized (sRecycleLock) { 5601 if (sRecycledCount < MAX_RECYCLED) { 5602 next = sRecycleBin; 5603 sRecycleBin = this; 5604 sRecycledCount += 1; 5605 } else { 5606 next = null; 5607 } 5608 child = null; 5609 } 5610 } 5611 } 5612} 5613