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