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