ViewGroup.java revision 6f3a6a453ac55ac2974d32ead4615746594382c8
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 final Transformation mChildTransformation = new Transformation(); 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 lastHoverTarget = hoverTarget; 1521 mFirstHoverTarget = hoverTarget; 1522 } 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 /** 3215 * {@hide} 3216 */ 3217 @Override 3218 protected View findViewTraversal(int id) { 3219 if (id == mID) { 3220 return this; 3221 } 3222 3223 final View[] where = mChildren; 3224 final int len = mChildrenCount; 3225 3226 for (int i = 0; i < len; i++) { 3227 View v = where[i]; 3228 3229 if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) { 3230 v = v.findViewById(id); 3231 3232 if (v != null) { 3233 return v; 3234 } 3235 } 3236 } 3237 3238 return null; 3239 } 3240 3241 /** 3242 * {@hide} 3243 */ 3244 @Override 3245 protected View findViewWithTagTraversal(Object tag) { 3246 if (tag != null && tag.equals(mTag)) { 3247 return this; 3248 } 3249 3250 final View[] where = mChildren; 3251 final int len = mChildrenCount; 3252 3253 for (int i = 0; i < len; i++) { 3254 View v = where[i]; 3255 3256 if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) { 3257 v = v.findViewWithTag(tag); 3258 3259 if (v != null) { 3260 return v; 3261 } 3262 } 3263 } 3264 3265 return null; 3266 } 3267 3268 /** 3269 * {@hide} 3270 */ 3271 @Override 3272 protected View findViewByPredicateTraversal(Predicate<View> predicate, View childToSkip) { 3273 if (predicate.apply(this)) { 3274 return this; 3275 } 3276 3277 final View[] where = mChildren; 3278 final int len = mChildrenCount; 3279 3280 for (int i = 0; i < len; i++) { 3281 View v = where[i]; 3282 3283 if (v != childToSkip && (v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) { 3284 v = v.findViewByPredicate(predicate); 3285 3286 if (v != null) { 3287 return v; 3288 } 3289 } 3290 } 3291 3292 return null; 3293 } 3294 3295 /** 3296 * <p>Adds a child view. If no layout parameters are already set on the child, the 3297 * default parameters for this ViewGroup are set on the child.</p> 3298 * 3299 * <p><strong>Note:</strong> do not invoke this method from 3300 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3301 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3302 * 3303 * @param child the child view to add 3304 * 3305 * @see #generateDefaultLayoutParams() 3306 */ 3307 public void addView(View child) { 3308 addView(child, -1); 3309 } 3310 3311 /** 3312 * Adds a child view. If no layout parameters are already set on the child, the 3313 * default parameters for this ViewGroup are set on the child. 3314 * 3315 * <p><strong>Note:</strong> do not invoke this method from 3316 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3317 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3318 * 3319 * @param child the child view to add 3320 * @param index the position at which to add the child 3321 * 3322 * @see #generateDefaultLayoutParams() 3323 */ 3324 public void addView(View child, int index) { 3325 LayoutParams params = child.getLayoutParams(); 3326 if (params == null) { 3327 params = generateDefaultLayoutParams(); 3328 if (params == null) { 3329 throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null"); 3330 } 3331 } 3332 addView(child, index, params); 3333 } 3334 3335 /** 3336 * Adds a child view with this ViewGroup's default layout parameters and the 3337 * specified width and height. 3338 * 3339 * <p><strong>Note:</strong> do not invoke this method from 3340 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3341 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3342 * 3343 * @param child the child view to add 3344 */ 3345 public void addView(View child, int width, int height) { 3346 final LayoutParams params = generateDefaultLayoutParams(); 3347 params.width = width; 3348 params.height = height; 3349 addView(child, -1, params); 3350 } 3351 3352 /** 3353 * Adds a child view with the specified layout parameters. 3354 * 3355 * <p><strong>Note:</strong> do not invoke this method from 3356 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3357 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3358 * 3359 * @param child the child view to add 3360 * @param params the layout parameters to set on the child 3361 */ 3362 public void addView(View child, LayoutParams params) { 3363 addView(child, -1, params); 3364 } 3365 3366 /** 3367 * Adds a child view with the specified layout parameters. 3368 * 3369 * <p><strong>Note:</strong> do not invoke this method from 3370 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3371 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3372 * 3373 * @param child the child view to add 3374 * @param index the position at which to add the child 3375 * @param params the layout parameters to set on the child 3376 */ 3377 public void addView(View child, int index, LayoutParams params) { 3378 if (DBG) { 3379 System.out.println(this + " addView"); 3380 } 3381 3382 // addViewInner() will call child.requestLayout() when setting the new LayoutParams 3383 // therefore, we call requestLayout() on ourselves before, so that the child's request 3384 // will be blocked at our level 3385 requestLayout(); 3386 invalidate(true); 3387 addViewInner(child, index, params, false); 3388 } 3389 3390 /** 3391 * {@inheritDoc} 3392 */ 3393 public void updateViewLayout(View view, ViewGroup.LayoutParams params) { 3394 if (!checkLayoutParams(params)) { 3395 throw new IllegalArgumentException("Invalid LayoutParams supplied to " + this); 3396 } 3397 if (view.mParent != this) { 3398 throw new IllegalArgumentException("Given view not a child of " + this); 3399 } 3400 view.setLayoutParams(params); 3401 } 3402 3403 /** 3404 * {@inheritDoc} 3405 */ 3406 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 3407 return p != null; 3408 } 3409 3410 /** 3411 * Interface definition for a callback to be invoked when the hierarchy 3412 * within this view changed. The hierarchy changes whenever a child is added 3413 * to or removed from this view. 3414 */ 3415 public interface OnHierarchyChangeListener { 3416 /** 3417 * Called when a new child is added to a parent view. 3418 * 3419 * @param parent the view in which a child was added 3420 * @param child the new child view added in the hierarchy 3421 */ 3422 void onChildViewAdded(View parent, View child); 3423 3424 /** 3425 * Called when a child is removed from a parent view. 3426 * 3427 * @param parent the view from which the child was removed 3428 * @param child the child removed from the hierarchy 3429 */ 3430 void onChildViewRemoved(View parent, View child); 3431 } 3432 3433 /** 3434 * Register a callback to be invoked when a child is added to or removed 3435 * from this view. 3436 * 3437 * @param listener the callback to invoke on hierarchy change 3438 */ 3439 public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) { 3440 mOnHierarchyChangeListener = listener; 3441 } 3442 3443 /** 3444 * @hide 3445 */ 3446 protected void onViewAdded(View child) { 3447 if (mOnHierarchyChangeListener != null) { 3448 mOnHierarchyChangeListener.onChildViewAdded(this, child); 3449 } 3450 } 3451 3452 /** 3453 * @hide 3454 */ 3455 protected void onViewRemoved(View child) { 3456 if (mOnHierarchyChangeListener != null) { 3457 mOnHierarchyChangeListener.onChildViewRemoved(this, child); 3458 } 3459 } 3460 3461 private void clearCachedLayoutMode() { 3462 if (!getBooleanFlag(FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET)) { 3463 mLayoutMode = LAYOUT_MODE_UNDEFINED; 3464 } 3465 } 3466 3467 @Override 3468 protected void onAttachedToWindow() { 3469 super.onAttachedToWindow(); 3470 clearCachedLayoutMode(); 3471 } 3472 3473 @Override 3474 protected void onDetachedFromWindow() { 3475 super.onDetachedFromWindow(); 3476 clearCachedLayoutMode(); 3477 } 3478 3479 /** 3480 * Adds a view during layout. This is useful if in your onLayout() method, 3481 * you need to add more views (as does the list view for example). 3482 * 3483 * If index is negative, it means put it at the end of the list. 3484 * 3485 * @param child the view to add to the group 3486 * @param index the index at which the child must be added 3487 * @param params the layout parameters to associate with the child 3488 * @return true if the child was added, false otherwise 3489 */ 3490 protected boolean addViewInLayout(View child, int index, LayoutParams params) { 3491 return addViewInLayout(child, index, params, false); 3492 } 3493 3494 /** 3495 * Adds a view during layout. This is useful if in your onLayout() method, 3496 * you need to add more views (as does the list view for example). 3497 * 3498 * If index is negative, it means put it at the end of the list. 3499 * 3500 * @param child the view to add to the group 3501 * @param index the index at which the child must be added 3502 * @param params the layout parameters to associate with the child 3503 * @param preventRequestLayout if true, calling this method will not trigger a 3504 * layout request on child 3505 * @return true if the child was added, false otherwise 3506 */ 3507 protected boolean addViewInLayout(View child, int index, LayoutParams params, 3508 boolean preventRequestLayout) { 3509 child.mParent = null; 3510 addViewInner(child, index, params, preventRequestLayout); 3511 child.mPrivateFlags = (child.mPrivateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN; 3512 return true; 3513 } 3514 3515 /** 3516 * Prevents the specified child to be laid out during the next layout pass. 3517 * 3518 * @param child the child on which to perform the cleanup 3519 */ 3520 protected void cleanupLayoutState(View child) { 3521 child.mPrivateFlags &= ~View.PFLAG_FORCE_LAYOUT; 3522 } 3523 3524 private void addViewInner(View child, int index, LayoutParams params, 3525 boolean preventRequestLayout) { 3526 3527 if (mTransition != null) { 3528 // Don't prevent other add transitions from completing, but cancel remove 3529 // transitions to let them complete the process before we add to the container 3530 mTransition.cancel(LayoutTransition.DISAPPEARING); 3531 } 3532 3533 if (child.getParent() != null) { 3534 throw new IllegalStateException("The specified child already has a parent. " + 3535 "You must call removeView() on the child's parent first."); 3536 } 3537 3538 if (mTransition != null) { 3539 mTransition.addChild(this, child); 3540 } 3541 3542 if (!checkLayoutParams(params)) { 3543 params = generateLayoutParams(params); 3544 } 3545 3546 if (preventRequestLayout) { 3547 child.mLayoutParams = params; 3548 } else { 3549 child.setLayoutParams(params); 3550 } 3551 3552 if (index < 0) { 3553 index = mChildrenCount; 3554 } 3555 3556 addInArray(child, index); 3557 3558 // tell our children 3559 if (preventRequestLayout) { 3560 child.assignParent(this); 3561 } else { 3562 child.mParent = this; 3563 } 3564 3565 if (child.hasFocus()) { 3566 requestChildFocus(child, child.findFocus()); 3567 } 3568 3569 AttachInfo ai = mAttachInfo; 3570 if (ai != null && (mGroupFlags & FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW) == 0) { 3571 boolean lastKeepOn = ai.mKeepScreenOn; 3572 ai.mKeepScreenOn = false; 3573 child.dispatchAttachedToWindow(mAttachInfo, (mViewFlags&VISIBILITY_MASK)); 3574 if (ai.mKeepScreenOn) { 3575 needGlobalAttributesUpdate(true); 3576 } 3577 ai.mKeepScreenOn = lastKeepOn; 3578 } 3579 3580 if (child.isLayoutDirectionInherited()) { 3581 child.resetRtlProperties(); 3582 } 3583 3584 onViewAdded(child); 3585 3586 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) == DUPLICATE_PARENT_STATE) { 3587 mGroupFlags |= FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE; 3588 } 3589 3590 if (child.hasTransientState()) { 3591 childHasTransientStateChanged(child, true); 3592 } 3593 } 3594 3595 private void addInArray(View child, int index) { 3596 View[] children = mChildren; 3597 final int count = mChildrenCount; 3598 final int size = children.length; 3599 if (index == count) { 3600 if (size == count) { 3601 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 3602 System.arraycopy(children, 0, mChildren, 0, size); 3603 children = mChildren; 3604 } 3605 children[mChildrenCount++] = child; 3606 } else if (index < count) { 3607 if (size == count) { 3608 mChildren = new View[size + ARRAY_CAPACITY_INCREMENT]; 3609 System.arraycopy(children, 0, mChildren, 0, index); 3610 System.arraycopy(children, index, mChildren, index + 1, count - index); 3611 children = mChildren; 3612 } else { 3613 System.arraycopy(children, index, children, index + 1, count - index); 3614 } 3615 children[index] = child; 3616 mChildrenCount++; 3617 if (mLastTouchDownIndex >= index) { 3618 mLastTouchDownIndex++; 3619 } 3620 } else { 3621 throw new IndexOutOfBoundsException("index=" + index + " count=" + count); 3622 } 3623 } 3624 3625 // This method also sets the child's mParent to null 3626 private void removeFromArray(int index) { 3627 final View[] children = mChildren; 3628 if (!(mTransitioningViews != null && mTransitioningViews.contains(children[index]))) { 3629 children[index].mParent = null; 3630 } 3631 final int count = mChildrenCount; 3632 if (index == count - 1) { 3633 children[--mChildrenCount] = null; 3634 } else if (index >= 0 && index < count) { 3635 System.arraycopy(children, index + 1, children, index, count - index - 1); 3636 children[--mChildrenCount] = null; 3637 } else { 3638 throw new IndexOutOfBoundsException(); 3639 } 3640 if (mLastTouchDownIndex == index) { 3641 mLastTouchDownTime = 0; 3642 mLastTouchDownIndex = -1; 3643 } else if (mLastTouchDownIndex > index) { 3644 mLastTouchDownIndex--; 3645 } 3646 } 3647 3648 // This method also sets the children's mParent to null 3649 private void removeFromArray(int start, int count) { 3650 final View[] children = mChildren; 3651 final int childrenCount = mChildrenCount; 3652 3653 start = Math.max(0, start); 3654 final int end = Math.min(childrenCount, start + count); 3655 3656 if (start == end) { 3657 return; 3658 } 3659 3660 if (end == childrenCount) { 3661 for (int i = start; i < end; i++) { 3662 children[i].mParent = null; 3663 children[i] = null; 3664 } 3665 } else { 3666 for (int i = start; i < end; i++) { 3667 children[i].mParent = null; 3668 } 3669 3670 // Since we're looping above, we might as well do the copy, but is arraycopy() 3671 // faster than the extra 2 bounds checks we would do in the loop? 3672 System.arraycopy(children, end, children, start, childrenCount - end); 3673 3674 for (int i = childrenCount - (end - start); i < childrenCount; i++) { 3675 children[i] = null; 3676 } 3677 } 3678 3679 mChildrenCount -= (end - start); 3680 } 3681 3682 private void bindLayoutAnimation(View child) { 3683 Animation a = mLayoutAnimationController.getAnimationForView(child); 3684 child.setAnimation(a); 3685 } 3686 3687 /** 3688 * Subclasses should override this method to set layout animation 3689 * parameters on the supplied child. 3690 * 3691 * @param child the child to associate with animation parameters 3692 * @param params the child's layout parameters which hold the animation 3693 * parameters 3694 * @param index the index of the child in the view group 3695 * @param count the number of children in the view group 3696 */ 3697 protected void attachLayoutAnimationParameters(View child, 3698 LayoutParams params, int index, int count) { 3699 LayoutAnimationController.AnimationParameters animationParams = 3700 params.layoutAnimationParameters; 3701 if (animationParams == null) { 3702 animationParams = new LayoutAnimationController.AnimationParameters(); 3703 params.layoutAnimationParameters = animationParams; 3704 } 3705 3706 animationParams.count = count; 3707 animationParams.index = index; 3708 } 3709 3710 /** 3711 * {@inheritDoc} 3712 * 3713 * <p><strong>Note:</strong> do not invoke this method from 3714 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3715 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3716 */ 3717 public void removeView(View view) { 3718 removeViewInternal(view); 3719 requestLayout(); 3720 invalidate(true); 3721 } 3722 3723 /** 3724 * Removes a view during layout. This is useful if in your onLayout() method, 3725 * you need to remove more views. 3726 * 3727 * <p><strong>Note:</strong> do not invoke this method from 3728 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3729 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3730 * 3731 * @param view the view to remove from the group 3732 */ 3733 public void removeViewInLayout(View view) { 3734 removeViewInternal(view); 3735 } 3736 3737 /** 3738 * Removes a range of views during layout. This is useful if in your onLayout() method, 3739 * you need to remove more views. 3740 * 3741 * <p><strong>Note:</strong> do not invoke this method from 3742 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3743 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3744 * 3745 * @param start the index of the first view to remove from the group 3746 * @param count the number of views to remove from the group 3747 */ 3748 public void removeViewsInLayout(int start, int count) { 3749 removeViewsInternal(start, count); 3750 } 3751 3752 /** 3753 * Removes the view at the specified position in the group. 3754 * 3755 * <p><strong>Note:</strong> do not invoke this method from 3756 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3757 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3758 * 3759 * @param index the position in the group of the view to remove 3760 */ 3761 public void removeViewAt(int index) { 3762 removeViewInternal(index, getChildAt(index)); 3763 requestLayout(); 3764 invalidate(true); 3765 } 3766 3767 /** 3768 * Removes the specified range of views from the group. 3769 * 3770 * <p><strong>Note:</strong> do not invoke this method from 3771 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3772 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3773 * 3774 * @param start the first position in the group of the range of views to remove 3775 * @param count the number of views to remove 3776 */ 3777 public void removeViews(int start, int count) { 3778 removeViewsInternal(start, count); 3779 requestLayout(); 3780 invalidate(true); 3781 } 3782 3783 private void removeViewInternal(View view) { 3784 final int index = indexOfChild(view); 3785 if (index >= 0) { 3786 removeViewInternal(index, view); 3787 } 3788 } 3789 3790 private void removeViewInternal(int index, View view) { 3791 3792 if (mTransition != null) { 3793 mTransition.removeChild(this, view); 3794 } 3795 3796 boolean clearChildFocus = false; 3797 if (view == mFocused) { 3798 view.unFocus(); 3799 clearChildFocus = true; 3800 } 3801 3802 if (view.isAccessibilityFocused()) { 3803 view.clearAccessibilityFocus(); 3804 } 3805 3806 cancelTouchTarget(view); 3807 cancelHoverTarget(view); 3808 3809 if (view.getAnimation() != null || 3810 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3811 addDisappearingView(view); 3812 } else if (view.mAttachInfo != null) { 3813 view.dispatchDetachedFromWindow(); 3814 } 3815 3816 if (view.hasTransientState()) { 3817 childHasTransientStateChanged(view, false); 3818 } 3819 3820 needGlobalAttributesUpdate(false); 3821 3822 removeFromArray(index); 3823 3824 if (clearChildFocus) { 3825 clearChildFocus(view); 3826 if (!rootViewRequestFocus()) { 3827 notifyGlobalFocusCleared(this); 3828 } 3829 } 3830 3831 onViewRemoved(view); 3832 } 3833 3834 /** 3835 * Sets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3836 * not null, changes in layout which occur because of children being added to or removed from 3837 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3838 * object. By default, the transition object is null (so layout changes are not animated). 3839 * 3840 * @param transition The LayoutTransition object that will animated changes in layout. A value 3841 * of <code>null</code> means no transition will run on layout changes. 3842 * @attr ref android.R.styleable#ViewGroup_animateLayoutChanges 3843 */ 3844 public void setLayoutTransition(LayoutTransition transition) { 3845 if (mTransition != null) { 3846 mTransition.removeTransitionListener(mLayoutTransitionListener); 3847 } 3848 mTransition = transition; 3849 if (mTransition != null) { 3850 mTransition.addTransitionListener(mLayoutTransitionListener); 3851 } 3852 } 3853 3854 /** 3855 * Gets the LayoutTransition object for this ViewGroup. If the LayoutTransition object is 3856 * not null, changes in layout which occur because of children being added to or removed from 3857 * the ViewGroup will be animated according to the animations defined in that LayoutTransition 3858 * object. By default, the transition object is null (so layout changes are not animated). 3859 * 3860 * @return LayoutTranstion The LayoutTransition object that will animated changes in layout. 3861 * A value of <code>null</code> means no transition will run on layout changes. 3862 */ 3863 public LayoutTransition getLayoutTransition() { 3864 return mTransition; 3865 } 3866 3867 private void removeViewsInternal(int start, int count) { 3868 final View focused = mFocused; 3869 final boolean detach = mAttachInfo != null; 3870 boolean clearChildFocus = false; 3871 3872 final View[] children = mChildren; 3873 final int end = start + count; 3874 3875 for (int i = start; i < end; i++) { 3876 final View view = children[i]; 3877 3878 if (mTransition != null) { 3879 mTransition.removeChild(this, view); 3880 } 3881 3882 if (view == focused) { 3883 view.unFocus(); 3884 clearChildFocus = true; 3885 } 3886 3887 if (view.isAccessibilityFocused()) { 3888 view.clearAccessibilityFocus(); 3889 } 3890 3891 cancelTouchTarget(view); 3892 cancelHoverTarget(view); 3893 3894 if (view.getAnimation() != null || 3895 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3896 addDisappearingView(view); 3897 } else if (detach) { 3898 view.dispatchDetachedFromWindow(); 3899 } 3900 3901 if (view.hasTransientState()) { 3902 childHasTransientStateChanged(view, false); 3903 } 3904 3905 needGlobalAttributesUpdate(false); 3906 3907 onViewRemoved(view); 3908 } 3909 3910 removeFromArray(start, count); 3911 3912 if (clearChildFocus) { 3913 clearChildFocus(focused); 3914 if (!rootViewRequestFocus()) { 3915 notifyGlobalFocusCleared(focused); 3916 } 3917 } 3918 } 3919 3920 /** 3921 * Call this method to remove all child views from the 3922 * ViewGroup. 3923 * 3924 * <p><strong>Note:</strong> do not invoke this method from 3925 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3926 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3927 */ 3928 public void removeAllViews() { 3929 removeAllViewsInLayout(); 3930 requestLayout(); 3931 invalidate(true); 3932 } 3933 3934 /** 3935 * Called by a ViewGroup subclass to remove child views from itself, 3936 * when it must first know its size on screen before it can calculate how many 3937 * child views it will render. An example is a Gallery or a ListView, which 3938 * may "have" 50 children, but actually only render the number of children 3939 * that can currently fit inside the object on screen. Do not call 3940 * this method unless you are extending ViewGroup and understand the 3941 * view measuring and layout pipeline. 3942 * 3943 * <p><strong>Note:</strong> do not invoke this method from 3944 * {@link #draw(android.graphics.Canvas)}, {@link #onDraw(android.graphics.Canvas)}, 3945 * {@link #dispatchDraw(android.graphics.Canvas)} or any related method.</p> 3946 */ 3947 public void removeAllViewsInLayout() { 3948 final int count = mChildrenCount; 3949 if (count <= 0) { 3950 return; 3951 } 3952 3953 final View[] children = mChildren; 3954 mChildrenCount = 0; 3955 3956 final View focused = mFocused; 3957 final boolean detach = mAttachInfo != null; 3958 boolean clearChildFocus = false; 3959 3960 needGlobalAttributesUpdate(false); 3961 3962 for (int i = count - 1; i >= 0; i--) { 3963 final View view = children[i]; 3964 3965 if (mTransition != null) { 3966 mTransition.removeChild(this, view); 3967 } 3968 3969 if (view == focused) { 3970 view.unFocus(); 3971 clearChildFocus = true; 3972 } 3973 3974 if (view.isAccessibilityFocused()) { 3975 view.clearAccessibilityFocus(); 3976 } 3977 3978 cancelTouchTarget(view); 3979 cancelHoverTarget(view); 3980 3981 if (view.getAnimation() != null || 3982 (mTransitioningViews != null && mTransitioningViews.contains(view))) { 3983 addDisappearingView(view); 3984 } else if (detach) { 3985 view.dispatchDetachedFromWindow(); 3986 } 3987 3988 if (view.hasTransientState()) { 3989 childHasTransientStateChanged(view, false); 3990 } 3991 3992 onViewRemoved(view); 3993 3994 view.mParent = null; 3995 children[i] = null; 3996 } 3997 3998 if (clearChildFocus) { 3999 clearChildFocus(focused); 4000 if (!rootViewRequestFocus()) { 4001 notifyGlobalFocusCleared(focused); 4002 } 4003 } 4004 } 4005 4006 /** 4007 * Finishes the removal of a detached view. This method will dispatch the detached from 4008 * window event and notify the hierarchy change listener. 4009 * <p> 4010 * This method is intended to be lightweight and makes no assumptions about whether the 4011 * parent or child should be redrawn. Proper use of this method will include also making 4012 * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls. 4013 * For example, callers can {@link #post(Runnable) post} a {@link Runnable} 4014 * which performs a {@link #requestLayout()} on the next frame, after all detach/remove 4015 * calls are finished, causing layout to be run prior to redrawing the view hierarchy. 4016 * 4017 * @param child the child to be definitely removed from the view hierarchy 4018 * @param animate if true and the view has an animation, the view is placed in the 4019 * disappearing views list, otherwise, it is detached from the window 4020 * 4021 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 4022 * @see #detachAllViewsFromParent() 4023 * @see #detachViewFromParent(View) 4024 * @see #detachViewFromParent(int) 4025 */ 4026 protected void removeDetachedView(View child, boolean animate) { 4027 if (mTransition != null) { 4028 mTransition.removeChild(this, child); 4029 } 4030 4031 if (child == mFocused) { 4032 child.clearFocus(); 4033 } 4034 4035 child.clearAccessibilityFocus(); 4036 4037 cancelTouchTarget(child); 4038 cancelHoverTarget(child); 4039 4040 if ((animate && child.getAnimation() != null) || 4041 (mTransitioningViews != null && mTransitioningViews.contains(child))) { 4042 addDisappearingView(child); 4043 } else if (child.mAttachInfo != null) { 4044 child.dispatchDetachedFromWindow(); 4045 } 4046 4047 if (child.hasTransientState()) { 4048 childHasTransientStateChanged(child, false); 4049 } 4050 4051 onViewRemoved(child); 4052 } 4053 4054 /** 4055 * Attaches a view to this view group. Attaching a view assigns this group as the parent, 4056 * sets the layout parameters and puts the view in the list of children so that 4057 * it can be retrieved by calling {@link #getChildAt(int)}. 4058 * <p> 4059 * This method is intended to be lightweight and makes no assumptions about whether the 4060 * parent or child should be redrawn. Proper use of this method will include also making 4061 * any appropriate {@link #requestLayout()} or {@link #invalidate()} calls. 4062 * For example, callers can {@link #post(Runnable) post} a {@link Runnable} 4063 * which performs a {@link #requestLayout()} on the next frame, after all detach/attach 4064 * calls are finished, causing layout to be run prior to redrawing the view hierarchy. 4065 * <p> 4066 * This method should be called only for views which were detached from their parent. 4067 * 4068 * @param child the child to attach 4069 * @param index the index at which the child should be attached 4070 * @param params the layout parameters of the child 4071 * 4072 * @see #removeDetachedView(View, boolean) 4073 * @see #detachAllViewsFromParent() 4074 * @see #detachViewFromParent(View) 4075 * @see #detachViewFromParent(int) 4076 */ 4077 protected void attachViewToParent(View child, int index, LayoutParams params) { 4078 child.mLayoutParams = params; 4079 4080 if (index < 0) { 4081 index = mChildrenCount; 4082 } 4083 4084 addInArray(child, index); 4085 4086 child.mParent = this; 4087 child.mPrivateFlags = (child.mPrivateFlags & ~PFLAG_DIRTY_MASK 4088 & ~PFLAG_DRAWING_CACHE_VALID) 4089 | PFLAG_DRAWN | PFLAG_INVALIDATED; 4090 this.mPrivateFlags |= PFLAG_INVALIDATED; 4091 4092 if (child.hasFocus()) { 4093 requestChildFocus(child, child.findFocus()); 4094 } 4095 } 4096 4097 /** 4098 * Detaches a view from its parent. Detaching a view should be followed 4099 * either by a call to 4100 * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 4101 * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be 4102 * temporary; reattachment or removal should happen within the same drawing cycle as 4103 * detachment. When a view is detached, its parent is null and cannot be retrieved by a 4104 * call to {@link #getChildAt(int)}. 4105 * 4106 * @param child the child to detach 4107 * 4108 * @see #detachViewFromParent(int) 4109 * @see #detachViewsFromParent(int, int) 4110 * @see #detachAllViewsFromParent() 4111 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 4112 * @see #removeDetachedView(View, boolean) 4113 */ 4114 protected void detachViewFromParent(View child) { 4115 removeFromArray(indexOfChild(child)); 4116 } 4117 4118 /** 4119 * Detaches a view from its parent. Detaching a view should be followed 4120 * either by a call to 4121 * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 4122 * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be 4123 * temporary; reattachment or removal should happen within the same drawing cycle as 4124 * detachment. When a view is detached, its parent is null and cannot be retrieved by a 4125 * call to {@link #getChildAt(int)}. 4126 * 4127 * @param index the index of the child to detach 4128 * 4129 * @see #detachViewFromParent(View) 4130 * @see #detachAllViewsFromParent() 4131 * @see #detachViewsFromParent(int, int) 4132 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 4133 * @see #removeDetachedView(View, boolean) 4134 */ 4135 protected void detachViewFromParent(int index) { 4136 removeFromArray(index); 4137 } 4138 4139 /** 4140 * Detaches a range of views from their parents. Detaching a view should be followed 4141 * either by a call to 4142 * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 4143 * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be 4144 * temporary; reattachment or removal should happen within the same drawing cycle as 4145 * detachment. When a view is detached, its parent is null and cannot be retrieved by a 4146 * call to {@link #getChildAt(int)}. 4147 * 4148 * @param start the first index of the childrend range to detach 4149 * @param count the number of children to detach 4150 * 4151 * @see #detachViewFromParent(View) 4152 * @see #detachViewFromParent(int) 4153 * @see #detachAllViewsFromParent() 4154 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 4155 * @see #removeDetachedView(View, boolean) 4156 */ 4157 protected void detachViewsFromParent(int start, int count) { 4158 removeFromArray(start, count); 4159 } 4160 4161 /** 4162 * Detaches all views from the parent. Detaching a view should be followed 4163 * either by a call to 4164 * {@link #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams)} 4165 * or a call to {@link #removeDetachedView(View, boolean)}. Detachment should only be 4166 * temporary; reattachment or removal should happen within the same drawing cycle as 4167 * detachment. When a view is detached, its parent is null and cannot be retrieved by a 4168 * call to {@link #getChildAt(int)}. 4169 * 4170 * @see #detachViewFromParent(View) 4171 * @see #detachViewFromParent(int) 4172 * @see #detachViewsFromParent(int, int) 4173 * @see #attachViewToParent(View, int, android.view.ViewGroup.LayoutParams) 4174 * @see #removeDetachedView(View, boolean) 4175 */ 4176 protected void detachAllViewsFromParent() { 4177 final int count = mChildrenCount; 4178 if (count <= 0) { 4179 return; 4180 } 4181 4182 final View[] children = mChildren; 4183 mChildrenCount = 0; 4184 4185 for (int i = count - 1; i >= 0; i--) { 4186 children[i].mParent = null; 4187 children[i] = null; 4188 } 4189 } 4190 4191 /** 4192 * Don't call or override this method. It is used for the implementation of 4193 * the view hierarchy. 4194 */ 4195 public final void invalidateChild(View child, final Rect dirty) { 4196 ViewParent parent = this; 4197 4198 final AttachInfo attachInfo = mAttachInfo; 4199 if (attachInfo != null) { 4200 // If the child is drawing an animation, we want to copy this flag onto 4201 // ourselves and the parent to make sure the invalidate request goes 4202 // through 4203 final boolean drawAnimation = (child.mPrivateFlags & PFLAG_DRAW_ANIMATION) 4204 == PFLAG_DRAW_ANIMATION; 4205 4206 // Check whether the child that requests the invalidate is fully opaque 4207 // Views being animated or transformed are not considered opaque because we may 4208 // be invalidating their old position and need the parent to paint behind them. 4209 Matrix childMatrix = child.getMatrix(); 4210 final boolean isOpaque = child.isOpaque() && !drawAnimation && 4211 child.getAnimation() == null && childMatrix.isIdentity(); 4212 // Mark the child as dirty, using the appropriate flag 4213 // Make sure we do not set both flags at the same time 4214 int opaqueFlag = isOpaque ? PFLAG_DIRTY_OPAQUE : PFLAG_DIRTY; 4215 4216 if (child.mLayerType != LAYER_TYPE_NONE) { 4217 mPrivateFlags |= PFLAG_INVALIDATED; 4218 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 4219 child.mLocalDirtyRect.union(dirty); 4220 } 4221 4222 final int[] location = attachInfo.mInvalidateChildLocation; 4223 location[CHILD_LEFT_INDEX] = child.mLeft; 4224 location[CHILD_TOP_INDEX] = child.mTop; 4225 if (!childMatrix.isIdentity() || 4226 (mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 4227 RectF boundingRect = attachInfo.mTmpTransformRect; 4228 boundingRect.set(dirty); 4229 Matrix transformMatrix; 4230 if ((mGroupFlags & ViewGroup.FLAG_SUPPORT_STATIC_TRANSFORMATIONS) != 0) { 4231 Transformation t = attachInfo.mTmpTransformation; 4232 boolean transformed = getChildStaticTransformation(child, t); 4233 if (transformed) { 4234 transformMatrix = attachInfo.mTmpMatrix; 4235 transformMatrix.set(t.getMatrix()); 4236 if (!childMatrix.isIdentity()) { 4237 transformMatrix.preConcat(childMatrix); 4238 } 4239 } else { 4240 transformMatrix = childMatrix; 4241 } 4242 } else { 4243 transformMatrix = childMatrix; 4244 } 4245 transformMatrix.mapRect(boundingRect); 4246 dirty.set((int) (boundingRect.left - 0.5f), 4247 (int) (boundingRect.top - 0.5f), 4248 (int) (boundingRect.right + 0.5f), 4249 (int) (boundingRect.bottom + 0.5f)); 4250 } 4251 4252 do { 4253 View view = null; 4254 if (parent instanceof View) { 4255 view = (View) parent; 4256 } 4257 4258 if (drawAnimation) { 4259 if (view != null) { 4260 view.mPrivateFlags |= PFLAG_DRAW_ANIMATION; 4261 } else if (parent instanceof ViewRootImpl) { 4262 ((ViewRootImpl) parent).mIsAnimating = true; 4263 } 4264 } 4265 4266 // If the parent is dirty opaque or not dirty, mark it dirty with the opaque 4267 // flag coming from the child that initiated the invalidate 4268 if (view != null) { 4269 if ((view.mViewFlags & FADING_EDGE_MASK) != 0 && 4270 view.getSolidColor() == 0) { 4271 opaqueFlag = PFLAG_DIRTY; 4272 } 4273 if ((view.mPrivateFlags & PFLAG_DIRTY_MASK) != PFLAG_DIRTY) { 4274 view.mPrivateFlags = (view.mPrivateFlags & ~PFLAG_DIRTY_MASK) | opaqueFlag; 4275 } 4276 } 4277 4278 parent = parent.invalidateChildInParent(location, dirty); 4279 if (view != null) { 4280 // Account for transform on current parent 4281 Matrix m = view.getMatrix(); 4282 if (!m.isIdentity()) { 4283 RectF boundingRect = attachInfo.mTmpTransformRect; 4284 boundingRect.set(dirty); 4285 m.mapRect(boundingRect); 4286 dirty.set((int) (boundingRect.left - 0.5f), 4287 (int) (boundingRect.top - 0.5f), 4288 (int) (boundingRect.right + 0.5f), 4289 (int) (boundingRect.bottom + 0.5f)); 4290 } 4291 } 4292 } while (parent != null); 4293 } 4294 } 4295 4296 /** 4297 * Don't call or override this method. It is used for the implementation of 4298 * the view hierarchy. 4299 * 4300 * This implementation returns null if this ViewGroup does not have a parent, 4301 * if this ViewGroup is already fully invalidated or if the dirty rectangle 4302 * does not intersect with this ViewGroup's bounds. 4303 */ 4304 public ViewParent invalidateChildInParent(final int[] location, final Rect dirty) { 4305 if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN || 4306 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) { 4307 if ((mGroupFlags & (FLAG_OPTIMIZE_INVALIDATE | FLAG_ANIMATION_DONE)) != 4308 FLAG_OPTIMIZE_INVALIDATE) { 4309 dirty.offset(location[CHILD_LEFT_INDEX] - mScrollX, 4310 location[CHILD_TOP_INDEX] - mScrollY); 4311 if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0) { 4312 dirty.union(0, 0, mRight - mLeft, mBottom - mTop); 4313 } 4314 4315 final int left = mLeft; 4316 final int top = mTop; 4317 4318 if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) { 4319 if (!dirty.intersect(0, 0, mRight - left, mBottom - top)) { 4320 dirty.setEmpty(); 4321 } 4322 } 4323 mPrivateFlags &= ~PFLAG_DRAWING_CACHE_VALID; 4324 4325 location[CHILD_LEFT_INDEX] = left; 4326 location[CHILD_TOP_INDEX] = top; 4327 4328 if (mLayerType != LAYER_TYPE_NONE) { 4329 mPrivateFlags |= PFLAG_INVALIDATED; 4330 mLocalDirtyRect.union(dirty); 4331 } 4332 4333 return mParent; 4334 4335 } else { 4336 mPrivateFlags &= ~PFLAG_DRAWN & ~PFLAG_DRAWING_CACHE_VALID; 4337 4338 location[CHILD_LEFT_INDEX] = mLeft; 4339 location[CHILD_TOP_INDEX] = mTop; 4340 if ((mGroupFlags & FLAG_CLIP_CHILDREN) == FLAG_CLIP_CHILDREN) { 4341 dirty.set(0, 0, mRight - mLeft, mBottom - mTop); 4342 } else { 4343 // in case the dirty rect extends outside the bounds of this container 4344 dirty.union(0, 0, mRight - mLeft, mBottom - mTop); 4345 } 4346 4347 if (mLayerType != LAYER_TYPE_NONE) { 4348 mPrivateFlags |= PFLAG_INVALIDATED; 4349 mLocalDirtyRect.union(dirty); 4350 } 4351 4352 return mParent; 4353 } 4354 } 4355 4356 return null; 4357 } 4358 4359 /** 4360 * Quick invalidation method called by View.invalidateViewProperty. This doesn't set the 4361 * DRAWN flags and doesn't handle the Animation logic that the default invalidation methods 4362 * do; all we want to do here is schedule a traversal with the appropriate dirty rect. 4363 * 4364 * @hide 4365 */ 4366 public void invalidateChildFast(View child, final Rect dirty) { 4367 ViewParent parent = this; 4368 4369 final AttachInfo attachInfo = mAttachInfo; 4370 if (attachInfo != null) { 4371 if (child.mLayerType != LAYER_TYPE_NONE) { 4372 child.mLocalDirtyRect.union(dirty); 4373 } 4374 4375 int left = child.mLeft; 4376 int top = child.mTop; 4377 if (!child.getMatrix().isIdentity()) { 4378 child.transformRect(dirty); 4379 } 4380 4381 do { 4382 if (parent instanceof ViewGroup) { 4383 ViewGroup parentVG = (ViewGroup) parent; 4384 if (parentVG.mLayerType != LAYER_TYPE_NONE) { 4385 // Layered parents should be recreated, not just re-issued 4386 parentVG.invalidate(); 4387 parent = null; 4388 } else { 4389 parent = parentVG.invalidateChildInParentFast(left, top, dirty); 4390 left = parentVG.mLeft; 4391 top = parentVG.mTop; 4392 } 4393 } else { 4394 // Reached the top; this calls into the usual invalidate method in 4395 // ViewRootImpl, which schedules a traversal 4396 final int[] location = attachInfo.mInvalidateChildLocation; 4397 location[0] = left; 4398 location[1] = top; 4399 parent = parent.invalidateChildInParent(location, dirty); 4400 } 4401 } while (parent != null); 4402 } 4403 } 4404 4405 /** 4406 * Quick invalidation method that simply transforms the dirty rect into the parent's 4407 * coordinate system, pruning the invalidation if the parent has already been invalidated. 4408 */ 4409 private ViewParent invalidateChildInParentFast(int left, int top, final Rect dirty) { 4410 if ((mPrivateFlags & PFLAG_DRAWN) == PFLAG_DRAWN || 4411 (mPrivateFlags & PFLAG_DRAWING_CACHE_VALID) == PFLAG_DRAWING_CACHE_VALID) { 4412 dirty.offset(left - mScrollX, top - mScrollY); 4413 if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0) { 4414 dirty.union(0, 0, mRight - mLeft, mBottom - mTop); 4415 } 4416 4417 if ((mGroupFlags & FLAG_CLIP_CHILDREN) == 0 || 4418 dirty.intersect(0, 0, mRight - mLeft, mBottom - mTop)) { 4419 4420 if (mLayerType != LAYER_TYPE_NONE) { 4421 mLocalDirtyRect.union(dirty); 4422 } 4423 if (!getMatrix().isIdentity()) { 4424 transformRect(dirty); 4425 } 4426 4427 return mParent; 4428 } 4429 } 4430 4431 return null; 4432 } 4433 4434 /** 4435 * Offset a rectangle that is in a descendant's coordinate 4436 * space into our coordinate space. 4437 * @param descendant A descendant of this view 4438 * @param rect A rectangle defined in descendant's coordinate space. 4439 */ 4440 public final void offsetDescendantRectToMyCoords(View descendant, Rect rect) { 4441 offsetRectBetweenParentAndChild(descendant, rect, true, false); 4442 } 4443 4444 /** 4445 * Offset a rectangle that is in our coordinate space into an ancestor's 4446 * coordinate space. 4447 * @param descendant A descendant of this view 4448 * @param rect A rectangle defined in descendant's coordinate space. 4449 */ 4450 public final void offsetRectIntoDescendantCoords(View descendant, Rect rect) { 4451 offsetRectBetweenParentAndChild(descendant, rect, false, false); 4452 } 4453 4454 /** 4455 * Helper method that offsets a rect either from parent to descendant or 4456 * descendant to parent. 4457 */ 4458 void offsetRectBetweenParentAndChild(View descendant, Rect rect, 4459 boolean offsetFromChildToParent, boolean clipToBounds) { 4460 4461 // already in the same coord system :) 4462 if (descendant == this) { 4463 return; 4464 } 4465 4466 ViewParent theParent = descendant.mParent; 4467 4468 // search and offset up to the parent 4469 while ((theParent != null) 4470 && (theParent instanceof View) 4471 && (theParent != this)) { 4472 4473 if (offsetFromChildToParent) { 4474 rect.offset(descendant.mLeft - descendant.mScrollX, 4475 descendant.mTop - descendant.mScrollY); 4476 if (clipToBounds) { 4477 View p = (View) theParent; 4478 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 4479 } 4480 } else { 4481 if (clipToBounds) { 4482 View p = (View) theParent; 4483 rect.intersect(0, 0, p.mRight - p.mLeft, p.mBottom - p.mTop); 4484 } 4485 rect.offset(descendant.mScrollX - descendant.mLeft, 4486 descendant.mScrollY - descendant.mTop); 4487 } 4488 4489 descendant = (View) theParent; 4490 theParent = descendant.mParent; 4491 } 4492 4493 // now that we are up to this view, need to offset one more time 4494 // to get into our coordinate space 4495 if (theParent == this) { 4496 if (offsetFromChildToParent) { 4497 rect.offset(descendant.mLeft - descendant.mScrollX, 4498 descendant.mTop - descendant.mScrollY); 4499 } else { 4500 rect.offset(descendant.mScrollX - descendant.mLeft, 4501 descendant.mScrollY - descendant.mTop); 4502 } 4503 } else { 4504 throw new IllegalArgumentException("parameter must be a descendant of this view"); 4505 } 4506 } 4507 4508 /** 4509 * Offset the vertical location of all children of this view by the specified number of pixels. 4510 * 4511 * @param offset the number of pixels to offset 4512 * 4513 * @hide 4514 */ 4515 public void offsetChildrenTopAndBottom(int offset) { 4516 final int count = mChildrenCount; 4517 final View[] children = mChildren; 4518 boolean invalidate = false; 4519 4520 for (int i = 0; i < count; i++) { 4521 final View v = children[i]; 4522 v.mTop += offset; 4523 v.mBottom += offset; 4524 if (v.mDisplayList != null) { 4525 invalidate = true; 4526 v.mDisplayList.offsetTopAndBottom(offset); 4527 } 4528 } 4529 4530 if (invalidate) { 4531 invalidateViewProperty(false, false); 4532 } 4533 } 4534 4535 /** 4536 * {@inheritDoc} 4537 */ 4538 public boolean getChildVisibleRect(View child, Rect r, android.graphics.Point offset) { 4539 // It doesn't make a whole lot of sense to call this on a view that isn't attached, 4540 // but for some simple tests it can be useful. If we don't have attach info this 4541 // will allocate memory. 4542 final RectF rect = mAttachInfo != null ? mAttachInfo.mTmpTransformRect : new RectF(); 4543 rect.set(r); 4544 4545 if (!child.hasIdentityMatrix()) { 4546 child.getMatrix().mapRect(rect); 4547 } 4548 4549 int dx = child.mLeft - mScrollX; 4550 int dy = child.mTop - mScrollY; 4551 4552 rect.offset(dx, dy); 4553 4554 if (offset != null) { 4555 if (!child.hasIdentityMatrix()) { 4556 float[] position = mAttachInfo != null ? mAttachInfo.mTmpTransformLocation 4557 : new float[2]; 4558 position[0] = offset.x; 4559 position[1] = offset.y; 4560 child.getMatrix().mapPoints(position); 4561 offset.x = (int) (position[0] + 0.5f); 4562 offset.y = (int) (position[1] + 0.5f); 4563 } 4564 offset.x += dx; 4565 offset.y += dy; 4566 } 4567 4568 if (rect.intersect(0, 0, mRight - mLeft, mBottom - mTop)) { 4569 if (mParent == null) return true; 4570 r.set((int) (rect.left + 0.5f), (int) (rect.top + 0.5f), 4571 (int) (rect.right + 0.5f), (int) (rect.bottom + 0.5f)); 4572 return mParent.getChildVisibleRect(this, r, offset); 4573 } 4574 4575 return false; 4576 } 4577 4578 /** 4579 * {@inheritDoc} 4580 */ 4581 @Override 4582 public final void layout(int l, int t, int r, int b) { 4583 if (!mSuppressLayout && (mTransition == null || !mTransition.isChangingLayout())) { 4584 if (mTransition != null) { 4585 mTransition.layoutChange(this); 4586 } 4587 super.layout(l, t, r, b); 4588 } else { 4589 // record the fact that we noop'd it; request layout when transition finishes 4590 mLayoutCalledWhileSuppressed = true; 4591 } 4592 } 4593 4594 /** 4595 * {@inheritDoc} 4596 */ 4597 @Override 4598 protected abstract void onLayout(boolean changed, 4599 int l, int t, int r, int b); 4600 4601 /** 4602 * Indicates whether the view group has the ability to animate its children 4603 * after the first layout. 4604 * 4605 * @return true if the children can be animated, false otherwise 4606 */ 4607 protected boolean canAnimate() { 4608 return mLayoutAnimationController != null; 4609 } 4610 4611 /** 4612 * Runs the layout animation. Calling this method triggers a relayout of 4613 * this view group. 4614 */ 4615 public void startLayoutAnimation() { 4616 if (mLayoutAnimationController != null) { 4617 mGroupFlags |= FLAG_RUN_ANIMATION; 4618 requestLayout(); 4619 } 4620 } 4621 4622 /** 4623 * Schedules the layout animation to be played after the next layout pass 4624 * of this view group. This can be used to restart the layout animation 4625 * when the content of the view group changes or when the activity is 4626 * paused and resumed. 4627 */ 4628 public void scheduleLayoutAnimation() { 4629 mGroupFlags |= FLAG_RUN_ANIMATION; 4630 } 4631 4632 /** 4633 * Sets the layout animation controller used to animate the group's 4634 * children after the first layout. 4635 * 4636 * @param controller the animation controller 4637 */ 4638 public void setLayoutAnimation(LayoutAnimationController controller) { 4639 mLayoutAnimationController = controller; 4640 if (mLayoutAnimationController != null) { 4641 mGroupFlags |= FLAG_RUN_ANIMATION; 4642 } 4643 } 4644 4645 /** 4646 * Returns the layout animation controller used to animate the group's 4647 * children. 4648 * 4649 * @return the current animation controller 4650 */ 4651 public LayoutAnimationController getLayoutAnimation() { 4652 return mLayoutAnimationController; 4653 } 4654 4655 /** 4656 * Indicates whether the children's drawing cache is used during a layout 4657 * animation. By default, the drawing cache is enabled but this will prevent 4658 * nested layout animations from working. To nest animations, you must disable 4659 * the cache. 4660 * 4661 * @return true if the animation cache is enabled, false otherwise 4662 * 4663 * @see #setAnimationCacheEnabled(boolean) 4664 * @see View#setDrawingCacheEnabled(boolean) 4665 */ 4666 @ViewDebug.ExportedProperty 4667 public boolean isAnimationCacheEnabled() { 4668 return (mGroupFlags & FLAG_ANIMATION_CACHE) == FLAG_ANIMATION_CACHE; 4669 } 4670 4671 /** 4672 * Enables or disables the children's drawing cache during a layout animation. 4673 * By default, the drawing cache is enabled but this will prevent nested 4674 * layout animations from working. To nest animations, you must disable the 4675 * cache. 4676 * 4677 * @param enabled true to enable the animation cache, false otherwise 4678 * 4679 * @see #isAnimationCacheEnabled() 4680 * @see View#setDrawingCacheEnabled(boolean) 4681 */ 4682 public void setAnimationCacheEnabled(boolean enabled) { 4683 setBooleanFlag(FLAG_ANIMATION_CACHE, enabled); 4684 } 4685 4686 /** 4687 * Indicates whether this ViewGroup will always try to draw its children using their 4688 * drawing cache. By default this property is enabled. 4689 * 4690 * @return true if the animation cache is enabled, false otherwise 4691 * 4692 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4693 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4694 * @see View#setDrawingCacheEnabled(boolean) 4695 */ 4696 @ViewDebug.ExportedProperty(category = "drawing") 4697 public boolean isAlwaysDrawnWithCacheEnabled() { 4698 return (mGroupFlags & FLAG_ALWAYS_DRAWN_WITH_CACHE) == FLAG_ALWAYS_DRAWN_WITH_CACHE; 4699 } 4700 4701 /** 4702 * Indicates whether this ViewGroup will always try to draw its children using their 4703 * drawing cache. This property can be set to true when the cache rendering is 4704 * slightly different from the children's normal rendering. Renderings can be different, 4705 * for instance, when the cache's quality is set to low. 4706 * 4707 * When this property is disabled, the ViewGroup will use the drawing cache of its 4708 * children only when asked to. It's usually the task of subclasses to tell ViewGroup 4709 * when to start using the drawing cache and when to stop using it. 4710 * 4711 * @param always true to always draw with the drawing cache, false otherwise 4712 * 4713 * @see #isAlwaysDrawnWithCacheEnabled() 4714 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4715 * @see View#setDrawingCacheEnabled(boolean) 4716 * @see View#setDrawingCacheQuality(int) 4717 */ 4718 public void setAlwaysDrawnWithCacheEnabled(boolean always) { 4719 setBooleanFlag(FLAG_ALWAYS_DRAWN_WITH_CACHE, always); 4720 } 4721 4722 /** 4723 * Indicates whether the ViewGroup is currently drawing its children using 4724 * their drawing cache. 4725 * 4726 * @return true if children should be drawn with their cache, false otherwise 4727 * 4728 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4729 * @see #setChildrenDrawnWithCacheEnabled(boolean) 4730 */ 4731 @ViewDebug.ExportedProperty(category = "drawing") 4732 protected boolean isChildrenDrawnWithCacheEnabled() { 4733 return (mGroupFlags & FLAG_CHILDREN_DRAWN_WITH_CACHE) == FLAG_CHILDREN_DRAWN_WITH_CACHE; 4734 } 4735 4736 /** 4737 * Tells the ViewGroup to draw its children using their drawing cache. This property 4738 * is ignored when {@link #isAlwaysDrawnWithCacheEnabled()} is true. A child's drawing cache 4739 * will be used only if it has been enabled. 4740 * 4741 * Subclasses should call this method to start and stop using the drawing cache when 4742 * they perform performance sensitive operations, like scrolling or animating. 4743 * 4744 * @param enabled true if children should be drawn with their cache, false otherwise 4745 * 4746 * @see #setAlwaysDrawnWithCacheEnabled(boolean) 4747 * @see #isChildrenDrawnWithCacheEnabled() 4748 */ 4749 protected void setChildrenDrawnWithCacheEnabled(boolean enabled) { 4750 setBooleanFlag(FLAG_CHILDREN_DRAWN_WITH_CACHE, enabled); 4751 } 4752 4753 /** 4754 * Indicates whether the ViewGroup is drawing its children in the order defined by 4755 * {@link #getChildDrawingOrder(int, int)}. 4756 * 4757 * @return true if children drawing order is defined by {@link #getChildDrawingOrder(int, int)}, 4758 * false otherwise 4759 * 4760 * @see #setChildrenDrawingOrderEnabled(boolean) 4761 * @see #getChildDrawingOrder(int, int) 4762 */ 4763 @ViewDebug.ExportedProperty(category = "drawing") 4764 protected boolean isChildrenDrawingOrderEnabled() { 4765 return (mGroupFlags & FLAG_USE_CHILD_DRAWING_ORDER) == FLAG_USE_CHILD_DRAWING_ORDER; 4766 } 4767 4768 /** 4769 * Tells the ViewGroup whether to draw its children in the order defined by the method 4770 * {@link #getChildDrawingOrder(int, int)}. 4771 * 4772 * @param enabled true if the order of the children when drawing is determined by 4773 * {@link #getChildDrawingOrder(int, int)}, false otherwise 4774 * 4775 * @see #isChildrenDrawingOrderEnabled() 4776 * @see #getChildDrawingOrder(int, int) 4777 */ 4778 protected void setChildrenDrawingOrderEnabled(boolean enabled) { 4779 setBooleanFlag(FLAG_USE_CHILD_DRAWING_ORDER, enabled); 4780 } 4781 4782 private boolean getBooleanFlag(int flag) { 4783 return (mGroupFlags & flag) == flag; 4784 } 4785 4786 private void setBooleanFlag(int flag, boolean value) { 4787 if (value) { 4788 mGroupFlags |= flag; 4789 } else { 4790 mGroupFlags &= ~flag; 4791 } 4792 } 4793 4794 /** 4795 * Returns an integer indicating what types of drawing caches are kept in memory. 4796 * 4797 * @see #setPersistentDrawingCache(int) 4798 * @see #setAnimationCacheEnabled(boolean) 4799 * 4800 * @return one or a combination of {@link #PERSISTENT_NO_CACHE}, 4801 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4802 * and {@link #PERSISTENT_ALL_CACHES} 4803 */ 4804 @ViewDebug.ExportedProperty(category = "drawing", mapping = { 4805 @ViewDebug.IntToString(from = PERSISTENT_NO_CACHE, to = "NONE"), 4806 @ViewDebug.IntToString(from = PERSISTENT_ANIMATION_CACHE, to = "ANIMATION"), 4807 @ViewDebug.IntToString(from = PERSISTENT_SCROLLING_CACHE, to = "SCROLLING"), 4808 @ViewDebug.IntToString(from = PERSISTENT_ALL_CACHES, to = "ALL") 4809 }) 4810 public int getPersistentDrawingCache() { 4811 return mPersistentDrawingCache; 4812 } 4813 4814 /** 4815 * Indicates what types of drawing caches should be kept in memory after 4816 * they have been created. 4817 * 4818 * @see #getPersistentDrawingCache() 4819 * @see #setAnimationCacheEnabled(boolean) 4820 * 4821 * @param drawingCacheToKeep one or a combination of {@link #PERSISTENT_NO_CACHE}, 4822 * {@link #PERSISTENT_ANIMATION_CACHE}, {@link #PERSISTENT_SCROLLING_CACHE} 4823 * and {@link #PERSISTENT_ALL_CACHES} 4824 */ 4825 public void setPersistentDrawingCache(int drawingCacheToKeep) { 4826 mPersistentDrawingCache = drawingCacheToKeep & PERSISTENT_ALL_CACHES; 4827 } 4828 4829 private void setLayoutMode(int layoutMode, boolean explicitly) { 4830 mLayoutMode = layoutMode; 4831 setBooleanFlag(FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET, explicitly); 4832 } 4833 4834 /** 4835 * Recursively traverse the view hierarchy, resetting the layoutMode of any 4836 * descendants that had inherited a different layoutMode from a previous parent. 4837 * Recursion terminates when a descendant's mode is: 4838 * <ul> 4839 * <li>Undefined</li> 4840 * <li>The same as the root node's</li> 4841 * <li>A mode that had been explicitly set</li> 4842 * <ul/> 4843 * The first two clauses are optimizations. 4844 * @param layoutModeOfRoot 4845 */ 4846 @Override 4847 void invalidateInheritedLayoutMode(int layoutModeOfRoot) { 4848 if (mLayoutMode == LAYOUT_MODE_UNDEFINED || 4849 mLayoutMode == layoutModeOfRoot || 4850 getBooleanFlag(FLAG_LAYOUT_MODE_WAS_EXPLICITLY_SET)) { 4851 return; 4852 } 4853 setLayoutMode(LAYOUT_MODE_UNDEFINED, false); 4854 4855 // apply recursively 4856 for (int i = 0, N = getChildCount(); i < N; i++) { 4857 getChildAt(i).invalidateInheritedLayoutMode(layoutModeOfRoot); 4858 } 4859 } 4860 4861 /** 4862 * Returns the basis of alignment during layout operations on this ViewGroup: 4863 * either {@link #LAYOUT_MODE_CLIP_BOUNDS} or {@link #LAYOUT_MODE_OPTICAL_BOUNDS}. 4864 * <p> 4865 * If no layoutMode was explicitly set, either programmatically or in an XML resource, 4866 * the method returns the layoutMode of the view's parent ViewGroup if such a parent exists, 4867 * otherwise the method returns a default value of {@link #LAYOUT_MODE_CLIP_BOUNDS}. 4868 * 4869 * @return the layout mode to use during layout operations 4870 * 4871 * @see #setLayoutMode(int) 4872 */ 4873 public int getLayoutMode() { 4874 if (mLayoutMode == LAYOUT_MODE_UNDEFINED) { 4875 int inheritedLayoutMode = (mParent instanceof ViewGroup) ? 4876 ((ViewGroup) mParent).getLayoutMode() : LAYOUT_MODE_DEFAULT; 4877 setLayoutMode(inheritedLayoutMode, false); 4878 } 4879 return mLayoutMode; 4880 } 4881 4882 /** 4883 * Sets the basis of alignment during the layout of this ViewGroup. 4884 * Valid values are either {@link #LAYOUT_MODE_CLIP_BOUNDS} or 4885 * {@link #LAYOUT_MODE_OPTICAL_BOUNDS}. 4886 * 4887 * @param layoutMode the layout mode to use during layout operations 4888 * 4889 * @see #getLayoutMode() 4890 */ 4891 public void setLayoutMode(int layoutMode) { 4892 if (mLayoutMode != layoutMode) { 4893 invalidateInheritedLayoutMode(layoutMode); 4894 setLayoutMode(layoutMode, layoutMode != LAYOUT_MODE_UNDEFINED); 4895 requestLayout(); 4896 } 4897 } 4898 4899 /** 4900 * Returns a new set of layout parameters based on the supplied attributes set. 4901 * 4902 * @param attrs the attributes to build the layout parameters from 4903 * 4904 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4905 * of its descendants 4906 */ 4907 public LayoutParams generateLayoutParams(AttributeSet attrs) { 4908 return new LayoutParams(getContext(), attrs); 4909 } 4910 4911 /** 4912 * Returns a safe set of layout parameters based on the supplied layout params. 4913 * When a ViewGroup is passed a View whose layout params do not pass the test of 4914 * {@link #checkLayoutParams(android.view.ViewGroup.LayoutParams)}, this method 4915 * is invoked. This method should return a new set of layout params suitable for 4916 * this ViewGroup, possibly by copying the appropriate attributes from the 4917 * specified set of layout params. 4918 * 4919 * @param p The layout parameters to convert into a suitable set of layout parameters 4920 * for this ViewGroup. 4921 * 4922 * @return an instance of {@link android.view.ViewGroup.LayoutParams} or one 4923 * of its descendants 4924 */ 4925 protected LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 4926 return p; 4927 } 4928 4929 /** 4930 * Returns a set of default layout parameters. These parameters are requested 4931 * when the View passed to {@link #addView(View)} has no layout parameters 4932 * already set. If null is returned, an exception is thrown from addView. 4933 * 4934 * @return a set of default layout parameters or null 4935 */ 4936 protected LayoutParams generateDefaultLayoutParams() { 4937 return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 4938 } 4939 4940 /** 4941 * {@inheritDoc} 4942 */ 4943 @Override 4944 protected void debug(int depth) { 4945 super.debug(depth); 4946 String output; 4947 4948 if (mFocused != null) { 4949 output = debugIndent(depth); 4950 output += "mFocused"; 4951 Log.d(VIEW_LOG_TAG, output); 4952 } 4953 if (mChildrenCount != 0) { 4954 output = debugIndent(depth); 4955 output += "{"; 4956 Log.d(VIEW_LOG_TAG, output); 4957 } 4958 int count = mChildrenCount; 4959 for (int i = 0; i < count; i++) { 4960 View child = mChildren[i]; 4961 child.debug(depth + 1); 4962 } 4963 4964 if (mChildrenCount != 0) { 4965 output = debugIndent(depth); 4966 output += "}"; 4967 Log.d(VIEW_LOG_TAG, output); 4968 } 4969 } 4970 4971 /** 4972 * Returns the position in the group of the specified child view. 4973 * 4974 * @param child the view for which to get the position 4975 * @return a positive integer representing the position of the view in the 4976 * group, or -1 if the view does not exist in the group 4977 */ 4978 public int indexOfChild(View child) { 4979 final int count = mChildrenCount; 4980 final View[] children = mChildren; 4981 for (int i = 0; i < count; i++) { 4982 if (children[i] == child) { 4983 return i; 4984 } 4985 } 4986 return -1; 4987 } 4988 4989 /** 4990 * Returns the number of children in the group. 4991 * 4992 * @return a positive integer representing the number of children in 4993 * the group 4994 */ 4995 public int getChildCount() { 4996 return mChildrenCount; 4997 } 4998 4999 /** 5000 * Returns the view at the specified position in the group. 5001 * 5002 * @param index the position at which to get the view from 5003 * @return the view at the specified position or null if the position 5004 * does not exist within the group 5005 */ 5006 public View getChildAt(int index) { 5007 if (index < 0 || index >= mChildrenCount) { 5008 return null; 5009 } 5010 return mChildren[index]; 5011 } 5012 5013 /** 5014 * Ask all of the children of this view to measure themselves, taking into 5015 * account both the MeasureSpec requirements for this view and its padding. 5016 * We skip children that are in the GONE state The heavy lifting is done in 5017 * getChildMeasureSpec. 5018 * 5019 * @param widthMeasureSpec The width requirements for this view 5020 * @param heightMeasureSpec The height requirements for this view 5021 */ 5022 protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) { 5023 final int size = mChildrenCount; 5024 final View[] children = mChildren; 5025 for (int i = 0; i < size; ++i) { 5026 final View child = children[i]; 5027 if ((child.mViewFlags & VISIBILITY_MASK) != GONE) { 5028 measureChild(child, widthMeasureSpec, heightMeasureSpec); 5029 } 5030 } 5031 } 5032 5033 /** 5034 * Ask one of the children of this view to measure itself, taking into 5035 * account both the MeasureSpec requirements for this view and its padding. 5036 * The heavy lifting is done in getChildMeasureSpec. 5037 * 5038 * @param child The child to measure 5039 * @param parentWidthMeasureSpec The width requirements for this view 5040 * @param parentHeightMeasureSpec The height requirements for this view 5041 */ 5042 protected void measureChild(View child, int parentWidthMeasureSpec, 5043 int parentHeightMeasureSpec) { 5044 final LayoutParams lp = child.getLayoutParams(); 5045 5046 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 5047 mPaddingLeft + mPaddingRight, lp.width); 5048 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 5049 mPaddingTop + mPaddingBottom, lp.height); 5050 5051 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 5052 } 5053 5054 /** 5055 * Ask one of the children of this view to measure itself, taking into 5056 * account both the MeasureSpec requirements for this view and its padding 5057 * and margins. The child must have MarginLayoutParams The heavy lifting is 5058 * done in getChildMeasureSpec. 5059 * 5060 * @param child The child to measure 5061 * @param parentWidthMeasureSpec The width requirements for this view 5062 * @param widthUsed Extra space that has been used up by the parent 5063 * horizontally (possibly by other children of the parent) 5064 * @param parentHeightMeasureSpec The height requirements for this view 5065 * @param heightUsed Extra space that has been used up by the parent 5066 * vertically (possibly by other children of the parent) 5067 */ 5068 protected void measureChildWithMargins(View child, 5069 int parentWidthMeasureSpec, int widthUsed, 5070 int parentHeightMeasureSpec, int heightUsed) { 5071 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); 5072 5073 final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, 5074 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin 5075 + widthUsed, lp.width); 5076 final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, 5077 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin 5078 + heightUsed, lp.height); 5079 5080 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); 5081 } 5082 5083 /** 5084 * Does the hard part of measureChildren: figuring out the MeasureSpec to 5085 * pass to a particular child. This method figures out the right MeasureSpec 5086 * for one dimension (height or width) of one child view. 5087 * 5088 * The goal is to combine information from our MeasureSpec with the 5089 * LayoutParams of the child to get the best possible results. For example, 5090 * if the this view knows its size (because its MeasureSpec has a mode of 5091 * EXACTLY), and the child has indicated in its LayoutParams that it wants 5092 * to be the same size as the parent, the parent should ask the child to 5093 * layout given an exact size. 5094 * 5095 * @param spec The requirements for this view 5096 * @param padding The padding of this view for the current dimension and 5097 * margins, if applicable 5098 * @param childDimension How big the child wants to be in the current 5099 * dimension 5100 * @return a MeasureSpec integer for the child 5101 */ 5102 public static int getChildMeasureSpec(int spec, int padding, int childDimension) { 5103 int specMode = MeasureSpec.getMode(spec); 5104 int specSize = MeasureSpec.getSize(spec); 5105 5106 int size = Math.max(0, specSize - padding); 5107 5108 int resultSize = 0; 5109 int resultMode = 0; 5110 5111 switch (specMode) { 5112 // Parent has imposed an exact size on us 5113 case MeasureSpec.EXACTLY: 5114 if (childDimension >= 0) { 5115 resultSize = childDimension; 5116 resultMode = MeasureSpec.EXACTLY; 5117 } else if (childDimension == LayoutParams.MATCH_PARENT) { 5118 // Child wants to be our size. So be it. 5119 resultSize = size; 5120 resultMode = MeasureSpec.EXACTLY; 5121 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 5122 // Child wants to determine its own size. It can't be 5123 // bigger than us. 5124 resultSize = size; 5125 resultMode = MeasureSpec.AT_MOST; 5126 } 5127 break; 5128 5129 // Parent has imposed a maximum size on us 5130 case MeasureSpec.AT_MOST: 5131 if (childDimension >= 0) { 5132 // Child wants a specific size... so be it 5133 resultSize = childDimension; 5134 resultMode = MeasureSpec.EXACTLY; 5135 } else if (childDimension == LayoutParams.MATCH_PARENT) { 5136 // Child wants to be our size, but our size is not fixed. 5137 // Constrain child to not be bigger than us. 5138 resultSize = size; 5139 resultMode = MeasureSpec.AT_MOST; 5140 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 5141 // Child wants to determine its own size. It can't be 5142 // bigger than us. 5143 resultSize = size; 5144 resultMode = MeasureSpec.AT_MOST; 5145 } 5146 break; 5147 5148 // Parent asked to see how big we want to be 5149 case MeasureSpec.UNSPECIFIED: 5150 if (childDimension >= 0) { 5151 // Child wants a specific size... let him have it 5152 resultSize = childDimension; 5153 resultMode = MeasureSpec.EXACTLY; 5154 } else if (childDimension == LayoutParams.MATCH_PARENT) { 5155 // Child wants to be our size... find out how big it should 5156 // be 5157 resultSize = 0; 5158 resultMode = MeasureSpec.UNSPECIFIED; 5159 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 5160 // Child wants to determine its own size.... find out how 5161 // big it should be 5162 resultSize = 0; 5163 resultMode = MeasureSpec.UNSPECIFIED; 5164 } 5165 break; 5166 } 5167 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 5168 } 5169 5170 5171 /** 5172 * Removes any pending animations for views that have been removed. Call 5173 * this if you don't want animations for exiting views to stack up. 5174 */ 5175 public void clearDisappearingChildren() { 5176 if (mDisappearingChildren != null) { 5177 mDisappearingChildren.clear(); 5178 invalidate(); 5179 } 5180 } 5181 5182 /** 5183 * Add a view which is removed from mChildren but still needs animation 5184 * 5185 * @param v View to add 5186 */ 5187 private void addDisappearingView(View v) { 5188 ArrayList<View> disappearingChildren = mDisappearingChildren; 5189 5190 if (disappearingChildren == null) { 5191 disappearingChildren = mDisappearingChildren = new ArrayList<View>(); 5192 } 5193 5194 disappearingChildren.add(v); 5195 } 5196 5197 /** 5198 * Cleanup a view when its animation is done. This may mean removing it from 5199 * the list of disappearing views. 5200 * 5201 * @param view The view whose animation has finished 5202 * @param animation The animation, cannot be null 5203 */ 5204 void finishAnimatingView(final View view, Animation animation) { 5205 final ArrayList<View> disappearingChildren = mDisappearingChildren; 5206 if (disappearingChildren != null) { 5207 if (disappearingChildren.contains(view)) { 5208 disappearingChildren.remove(view); 5209 5210 if (view.mAttachInfo != null) { 5211 view.dispatchDetachedFromWindow(); 5212 } 5213 5214 view.clearAnimation(); 5215 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 5216 } 5217 } 5218 5219 if (animation != null && !animation.getFillAfter()) { 5220 view.clearAnimation(); 5221 } 5222 5223 if ((view.mPrivateFlags & PFLAG_ANIMATION_STARTED) == PFLAG_ANIMATION_STARTED) { 5224 view.onAnimationEnd(); 5225 // Should be performed by onAnimationEnd() but this avoid an infinite loop, 5226 // so we'd rather be safe than sorry 5227 view.mPrivateFlags &= ~PFLAG_ANIMATION_STARTED; 5228 // Draw one more frame after the animation is done 5229 mGroupFlags |= FLAG_INVALIDATE_REQUIRED; 5230 } 5231 } 5232 5233 /** 5234 * Utility function called by View during invalidation to determine whether a view that 5235 * is invisible or gone should still be invalidated because it is being transitioned (and 5236 * therefore still needs to be drawn). 5237 */ 5238 boolean isViewTransitioning(View view) { 5239 return (mTransitioningViews != null && mTransitioningViews.contains(view)); 5240 } 5241 5242 /** 5243 * This method tells the ViewGroup that the given View object, which should have this 5244 * ViewGroup as its parent, 5245 * should be kept around (re-displayed when the ViewGroup draws its children) even if it 5246 * is removed from its parent. This allows animations, such as those used by 5247 * {@link android.app.Fragment} and {@link android.animation.LayoutTransition} to animate 5248 * the removal of views. A call to this method should always be accompanied by a later call 5249 * to {@link #endViewTransition(View)}, such as after an animation on the View has finished, 5250 * so that the View finally gets removed. 5251 * 5252 * @param view The View object to be kept visible even if it gets removed from its parent. 5253 */ 5254 public void startViewTransition(View view) { 5255 if (view.mParent == this) { 5256 if (mTransitioningViews == null) { 5257 mTransitioningViews = new ArrayList<View>(); 5258 } 5259 mTransitioningViews.add(view); 5260 } 5261 } 5262 5263 /** 5264 * This method should always be called following an earlier call to 5265 * {@link #startViewTransition(View)}. The given View is finally removed from its parent 5266 * and will no longer be displayed. Note that this method does not perform the functionality 5267 * of removing a view from its parent; it just discontinues the display of a View that 5268 * has previously been removed. 5269 * 5270 * @return view The View object that has been removed but is being kept around in the visible 5271 * hierarchy by an earlier call to {@link #startViewTransition(View)}. 5272 */ 5273 public void endViewTransition(View view) { 5274 if (mTransitioningViews != null) { 5275 mTransitioningViews.remove(view); 5276 final ArrayList<View> disappearingChildren = mDisappearingChildren; 5277 if (disappearingChildren != null && disappearingChildren.contains(view)) { 5278 disappearingChildren.remove(view); 5279 if (mVisibilityChangingChildren != null && 5280 mVisibilityChangingChildren.contains(view)) { 5281 mVisibilityChangingChildren.remove(view); 5282 } else { 5283 if (view.mAttachInfo != null) { 5284 view.dispatchDetachedFromWindow(); 5285 } 5286 if (view.mParent != null) { 5287 view.mParent = null; 5288 } 5289 } 5290 invalidate(); 5291 } 5292 } 5293 } 5294 5295 private LayoutTransition.TransitionListener mLayoutTransitionListener = 5296 new LayoutTransition.TransitionListener() { 5297 @Override 5298 public void startTransition(LayoutTransition transition, ViewGroup container, 5299 View view, int transitionType) { 5300 // We only care about disappearing items, since we need special logic to keep 5301 // those items visible after they've been 'removed' 5302 if (transitionType == LayoutTransition.DISAPPEARING) { 5303 startViewTransition(view); 5304 } 5305 } 5306 5307 @Override 5308 public void endTransition(LayoutTransition transition, ViewGroup container, 5309 View view, int transitionType) { 5310 if (mLayoutCalledWhileSuppressed && !transition.isChangingLayout()) { 5311 requestLayout(); 5312 mLayoutCalledWhileSuppressed = false; 5313 } 5314 if (transitionType == LayoutTransition.DISAPPEARING && mTransitioningViews != null) { 5315 endViewTransition(view); 5316 } 5317 } 5318 }; 5319 5320 /** 5321 * Tells this ViewGroup to suppress all layout() calls until layout 5322 * suppression is disabled with a later call to suppressLayout(false). 5323 * When layout suppression is disabled, a requestLayout() call is sent 5324 * if layout() was attempted while layout was being suppressed. 5325 * 5326 * @hide 5327 */ 5328 public void suppressLayout(boolean suppress) { 5329 mSuppressLayout = suppress; 5330 if (!suppress) { 5331 if (mLayoutCalledWhileSuppressed) { 5332 requestLayout(); 5333 mLayoutCalledWhileSuppressed = false; 5334 } 5335 } 5336 } 5337 5338 /** 5339 * {@inheritDoc} 5340 */ 5341 @Override 5342 public boolean gatherTransparentRegion(Region region) { 5343 // If no transparent regions requested, we are always opaque. 5344 final boolean meOpaque = (mPrivateFlags & View.PFLAG_REQUEST_TRANSPARENT_REGIONS) == 0; 5345 if (meOpaque && region == null) { 5346 // The caller doesn't care about the region, so stop now. 5347 return true; 5348 } 5349 super.gatherTransparentRegion(region); 5350 final View[] children = mChildren; 5351 final int count = mChildrenCount; 5352 boolean noneOfTheChildrenAreTransparent = true; 5353 for (int i = 0; i < count; i++) { 5354 final View child = children[i]; 5355 if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { 5356 if (!child.gatherTransparentRegion(region)) { 5357 noneOfTheChildrenAreTransparent = false; 5358 } 5359 } 5360 } 5361 return meOpaque || noneOfTheChildrenAreTransparent; 5362 } 5363 5364 /** 5365 * {@inheritDoc} 5366 */ 5367 public void requestTransparentRegion(View child) { 5368 if (child != null) { 5369 child.mPrivateFlags |= View.PFLAG_REQUEST_TRANSPARENT_REGIONS; 5370 if (mParent != null) { 5371 mParent.requestTransparentRegion(this); 5372 } 5373 } 5374 } 5375 5376 5377 @Override 5378 protected boolean fitSystemWindows(Rect insets) { 5379 boolean done = super.fitSystemWindows(insets); 5380 if (!done) { 5381 final int count = mChildrenCount; 5382 final View[] children = mChildren; 5383 for (int i = 0; i < count; i++) { 5384 done = children[i].fitSystemWindows(insets); 5385 if (done) { 5386 break; 5387 } 5388 } 5389 } 5390 return done; 5391 } 5392 5393 /** 5394 * Returns the animation listener to which layout animation events are 5395 * sent. 5396 * 5397 * @return an {@link android.view.animation.Animation.AnimationListener} 5398 */ 5399 public Animation.AnimationListener getLayoutAnimationListener() { 5400 return mAnimationListener; 5401 } 5402 5403 @Override 5404 protected void drawableStateChanged() { 5405 super.drawableStateChanged(); 5406 5407 if ((mGroupFlags & FLAG_NOTIFY_CHILDREN_ON_DRAWABLE_STATE_CHANGE) != 0) { 5408 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 5409 throw new IllegalStateException("addStateFromChildren cannot be enabled if a" 5410 + " child has duplicateParentState set to true"); 5411 } 5412 5413 final View[] children = mChildren; 5414 final int count = mChildrenCount; 5415 5416 for (int i = 0; i < count; i++) { 5417 final View child = children[i]; 5418 if ((child.mViewFlags & DUPLICATE_PARENT_STATE) != 0) { 5419 child.refreshDrawableState(); 5420 } 5421 } 5422 } 5423 } 5424 5425 @Override 5426 public void jumpDrawablesToCurrentState() { 5427 super.jumpDrawablesToCurrentState(); 5428 final View[] children = mChildren; 5429 final int count = mChildrenCount; 5430 for (int i = 0; i < count; i++) { 5431 children[i].jumpDrawablesToCurrentState(); 5432 } 5433 } 5434 5435 @Override 5436 protected int[] onCreateDrawableState(int extraSpace) { 5437 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) == 0) { 5438 return super.onCreateDrawableState(extraSpace); 5439 } 5440 5441 int need = 0; 5442 int n = getChildCount(); 5443 for (int i = 0; i < n; i++) { 5444 int[] childState = getChildAt(i).getDrawableState(); 5445 5446 if (childState != null) { 5447 need += childState.length; 5448 } 5449 } 5450 5451 int[] state = super.onCreateDrawableState(extraSpace + need); 5452 5453 for (int i = 0; i < n; i++) { 5454 int[] childState = getChildAt(i).getDrawableState(); 5455 5456 if (childState != null) { 5457 state = mergeDrawableStates(state, childState); 5458 } 5459 } 5460 5461 return state; 5462 } 5463 5464 /** 5465 * Sets whether this ViewGroup's drawable states also include 5466 * its children's drawable states. This is used, for example, to 5467 * make a group appear to be focused when its child EditText or button 5468 * is focused. 5469 */ 5470 public void setAddStatesFromChildren(boolean addsStates) { 5471 if (addsStates) { 5472 mGroupFlags |= FLAG_ADD_STATES_FROM_CHILDREN; 5473 } else { 5474 mGroupFlags &= ~FLAG_ADD_STATES_FROM_CHILDREN; 5475 } 5476 5477 refreshDrawableState(); 5478 } 5479 5480 /** 5481 * Returns whether this ViewGroup's drawable states also include 5482 * its children's drawable states. This is used, for example, to 5483 * make a group appear to be focused when its child EditText or button 5484 * is focused. 5485 */ 5486 public boolean addStatesFromChildren() { 5487 return (mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0; 5488 } 5489 5490 /** 5491 * If {@link #addStatesFromChildren} is true, refreshes this group's 5492 * drawable state (to include the states from its children). 5493 */ 5494 public void childDrawableStateChanged(View child) { 5495 if ((mGroupFlags & FLAG_ADD_STATES_FROM_CHILDREN) != 0) { 5496 refreshDrawableState(); 5497 } 5498 } 5499 5500 /** 5501 * Specifies the animation listener to which layout animation events must 5502 * be sent. Only 5503 * {@link android.view.animation.Animation.AnimationListener#onAnimationStart(Animation)} 5504 * and 5505 * {@link android.view.animation.Animation.AnimationListener#onAnimationEnd(Animation)} 5506 * are invoked. 5507 * 5508 * @param animationListener the layout animation listener 5509 */ 5510 public void setLayoutAnimationListener(Animation.AnimationListener animationListener) { 5511 mAnimationListener = animationListener; 5512 } 5513 5514 /** 5515 * This method is called by LayoutTransition when there are 'changing' animations that need 5516 * to start after the layout/setup phase. The request is forwarded to the ViewAncestor, who 5517 * starts all pending transitions prior to the drawing phase in the current traversal. 5518 * 5519 * @param transition The LayoutTransition to be started on the next traversal. 5520 * 5521 * @hide 5522 */ 5523 public void requestTransitionStart(LayoutTransition transition) { 5524 ViewRootImpl viewAncestor = getViewRootImpl(); 5525 if (viewAncestor != null) { 5526 viewAncestor.requestTransitionStart(transition); 5527 } 5528 } 5529 5530 /** 5531 * @hide 5532 */ 5533 @Override 5534 public boolean resolveRtlPropertiesIfNeeded() { 5535 final boolean result = super.resolveRtlPropertiesIfNeeded(); 5536 // We dont need to resolve the children RTL properties if nothing has changed for the parent 5537 if (result) { 5538 int count = getChildCount(); 5539 for (int i = 0; i < count; i++) { 5540 final View child = getChildAt(i); 5541 if (child.isLayoutDirectionInherited()) { 5542 child.resolveRtlPropertiesIfNeeded(); 5543 } 5544 } 5545 } 5546 return result; 5547 } 5548 5549 /** 5550 * @hide 5551 */ 5552 @Override 5553 public boolean resolveLayoutDirection() { 5554 final boolean result = super.resolveLayoutDirection(); 5555 if (result) { 5556 int count = getChildCount(); 5557 for (int i = 0; i < count; i++) { 5558 final View child = getChildAt(i); 5559 if (child.isLayoutDirectionInherited()) { 5560 child.resolveLayoutDirection(); 5561 } 5562 } 5563 } 5564 return result; 5565 } 5566 5567 /** 5568 * @hide 5569 */ 5570 @Override 5571 public boolean resolveTextDirection() { 5572 final boolean result = super.resolveTextDirection(); 5573 if (result) { 5574 int count = getChildCount(); 5575 for (int i = 0; i < count; i++) { 5576 final View child = getChildAt(i); 5577 if (child.isTextDirectionInherited()) { 5578 child.resolveTextDirection(); 5579 } 5580 } 5581 } 5582 return result; 5583 } 5584 5585 /** 5586 * @hide 5587 */ 5588 @Override 5589 public boolean resolveTextAlignment() { 5590 final boolean result = super.resolveTextAlignment(); 5591 if (result) { 5592 int count = getChildCount(); 5593 for (int i = 0; i < count; i++) { 5594 final View child = getChildAt(i); 5595 if (child.isTextAlignmentInherited()) { 5596 child.resolveTextAlignment(); 5597 } 5598 } 5599 } 5600 return result; 5601 } 5602 5603 /** 5604 * @hide 5605 */ 5606 @Override 5607 public void resolvePadding() { 5608 super.resolvePadding(); 5609 int count = getChildCount(); 5610 for (int i = 0; i < count; i++) { 5611 final View child = getChildAt(i); 5612 if (child.isLayoutDirectionInherited()) { 5613 child.resolvePadding(); 5614 } 5615 } 5616 } 5617 5618 /** 5619 * @hide 5620 */ 5621 @Override 5622 protected void resolveDrawables() { 5623 super.resolveDrawables(); 5624 int count = getChildCount(); 5625 for (int i = 0; i < count; i++) { 5626 final View child = getChildAt(i); 5627 if (child.isLayoutDirectionInherited()) { 5628 child.resolveDrawables(); 5629 } 5630 } 5631 } 5632 5633 /** 5634 * @hide 5635 */ 5636 @Override 5637 public void resolveLayoutParams() { 5638 super.resolveLayoutParams(); 5639 int count = getChildCount(); 5640 for (int i = 0; i < count; i++) { 5641 final View child = getChildAt(i); 5642 child.resolveLayoutParams(); 5643 } 5644 } 5645 5646 /** 5647 * @hide 5648 */ 5649 @Override 5650 public void resetResolvedLayoutDirection() { 5651 super.resetResolvedLayoutDirection(); 5652 5653 int count = getChildCount(); 5654 for (int i = 0; i < count; i++) { 5655 final View child = getChildAt(i); 5656 if (child.isLayoutDirectionInherited()) { 5657 child.resetResolvedLayoutDirection(); 5658 } 5659 } 5660 } 5661 5662 /** 5663 * @hide 5664 */ 5665 @Override 5666 public void resetResolvedTextDirection() { 5667 super.resetResolvedTextDirection(); 5668 5669 int count = getChildCount(); 5670 for (int i = 0; i < count; i++) { 5671 final View child = getChildAt(i); 5672 if (child.isTextDirectionInherited()) { 5673 child.resetResolvedTextDirection(); 5674 } 5675 } 5676 } 5677 5678 /** 5679 * @hide 5680 */ 5681 @Override 5682 public void resetResolvedTextAlignment() { 5683 super.resetResolvedTextAlignment(); 5684 5685 int count = getChildCount(); 5686 for (int i = 0; i < count; i++) { 5687 final View child = getChildAt(i); 5688 if (child.isTextAlignmentInherited()) { 5689 child.resetResolvedTextAlignment(); 5690 } 5691 } 5692 } 5693 5694 /** 5695 * @hide 5696 */ 5697 @Override 5698 public void resetResolvedPadding() { 5699 super.resetResolvedPadding(); 5700 5701 int count = getChildCount(); 5702 for (int i = 0; i < count; i++) { 5703 final View child = getChildAt(i); 5704 if (child.isLayoutDirectionInherited()) { 5705 child.resetResolvedPadding(); 5706 } 5707 } 5708 } 5709 5710 /** 5711 * @hide 5712 */ 5713 @Override 5714 protected void resetResolvedDrawables() { 5715 super.resetResolvedDrawables(); 5716 5717 int count = getChildCount(); 5718 for (int i = 0; i < count; i++) { 5719 final View child = getChildAt(i); 5720 if (child.isLayoutDirectionInherited()) { 5721 child.resetResolvedDrawables(); 5722 } 5723 } 5724 } 5725 5726 /** 5727 * Return true if the pressed state should be delayed for children or descendants of this 5728 * ViewGroup. Generally, this should be done for containers that can scroll, such as a List. 5729 * This prevents the pressed state from appearing when the user is actually trying to scroll 5730 * the content. 5731 * 5732 * The default implementation returns true for compatibility reasons. Subclasses that do 5733 * not scroll should generally override this method and return false. 5734 */ 5735 public boolean shouldDelayChildPressedState() { 5736 return true; 5737 } 5738 5739 /** @hide */ 5740 protected void onSetLayoutParams(View child, LayoutParams layoutParams) { 5741 } 5742 5743 /** 5744 * LayoutParams are used by views to tell their parents how they want to be 5745 * laid out. See 5746 * {@link android.R.styleable#ViewGroup_Layout ViewGroup Layout Attributes} 5747 * for a list of all child view attributes that this class supports. 5748 * 5749 * <p> 5750 * The base LayoutParams class just describes how big the view wants to be 5751 * for both width and height. For each dimension, it can specify one of: 5752 * <ul> 5753 * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which 5754 * means that the view wants to be as big as its parent (minus padding) 5755 * <li> WRAP_CONTENT, which means that the view wants to be just big enough 5756 * to enclose its content (plus padding) 5757 * <li> an exact number 5758 * </ul> 5759 * There are subclasses of LayoutParams for different subclasses of 5760 * ViewGroup. For example, AbsoluteLayout has its own subclass of 5761 * LayoutParams which adds an X and Y value.</p> 5762 * 5763 * <div class="special reference"> 5764 * <h3>Developer Guides</h3> 5765 * <p>For more information about creating user interface layouts, read the 5766 * <a href="{@docRoot}guide/topics/ui/declaring-layout.html">XML Layouts</a> developer 5767 * guide.</p></div> 5768 * 5769 * @attr ref android.R.styleable#ViewGroup_Layout_layout_height 5770 * @attr ref android.R.styleable#ViewGroup_Layout_layout_width 5771 */ 5772 public static class LayoutParams { 5773 /** 5774 * Special value for the height or width requested by a View. 5775 * FILL_PARENT means that the view wants to be as big as its parent, 5776 * minus the parent's padding, if any. This value is deprecated 5777 * starting in API Level 8 and replaced by {@link #MATCH_PARENT}. 5778 */ 5779 @SuppressWarnings({"UnusedDeclaration"}) 5780 @Deprecated 5781 public static final int FILL_PARENT = -1; 5782 5783 /** 5784 * Special value for the height or width requested by a View. 5785 * MATCH_PARENT means that the view wants to be as big as its parent, 5786 * minus the parent's padding, if any. Introduced in API Level 8. 5787 */ 5788 public static final int MATCH_PARENT = -1; 5789 5790 /** 5791 * Special value for the height or width requested by a View. 5792 * WRAP_CONTENT means that the view wants to be just large enough to fit 5793 * its own internal content, taking its own padding into account. 5794 */ 5795 public static final int WRAP_CONTENT = -2; 5796 5797 /** 5798 * Information about how wide the view wants to be. Can be one of the 5799 * constants FILL_PARENT (replaced by MATCH_PARENT , 5800 * in API Level 8) or WRAP_CONTENT. or an exact size. 5801 */ 5802 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5803 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5804 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5805 }) 5806 public int width; 5807 5808 /** 5809 * Information about how tall the view wants to be. Can be one of the 5810 * constants FILL_PARENT (replaced by MATCH_PARENT , 5811 * in API Level 8) or WRAP_CONTENT. or an exact size. 5812 */ 5813 @ViewDebug.ExportedProperty(category = "layout", mapping = { 5814 @ViewDebug.IntToString(from = MATCH_PARENT, to = "MATCH_PARENT"), 5815 @ViewDebug.IntToString(from = WRAP_CONTENT, to = "WRAP_CONTENT") 5816 }) 5817 public int height; 5818 5819 /** 5820 * Used to animate layouts. 5821 */ 5822 public LayoutAnimationController.AnimationParameters layoutAnimationParameters; 5823 5824 /** 5825 * Creates a new set of layout parameters. The values are extracted from 5826 * the supplied attributes set and context. The XML attributes mapped 5827 * to this set of layout parameters are: 5828 * 5829 * <ul> 5830 * <li><code>layout_width</code>: the width, either an exact value, 5831 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5832 * {@link #MATCH_PARENT} in API Level 8)</li> 5833 * <li><code>layout_height</code>: the height, either an exact value, 5834 * {@link #WRAP_CONTENT}, or {@link #FILL_PARENT} (replaced by 5835 * {@link #MATCH_PARENT} in API Level 8)</li> 5836 * </ul> 5837 * 5838 * @param c the application environment 5839 * @param attrs the set of attributes from which to extract the layout 5840 * parameters' values 5841 */ 5842 public LayoutParams(Context c, AttributeSet attrs) { 5843 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout); 5844 setBaseAttributes(a, 5845 R.styleable.ViewGroup_Layout_layout_width, 5846 R.styleable.ViewGroup_Layout_layout_height); 5847 a.recycle(); 5848 } 5849 5850 /** 5851 * Creates a new set of layout parameters with the specified width 5852 * and height. 5853 * 5854 * @param width the width, either {@link #WRAP_CONTENT}, 5855 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5856 * API Level 8), or a fixed size in pixels 5857 * @param height the height, either {@link #WRAP_CONTENT}, 5858 * {@link #FILL_PARENT} (replaced by {@link #MATCH_PARENT} in 5859 * API Level 8), or a fixed size in pixels 5860 */ 5861 public LayoutParams(int width, int height) { 5862 this.width = width; 5863 this.height = height; 5864 } 5865 5866 /** 5867 * Copy constructor. Clones the width and height values of the source. 5868 * 5869 * @param source The layout params to copy from. 5870 */ 5871 public LayoutParams(LayoutParams source) { 5872 this.width = source.width; 5873 this.height = source.height; 5874 } 5875 5876 /** 5877 * Used internally by MarginLayoutParams. 5878 * @hide 5879 */ 5880 LayoutParams() { 5881 } 5882 5883 /** 5884 * Extracts the layout parameters from the supplied attributes. 5885 * 5886 * @param a the style attributes to extract the parameters from 5887 * @param widthAttr the identifier of the width attribute 5888 * @param heightAttr the identifier of the height attribute 5889 */ 5890 protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { 5891 width = a.getLayoutDimension(widthAttr, "layout_width"); 5892 height = a.getLayoutDimension(heightAttr, "layout_height"); 5893 } 5894 5895 /** 5896 * Resolve layout parameters depending on the layout direction. Subclasses that care about 5897 * layoutDirection changes should override this method. The default implementation does 5898 * nothing. 5899 * 5900 * @param layoutDirection the direction of the layout 5901 * 5902 * {@link View#LAYOUT_DIRECTION_LTR} 5903 * {@link View#LAYOUT_DIRECTION_RTL} 5904 */ 5905 public void resolveLayoutDirection(int layoutDirection) { 5906 } 5907 5908 /** 5909 * Returns a String representation of this set of layout parameters. 5910 * 5911 * @param output the String to prepend to the internal representation 5912 * @return a String with the following format: output + 5913 * "ViewGroup.LayoutParams={ width=WIDTH, height=HEIGHT }" 5914 * 5915 * @hide 5916 */ 5917 public String debug(String output) { 5918 return output + "ViewGroup.LayoutParams={ width=" 5919 + sizeToString(width) + ", height=" + sizeToString(height) + " }"; 5920 } 5921 5922 /** 5923 * Use {@code canvas} to draw suitable debugging annotations for these LayoutParameters. 5924 * 5925 * @param view the view that contains these layout parameters 5926 * @param canvas the canvas on which to draw 5927 * 5928 * @hide 5929 */ 5930 public void onDebugDraw(View view, Canvas canvas, Paint paint) { 5931 } 5932 5933 /** 5934 * Converts the specified size to a readable String. 5935 * 5936 * @param size the size to convert 5937 * @return a String instance representing the supplied size 5938 * 5939 * @hide 5940 */ 5941 protected static String sizeToString(int size) { 5942 if (size == WRAP_CONTENT) { 5943 return "wrap-content"; 5944 } 5945 if (size == MATCH_PARENT) { 5946 return "match-parent"; 5947 } 5948 return String.valueOf(size); 5949 } 5950 } 5951 5952 /** 5953 * Per-child layout information for layouts that support margins. 5954 * See 5955 * {@link android.R.styleable#ViewGroup_MarginLayout ViewGroup Margin Layout Attributes} 5956 * for a list of all child view attributes that this class supports. 5957 */ 5958 public static class MarginLayoutParams extends ViewGroup.LayoutParams { 5959 /** 5960 * The left margin in pixels of the child. 5961 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5962 * to this field. 5963 */ 5964 @ViewDebug.ExportedProperty(category = "layout") 5965 public int leftMargin; 5966 5967 /** 5968 * The top margin in pixels of the child. 5969 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5970 * to this field. 5971 */ 5972 @ViewDebug.ExportedProperty(category = "layout") 5973 public int topMargin; 5974 5975 /** 5976 * The right margin in pixels of the child. 5977 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5978 * to this field. 5979 */ 5980 @ViewDebug.ExportedProperty(category = "layout") 5981 public int rightMargin; 5982 5983 /** 5984 * The bottom margin in pixels of the child. 5985 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5986 * to this field. 5987 */ 5988 @ViewDebug.ExportedProperty(category = "layout") 5989 public int bottomMargin; 5990 5991 /** 5992 * The start margin in pixels of the child. 5993 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 5994 * to this field. 5995 */ 5996 @ViewDebug.ExportedProperty(category = "layout") 5997 private int startMargin = DEFAULT_MARGIN_RELATIVE; 5998 5999 /** 6000 * The end margin in pixels of the child. 6001 * Call {@link ViewGroup#setLayoutParams(LayoutParams)} after reassigning a new value 6002 * to this field. 6003 */ 6004 @ViewDebug.ExportedProperty(category = "layout") 6005 private int endMargin = DEFAULT_MARGIN_RELATIVE; 6006 6007 /** 6008 * The default start and end margin. 6009 * @hide 6010 */ 6011 public static final int DEFAULT_MARGIN_RELATIVE = Integer.MIN_VALUE; 6012 6013 /** 6014 * Bit 0: layout direction 6015 * Bit 1: layout direction 6016 * Bit 2: left margin undefined 6017 * Bit 3: right margin undefined 6018 * Bit 4: is RTL compatibility mode 6019 * Bit 5: need resolution 6020 * 6021 * Bit 6 to 7 not used 6022 * 6023 * @hide 6024 */ 6025 @ViewDebug.ExportedProperty(category = "layout", flagMapping = { 6026 @ViewDebug.FlagToString(mask = LAYOUT_DIRECTION_MASK, 6027 equals = LAYOUT_DIRECTION_MASK, name = "LAYOUT_DIRECTION"), 6028 @ViewDebug.FlagToString(mask = LEFT_MARGIN_UNDEFINED_MASK, 6029 equals = LEFT_MARGIN_UNDEFINED_MASK, name = "LEFT_MARGIN_UNDEFINED_MASK"), 6030 @ViewDebug.FlagToString(mask = RIGHT_MARGIN_UNDEFINED_MASK, 6031 equals = RIGHT_MARGIN_UNDEFINED_MASK, name = "RIGHT_MARGIN_UNDEFINED_MASK"), 6032 @ViewDebug.FlagToString(mask = RTL_COMPATIBILITY_MODE_MASK, 6033 equals = RTL_COMPATIBILITY_MODE_MASK, name = "RTL_COMPATIBILITY_MODE_MASK"), 6034 @ViewDebug.FlagToString(mask = NEED_RESOLUTION_MASK, 6035 equals = NEED_RESOLUTION_MASK, name = "NEED_RESOLUTION_MASK") 6036 }) 6037 byte mMarginFlags; 6038 6039 private static final int LAYOUT_DIRECTION_MASK = 0x00000003; 6040 private static final int LEFT_MARGIN_UNDEFINED_MASK = 0x00000004; 6041 private static final int RIGHT_MARGIN_UNDEFINED_MASK = 0x00000008; 6042 private static final int RTL_COMPATIBILITY_MODE_MASK = 0x00000010; 6043 private static final int NEED_RESOLUTION_MASK = 0x00000020; 6044 6045 private static final int DEFAULT_MARGIN_RESOLVED = 0; 6046 private static final int UNDEFINED_MARGIN = DEFAULT_MARGIN_RELATIVE; 6047 6048 /** 6049 * Creates a new set of layout parameters. The values are extracted from 6050 * the supplied attributes set and context. 6051 * 6052 * @param c the application environment 6053 * @param attrs the set of attributes from which to extract the layout 6054 * parameters' values 6055 */ 6056 public MarginLayoutParams(Context c, AttributeSet attrs) { 6057 super(); 6058 6059 TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_MarginLayout); 6060 setBaseAttributes(a, 6061 R.styleable.ViewGroup_MarginLayout_layout_width, 6062 R.styleable.ViewGroup_MarginLayout_layout_height); 6063 6064 int margin = a.getDimensionPixelSize( 6065 com.android.internal.R.styleable.ViewGroup_MarginLayout_layout_margin, -1); 6066 if (margin >= 0) { 6067 leftMargin = margin; 6068 topMargin = margin; 6069 rightMargin= margin; 6070 bottomMargin = margin; 6071 } else { 6072 leftMargin = a.getDimensionPixelSize( 6073 R.styleable.ViewGroup_MarginLayout_layout_marginLeft, 6074 UNDEFINED_MARGIN); 6075 if (leftMargin == UNDEFINED_MARGIN) { 6076 mMarginFlags |= LEFT_MARGIN_UNDEFINED_MASK; 6077 leftMargin = DEFAULT_MARGIN_RESOLVED; 6078 } 6079 rightMargin = a.getDimensionPixelSize( 6080 R.styleable.ViewGroup_MarginLayout_layout_marginRight, 6081 UNDEFINED_MARGIN); 6082 if (rightMargin == UNDEFINED_MARGIN) { 6083 mMarginFlags |= RIGHT_MARGIN_UNDEFINED_MASK; 6084 rightMargin = DEFAULT_MARGIN_RESOLVED; 6085 } 6086 6087 topMargin = a.getDimensionPixelSize( 6088 R.styleable.ViewGroup_MarginLayout_layout_marginTop, 6089 DEFAULT_MARGIN_RESOLVED); 6090 bottomMargin = a.getDimensionPixelSize( 6091 R.styleable.ViewGroup_MarginLayout_layout_marginBottom, 6092 DEFAULT_MARGIN_RESOLVED); 6093 6094 startMargin = a.getDimensionPixelSize( 6095 R.styleable.ViewGroup_MarginLayout_layout_marginStart, 6096 DEFAULT_MARGIN_RELATIVE); 6097 endMargin = a.getDimensionPixelSize( 6098 R.styleable.ViewGroup_MarginLayout_layout_marginEnd, 6099 DEFAULT_MARGIN_RELATIVE); 6100 6101 if (isMarginRelative()) { 6102 mMarginFlags |= NEED_RESOLUTION_MASK; 6103 } 6104 } 6105 6106 final boolean hasRtlSupport = c.getApplicationInfo().hasRtlSupport(); 6107 final int targetSdkVersion = c.getApplicationInfo().targetSdkVersion; 6108 if (targetSdkVersion < JELLY_BEAN_MR1 || !hasRtlSupport) { 6109 mMarginFlags |= RTL_COMPATIBILITY_MODE_MASK; 6110 } 6111 6112 // Layout direction is LTR by default 6113 mMarginFlags |= LAYOUT_DIRECTION_LTR; 6114 6115 a.recycle(); 6116 } 6117 6118 /** 6119 * {@inheritDoc} 6120 */ 6121 public MarginLayoutParams(int width, int height) { 6122 super(width, height); 6123 6124 mMarginFlags |= LEFT_MARGIN_UNDEFINED_MASK; 6125 mMarginFlags |= RIGHT_MARGIN_UNDEFINED_MASK; 6126 6127 mMarginFlags &= ~NEED_RESOLUTION_MASK; 6128 mMarginFlags &= ~RTL_COMPATIBILITY_MODE_MASK; 6129 } 6130 6131 /** 6132 * Copy constructor. Clones the width, height and margin values of the source. 6133 * 6134 * @param source The layout params to copy from. 6135 */ 6136 public MarginLayoutParams(MarginLayoutParams source) { 6137 this.width = source.width; 6138 this.height = source.height; 6139 6140 this.leftMargin = source.leftMargin; 6141 this.topMargin = source.topMargin; 6142 this.rightMargin = source.rightMargin; 6143 this.bottomMargin = source.bottomMargin; 6144 this.startMargin = source.startMargin; 6145 this.endMargin = source.endMargin; 6146 6147 this.mMarginFlags = source.mMarginFlags; 6148 } 6149 6150 /** 6151 * {@inheritDoc} 6152 */ 6153 public MarginLayoutParams(LayoutParams source) { 6154 super(source); 6155 6156 mMarginFlags |= LEFT_MARGIN_UNDEFINED_MASK; 6157 mMarginFlags |= RIGHT_MARGIN_UNDEFINED_MASK; 6158 6159 mMarginFlags &= ~NEED_RESOLUTION_MASK; 6160 mMarginFlags &= ~RTL_COMPATIBILITY_MODE_MASK; 6161 } 6162 6163 /** 6164 * Sets the margins, in pixels. A call to {@link android.view.View#requestLayout()} needs 6165 * to be done so that the new margins are taken into account. Left and right margins may be 6166 * overriden by {@link android.view.View#requestLayout()} depending on layout direction. 6167 * 6168 * @param left the left margin size 6169 * @param top the top margin size 6170 * @param right the right margin size 6171 * @param bottom the bottom margin size 6172 * 6173 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginLeft 6174 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 6175 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginRight 6176 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 6177 */ 6178 public void setMargins(int left, int top, int right, int bottom) { 6179 leftMargin = left; 6180 topMargin = top; 6181 rightMargin = right; 6182 bottomMargin = bottom; 6183 mMarginFlags &= ~LEFT_MARGIN_UNDEFINED_MASK; 6184 mMarginFlags &= ~RIGHT_MARGIN_UNDEFINED_MASK; 6185 if (isMarginRelative()) { 6186 mMarginFlags |= NEED_RESOLUTION_MASK; 6187 } else { 6188 mMarginFlags &= ~NEED_RESOLUTION_MASK; 6189 } 6190 } 6191 6192 /** 6193 * Sets the relative margins, in pixels. A call to {@link android.view.View#requestLayout()} 6194 * needs to be done so that the new relative margins are taken into account. Left and right 6195 * margins may be overriden by {@link android.view.View#requestLayout()} depending on layout 6196 * direction. 6197 * 6198 * @param start the start margin size 6199 * @param top the top margin size 6200 * @param end the right margin size 6201 * @param bottom the bottom margin size 6202 * 6203 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 6204 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginTop 6205 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 6206 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginBottom 6207 * 6208 * @hide 6209 */ 6210 public void setMarginsRelative(int start, int top, int end, int bottom) { 6211 startMargin = start; 6212 topMargin = top; 6213 endMargin = end; 6214 bottomMargin = bottom; 6215 mMarginFlags |= NEED_RESOLUTION_MASK; 6216 } 6217 6218 /** 6219 * Sets the relative start margin. 6220 * 6221 * @param start the start margin size 6222 * 6223 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 6224 */ 6225 public void setMarginStart(int start) { 6226 startMargin = start; 6227 mMarginFlags |= NEED_RESOLUTION_MASK; 6228 } 6229 6230 /** 6231 * Returns the start margin in pixels. 6232 * 6233 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 6234 * 6235 * @return the start margin in pixels. 6236 */ 6237 public int getMarginStart() { 6238 if (startMargin != DEFAULT_MARGIN_RELATIVE) return startMargin; 6239 if ((mMarginFlags & NEED_RESOLUTION_MASK) == NEED_RESOLUTION_MASK) { 6240 doResolveMargins(); 6241 } 6242 switch(mMarginFlags & LAYOUT_DIRECTION_MASK) { 6243 case View.LAYOUT_DIRECTION_RTL: 6244 return rightMargin; 6245 case View.LAYOUT_DIRECTION_LTR: 6246 default: 6247 return leftMargin; 6248 } 6249 } 6250 6251 /** 6252 * Sets the relative end margin. 6253 * 6254 * @param end the end margin size 6255 * 6256 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 6257 */ 6258 public void setMarginEnd(int end) { 6259 endMargin = end; 6260 mMarginFlags |= NEED_RESOLUTION_MASK; 6261 } 6262 6263 /** 6264 * Returns the end margin in pixels. 6265 * 6266 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 6267 * 6268 * @return the end margin in pixels. 6269 */ 6270 public int getMarginEnd() { 6271 if (endMargin != DEFAULT_MARGIN_RELATIVE) return endMargin; 6272 if ((mMarginFlags & NEED_RESOLUTION_MASK) == NEED_RESOLUTION_MASK) { 6273 doResolveMargins(); 6274 } 6275 switch(mMarginFlags & LAYOUT_DIRECTION_MASK) { 6276 case View.LAYOUT_DIRECTION_RTL: 6277 return leftMargin; 6278 case View.LAYOUT_DIRECTION_LTR: 6279 default: 6280 return rightMargin; 6281 } 6282 } 6283 6284 /** 6285 * Check if margins are relative. 6286 * 6287 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginStart 6288 * @attr ref android.R.styleable#ViewGroup_MarginLayout_layout_marginEnd 6289 * 6290 * @return true if either marginStart or marginEnd has been set. 6291 */ 6292 public boolean isMarginRelative() { 6293 return (startMargin != DEFAULT_MARGIN_RELATIVE || endMargin != DEFAULT_MARGIN_RELATIVE); 6294 } 6295 6296 /** 6297 * Set the layout direction 6298 * @param layoutDirection the layout direction. 6299 * Should be either {@link View#LAYOUT_DIRECTION_LTR} 6300 * or {@link View#LAYOUT_DIRECTION_RTL}. 6301 */ 6302 public void setLayoutDirection(int layoutDirection) { 6303 if (layoutDirection != View.LAYOUT_DIRECTION_LTR && 6304 layoutDirection != View.LAYOUT_DIRECTION_RTL) return; 6305 if (layoutDirection != (mMarginFlags & LAYOUT_DIRECTION_MASK)) { 6306 mMarginFlags &= ~LAYOUT_DIRECTION_MASK; 6307 mMarginFlags |= (layoutDirection & LAYOUT_DIRECTION_MASK); 6308 if (isMarginRelative()) { 6309 mMarginFlags |= NEED_RESOLUTION_MASK; 6310 } else { 6311 mMarginFlags &= ~NEED_RESOLUTION_MASK; 6312 } 6313 } 6314 } 6315 6316 /** 6317 * Retuns the layout direction. Can be either {@link View#LAYOUT_DIRECTION_LTR} or 6318 * {@link View#LAYOUT_DIRECTION_RTL}. 6319 * 6320 * @return the layout direction. 6321 */ 6322 public int getLayoutDirection() { 6323 return (mMarginFlags & LAYOUT_DIRECTION_MASK); 6324 } 6325 6326 /** 6327 * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins 6328 * may be overridden depending on layout direction. 6329 */ 6330 @Override 6331 public void resolveLayoutDirection(int layoutDirection) { 6332 setLayoutDirection(layoutDirection); 6333 6334 // No relative margin or pre JB-MR1 case or no need to resolve, just dont do anything 6335 // Will use the left and right margins if no relative margin is defined. 6336 if (!isMarginRelative() || 6337 (mMarginFlags & NEED_RESOLUTION_MASK) != NEED_RESOLUTION_MASK) return; 6338 6339 // Proceed with resolution 6340 doResolveMargins(); 6341 } 6342 6343 private void doResolveMargins() { 6344 if ((mMarginFlags & RTL_COMPATIBILITY_MODE_MASK) == RTL_COMPATIBILITY_MODE_MASK) { 6345 // if left or right margins are not defined and if we have some start or end margin 6346 // defined then use those start and end margins. 6347 if ((mMarginFlags & LEFT_MARGIN_UNDEFINED_MASK) == LEFT_MARGIN_UNDEFINED_MASK 6348 && startMargin > DEFAULT_MARGIN_RELATIVE) { 6349 leftMargin = startMargin; 6350 } 6351 if ((mMarginFlags & RIGHT_MARGIN_UNDEFINED_MASK) == RIGHT_MARGIN_UNDEFINED_MASK 6352 && endMargin > DEFAULT_MARGIN_RELATIVE) { 6353 rightMargin = endMargin; 6354 } 6355 } else { 6356 // We have some relative margins (either the start one or the end one or both). So use 6357 // them and override what has been defined for left and right margins. If either start 6358 // or end margin is not defined, just set it to default "0". 6359 switch(mMarginFlags & LAYOUT_DIRECTION_MASK) { 6360 case View.LAYOUT_DIRECTION_RTL: 6361 leftMargin = (endMargin > DEFAULT_MARGIN_RELATIVE) ? 6362 endMargin : DEFAULT_MARGIN_RESOLVED; 6363 rightMargin = (startMargin > DEFAULT_MARGIN_RELATIVE) ? 6364 startMargin : DEFAULT_MARGIN_RESOLVED; 6365 break; 6366 case View.LAYOUT_DIRECTION_LTR: 6367 default: 6368 leftMargin = (startMargin > DEFAULT_MARGIN_RELATIVE) ? 6369 startMargin : DEFAULT_MARGIN_RESOLVED; 6370 rightMargin = (endMargin > DEFAULT_MARGIN_RELATIVE) ? 6371 endMargin : DEFAULT_MARGIN_RESOLVED; 6372 break; 6373 } 6374 } 6375 mMarginFlags &= ~NEED_RESOLUTION_MASK; 6376 } 6377 6378 /** 6379 * @hide 6380 */ 6381 public boolean isLayoutRtl() { 6382 return ((mMarginFlags & LAYOUT_DIRECTION_MASK) == View.LAYOUT_DIRECTION_RTL); 6383 } 6384 6385 /** 6386 * @hide 6387 */ 6388 @Override 6389 public void onDebugDraw(View view, Canvas canvas, Paint paint) { 6390 Insets oi = isLayoutModeOptical(view.mParent) ? view.getOpticalInsets() : Insets.NONE; 6391 6392 fillDifference(canvas, 6393 view.getLeft() + oi.left, 6394 view.getTop() + oi.top, 6395 view.getRight() - oi.right, 6396 view.getBottom() - oi.bottom, 6397 leftMargin, 6398 topMargin, 6399 rightMargin, 6400 bottomMargin, 6401 paint); 6402 } 6403 } 6404 6405 /* Describes a touched view and the ids of the pointers that it has captured. 6406 * 6407 * This code assumes that pointer ids are always in the range 0..31 such that 6408 * it can use a bitfield to track which pointer ids are present. 6409 * As it happens, the lower layers of the input dispatch pipeline also use the 6410 * same trick so the assumption should be safe here... 6411 */ 6412 private static final class TouchTarget { 6413 private static final int MAX_RECYCLED = 32; 6414 private static final Object sRecycleLock = new Object(); 6415 private static TouchTarget sRecycleBin; 6416 private static int sRecycledCount; 6417 6418 public static final int ALL_POINTER_IDS = -1; // all ones 6419 6420 // The touched child view. 6421 public View child; 6422 6423 // The combined bit mask of pointer ids for all pointers captured by the target. 6424 public int pointerIdBits; 6425 6426 // The next target in the target list. 6427 public TouchTarget next; 6428 6429 private TouchTarget() { 6430 } 6431 6432 public static TouchTarget obtain(View child, int pointerIdBits) { 6433 final TouchTarget target; 6434 synchronized (sRecycleLock) { 6435 if (sRecycleBin == null) { 6436 target = new TouchTarget(); 6437 } else { 6438 target = sRecycleBin; 6439 sRecycleBin = target.next; 6440 sRecycledCount--; 6441 target.next = null; 6442 } 6443 } 6444 target.child = child; 6445 target.pointerIdBits = pointerIdBits; 6446 return target; 6447 } 6448 6449 public void recycle() { 6450 synchronized (sRecycleLock) { 6451 if (sRecycledCount < MAX_RECYCLED) { 6452 next = sRecycleBin; 6453 sRecycleBin = this; 6454 sRecycledCount += 1; 6455 } else { 6456 next = null; 6457 } 6458 child = null; 6459 } 6460 } 6461 } 6462 6463 /* Describes a hovered view. */ 6464 private static final class HoverTarget { 6465 private static final int MAX_RECYCLED = 32; 6466 private static final Object sRecycleLock = new Object(); 6467 private static HoverTarget sRecycleBin; 6468 private static int sRecycledCount; 6469 6470 // The hovered child view. 6471 public View child; 6472 6473 // The next target in the target list. 6474 public HoverTarget next; 6475 6476 private HoverTarget() { 6477 } 6478 6479 public static HoverTarget obtain(View child) { 6480 final HoverTarget target; 6481 synchronized (sRecycleLock) { 6482 if (sRecycleBin == null) { 6483 target = new HoverTarget(); 6484 } else { 6485 target = sRecycleBin; 6486 sRecycleBin = target.next; 6487 sRecycledCount--; 6488 target.next = null; 6489 } 6490 } 6491 target.child = child; 6492 return target; 6493 } 6494 6495 public void recycle() { 6496 synchronized (sRecycleLock) { 6497 if (sRecycledCount < MAX_RECYCLED) { 6498 next = sRecycleBin; 6499 sRecycleBin = this; 6500 sRecycledCount += 1; 6501 } else { 6502 next = null; 6503 } 6504 child = null; 6505 } 6506 } 6507 } 6508 6509 /** 6510 * Pooled class that orderes the children of a ViewGroup from start 6511 * to end based on how they are laid out and the layout direction. 6512 */ 6513 static class ChildListForAccessibility { 6514 6515 private static final int MAX_POOL_SIZE = 32; 6516 6517 private static final SynchronizedPool<ChildListForAccessibility> sPool = 6518 new SynchronizedPool<ChildListForAccessibility>(MAX_POOL_SIZE); 6519 6520 private final ArrayList<View> mChildren = new ArrayList<View>(); 6521 6522 private final ArrayList<ViewLocationHolder> mHolders = new ArrayList<ViewLocationHolder>(); 6523 6524 public static ChildListForAccessibility obtain(ViewGroup parent, boolean sort) { 6525 ChildListForAccessibility list = sPool.acquire(); 6526 if (list == null) { 6527 list = new ChildListForAccessibility(); 6528 } 6529 list.init(parent, sort); 6530 return list; 6531 } 6532 6533 public void recycle() { 6534 clear(); 6535 sPool.release(this); 6536 } 6537 6538 public int getChildCount() { 6539 return mChildren.size(); 6540 } 6541 6542 public View getChildAt(int index) { 6543 return mChildren.get(index); 6544 } 6545 6546 public int getChildIndex(View child) { 6547 return mChildren.indexOf(child); 6548 } 6549 6550 private void init(ViewGroup parent, boolean sort) { 6551 ArrayList<View> children = mChildren; 6552 final int childCount = parent.getChildCount(); 6553 for (int i = 0; i < childCount; i++) { 6554 View child = parent.getChildAt(i); 6555 children.add(child); 6556 } 6557 if (sort) { 6558 ArrayList<ViewLocationHolder> holders = mHolders; 6559 for (int i = 0; i < childCount; i++) { 6560 View child = children.get(i); 6561 ViewLocationHolder holder = ViewLocationHolder.obtain(parent, child); 6562 holders.add(holder); 6563 } 6564 Collections.sort(holders); 6565 for (int i = 0; i < childCount; i++) { 6566 ViewLocationHolder holder = holders.get(i); 6567 children.set(i, holder.mView); 6568 holder.recycle(); 6569 } 6570 holders.clear(); 6571 } 6572 } 6573 6574 private void clear() { 6575 mChildren.clear(); 6576 } 6577 } 6578 6579 /** 6580 * Pooled class that holds a View and its location with respect to 6581 * a specified root. This enables sorting of views based on their 6582 * coordinates without recomputing the position relative to the root 6583 * on every comparison. 6584 */ 6585 static class ViewLocationHolder implements Comparable<ViewLocationHolder> { 6586 6587 private static final int MAX_POOL_SIZE = 32; 6588 6589 private static final SynchronizedPool<ViewLocationHolder> sPool = 6590 new SynchronizedPool<ViewLocationHolder>(MAX_POOL_SIZE); 6591 6592 private final Rect mLocation = new Rect(); 6593 6594 public View mView; 6595 6596 private int mLayoutDirection; 6597 6598 public static ViewLocationHolder obtain(ViewGroup root, View view) { 6599 ViewLocationHolder holder = sPool.acquire(); 6600 if (holder == null) { 6601 holder = new ViewLocationHolder(); 6602 } 6603 holder.init(root, view); 6604 return holder; 6605 } 6606 6607 public void recycle() { 6608 clear(); 6609 sPool.release(this); 6610 } 6611 6612 @Override 6613 public int compareTo(ViewLocationHolder another) { 6614 // This instance is greater than an invalid argument. 6615 if (another == null) { 6616 return 1; 6617 } 6618 if (getClass() != another.getClass()) { 6619 return 1; 6620 } 6621 // First is above second. 6622 if (mLocation.bottom - another.mLocation.top <= 0) { 6623 return -1; 6624 } 6625 // First is below second. 6626 if (mLocation.top - another.mLocation.bottom >= 0) { 6627 return 1; 6628 } 6629 // LTR 6630 if (mLayoutDirection == LAYOUT_DIRECTION_LTR) { 6631 final int leftDifference = mLocation.left - another.mLocation.left; 6632 // First more to the left than second. 6633 if (leftDifference != 0) { 6634 return leftDifference; 6635 } 6636 } else { // RTL 6637 final int rightDifference = mLocation.right - another.mLocation.right; 6638 // First more to the right than second. 6639 if (rightDifference != 0) { 6640 return -rightDifference; 6641 } 6642 } 6643 // Break tie by top. 6644 final int topDiference = mLocation.top - another.mLocation.top; 6645 if (topDiference != 0) { 6646 return topDiference; 6647 } 6648 // Break tie by height. 6649 final int heightDiference = mLocation.height() - another.mLocation.height(); 6650 if (heightDiference != 0) { 6651 return -heightDiference; 6652 } 6653 // Break tie by width. 6654 final int widthDiference = mLocation.width() - another.mLocation.width(); 6655 if (widthDiference != 0) { 6656 return -widthDiference; 6657 } 6658 // Just break the tie somehow. The accessibliity ids are unique 6659 // and stable, hence this is deterministic tie breaking. 6660 return mView.getAccessibilityViewId() - another.mView.getAccessibilityViewId(); 6661 } 6662 6663 private void init(ViewGroup root, View view) { 6664 Rect viewLocation = mLocation; 6665 view.getDrawingRect(viewLocation); 6666 root.offsetDescendantRectToMyCoords(view, viewLocation); 6667 mView = view; 6668 mLayoutDirection = root.getLayoutDirection(); 6669 } 6670 6671 private void clear() { 6672 mView = null; 6673 mLocation.set(0, 0, 0, 0); 6674 } 6675 } 6676 6677 private static Paint getDebugPaint() { 6678 if (sDebugPaint == null) { 6679 sDebugPaint = new Paint(); 6680 sDebugPaint.setAntiAlias(false); 6681 } 6682 return sDebugPaint; 6683 } 6684 6685 private void drawRect(Canvas canvas, Paint paint, int x1, int y1, int x2, int y2) { 6686 if (sDebugLines== null) { 6687 sDebugLines = new float[16]; 6688 } 6689 6690 sDebugLines[0] = x1; 6691 sDebugLines[1] = y1; 6692 sDebugLines[2] = x2; 6693 sDebugLines[3] = y1; 6694 6695 sDebugLines[4] = x2; 6696 sDebugLines[5] = y1; 6697 sDebugLines[6] = x2; 6698 sDebugLines[7] = y2; 6699 6700 sDebugLines[8] = x2; 6701 sDebugLines[9] = y2; 6702 sDebugLines[10] = x1; 6703 sDebugLines[11] = y2; 6704 6705 sDebugLines[12] = x1; 6706 sDebugLines[13] = y2; 6707 sDebugLines[14] = x1; 6708 sDebugLines[15] = y1; 6709 6710 canvas.drawLines(sDebugLines, paint); 6711 } 6712} 6713