RecyclerView.java revision 8f1039d92fe21e2c8a94712ce94777c09b38d407
1/* 2 * Copyright (C) 2013 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 17 18package android.support.v7.widget; 19 20import static android.support.annotation.RestrictTo.Scope.LIBRARY_GROUP; 21 22import android.content.Context; 23import android.content.res.TypedArray; 24import android.database.Observable; 25import android.graphics.Canvas; 26import android.graphics.Matrix; 27import android.graphics.PointF; 28import android.graphics.Rect; 29import android.graphics.RectF; 30import android.os.Build; 31import android.os.Bundle; 32import android.os.Parcel; 33import android.os.Parcelable; 34import android.os.SystemClock; 35import android.support.annotation.CallSuper; 36import android.support.annotation.IntDef; 37import android.support.annotation.NonNull; 38import android.support.annotation.Nullable; 39import android.support.annotation.RestrictTo; 40import android.support.annotation.VisibleForTesting; 41import android.support.v4.os.ParcelableCompat; 42import android.support.v4.os.ParcelableCompatCreatorCallbacks; 43import android.support.v4.os.TraceCompat; 44import android.support.v4.view.AbsSavedState; 45import android.support.v4.view.InputDeviceCompat; 46import android.support.v4.view.MotionEventCompat; 47import android.support.v4.view.NestedScrollingChild; 48import android.support.v4.view.NestedScrollingChildHelper; 49import android.support.v4.view.ScrollingView; 50import android.support.v4.view.VelocityTrackerCompat; 51import android.support.v4.view.ViewCompat; 52import android.support.v4.view.accessibility.AccessibilityEventCompat; 53import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat; 54import android.support.v4.view.accessibility.AccessibilityRecordCompat; 55import android.support.v4.widget.EdgeEffectCompat; 56import android.support.v4.widget.ScrollerCompat; 57import android.support.v7.recyclerview.R; 58import android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo; 59import android.util.AttributeSet; 60import android.util.Log; 61import android.util.SparseArray; 62import android.util.TypedValue; 63import android.view.Display; 64import android.view.FocusFinder; 65import android.view.MotionEvent; 66import android.view.VelocityTracker; 67import android.view.View; 68import android.view.ViewConfiguration; 69import android.view.ViewGroup; 70import android.view.ViewParent; 71import android.view.accessibility.AccessibilityEvent; 72import android.view.accessibility.AccessibilityManager; 73import android.view.animation.Interpolator; 74 75import java.lang.annotation.Retention; 76import java.lang.annotation.RetentionPolicy; 77import java.lang.ref.WeakReference; 78import java.lang.reflect.Constructor; 79import java.lang.reflect.InvocationTargetException; 80import java.util.ArrayList; 81import java.util.Collections; 82import java.util.List; 83 84/** 85 * A flexible view for providing a limited window into a large data set. 86 * 87 * <h3>Glossary of terms:</h3> 88 * 89 * <ul> 90 * <li><em>Adapter:</em> A subclass of {@link Adapter} responsible for providing views 91 * that represent items in a data set.</li> 92 * <li><em>Position:</em> The position of a data item within an <em>Adapter</em>.</li> 93 * <li><em>Index:</em> The index of an attached child view as used in a call to 94 * {@link ViewGroup#getChildAt}. Contrast with <em>Position.</em></li> 95 * <li><em>Binding:</em> The process of preparing a child view to display data corresponding 96 * to a <em>position</em> within the adapter.</li> 97 * <li><em>Recycle (view):</em> A view previously used to display data for a specific adapter 98 * position may be placed in a cache for later reuse to display the same type of data again 99 * later. This can drastically improve performance by skipping initial layout inflation 100 * or construction.</li> 101 * <li><em>Scrap (view):</em> A child view that has entered into a temporarily detached 102 * state during layout. Scrap views may be reused without becoming fully detached 103 * from the parent RecyclerView, either unmodified if no rebinding is required or modified 104 * by the adapter if the view was considered <em>dirty</em>.</li> 105 * <li><em>Dirty (view):</em> A child view that must be rebound by the adapter before 106 * being displayed.</li> 107 * </ul> 108 * 109 * <h4>Positions in RecyclerView:</h4> 110 * <p> 111 * RecyclerView introduces an additional level of abstraction between the {@link Adapter} and 112 * {@link LayoutManager} to be able to detect data set changes in batches during a layout 113 * calculation. This saves LayoutManager from tracking adapter changes to calculate animations. 114 * It also helps with performance because all view bindings happen at the same time and unnecessary 115 * bindings are avoided. 116 * <p> 117 * For this reason, there are two types of <code>position</code> related methods in RecyclerView: 118 * <ul> 119 * <li>layout position: Position of an item in the latest layout calculation. This is the 120 * position from the LayoutManager's perspective.</li> 121 * <li>adapter position: Position of an item in the adapter. This is the position from 122 * the Adapter's perspective.</li> 123 * </ul> 124 * <p> 125 * These two positions are the same except the time between dispatching <code>adapter.notify* 126 * </code> events and calculating the updated layout. 127 * <p> 128 * Methods that return or receive <code>*LayoutPosition*</code> use position as of the latest 129 * layout calculation (e.g. {@link ViewHolder#getLayoutPosition()}, 130 * {@link #findViewHolderForLayoutPosition(int)}). These positions include all changes until the 131 * last layout calculation. You can rely on these positions to be consistent with what user is 132 * currently seeing on the screen. For example, if you have a list of items on the screen and user 133 * asks for the 5<sup>th</sup> element, you should use these methods as they'll match what user 134 * is seeing. 135 * <p> 136 * The other set of position related methods are in the form of 137 * <code>*AdapterPosition*</code>. (e.g. {@link ViewHolder#getAdapterPosition()}, 138 * {@link #findViewHolderForAdapterPosition(int)}) You should use these methods when you need to 139 * work with up-to-date adapter positions even if they may not have been reflected to layout yet. 140 * For example, if you want to access the item in the adapter on a ViewHolder click, you should use 141 * {@link ViewHolder#getAdapterPosition()}. Beware that these methods may not be able to calculate 142 * adapter positions if {@link Adapter#notifyDataSetChanged()} has been called and new layout has 143 * not yet been calculated. For this reasons, you should carefully handle {@link #NO_POSITION} or 144 * <code>null</code> results from these methods. 145 * <p> 146 * When writing a {@link LayoutManager} you almost always want to use layout positions whereas when 147 * writing an {@link Adapter}, you probably want to use adapter positions. 148 * 149 * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_layoutManager 150 */ 151public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild { 152 153 static final String TAG = "RecyclerView"; 154 155 static final boolean DEBUG = false; 156 157 private static final int[] NESTED_SCROLLING_ATTRS 158 = {16843830 /* android.R.attr.nestedScrollingEnabled */}; 159 160 private static final int[] CLIP_TO_PADDING_ATTR = {android.R.attr.clipToPadding}; 161 162 /** 163 * On Kitkat and JB MR2, there is a bug which prevents DisplayList from being invalidated if 164 * a View is two levels deep(wrt to ViewHolder.itemView). DisplayList can be invalidated by 165 * setting View's visibility to INVISIBLE when View is detached. On Kitkat and JB MR2, Recycler 166 * recursively traverses itemView and invalidates display list for each ViewGroup that matches 167 * this criteria. 168 */ 169 static final boolean FORCE_INVALIDATE_DISPLAY_LIST = Build.VERSION.SDK_INT == 18 170 || Build.VERSION.SDK_INT == 19 || Build.VERSION.SDK_INT == 20; 171 /** 172 * On M+, an unspecified measure spec may include a hint which we can use. On older platforms, 173 * this value might be garbage. To save LayoutManagers from it, RecyclerView sets the size to 174 * 0 when mode is unspecified. 175 */ 176 static final boolean ALLOW_SIZE_IN_UNSPECIFIED_SPEC = Build.VERSION.SDK_INT >= 23; 177 178 static final boolean POST_UPDATES_ON_ANIMATION = Build.VERSION.SDK_INT >= 16; 179 180 /** 181 * On L+, with RenderThread, the UI thread has idle time after it has passed a frame off to 182 * RenderThread but before the next frame begins. We schedule prefetch work in this window. 183 */ 184 private static final boolean ALLOW_THREAD_GAP_WORK = Build.VERSION.SDK_INT >= 21; 185 186 /** 187 * FocusFinder#findNextFocus is broken on ICS MR1 and older for View.FOCUS_BACKWARD direction. 188 * We convert it to an absolute direction such as FOCUS_DOWN or FOCUS_LEFT. 189 */ 190 private static final boolean FORCE_ABS_FOCUS_SEARCH_DIRECTION = Build.VERSION.SDK_INT <= 15; 191 192 /** 193 * on API 15-, a focused child can still be considered a focused child of RV even after 194 * it's being removed or its focusable flag is set to false. This is because when this focused 195 * child is detached, the reference to this child is not removed in clearFocus. API 16 and above 196 * properly handle this case by calling ensureInputFocusOnFirstFocusable or rootViewRequestFocus 197 * to request focus on a new child, which will clear the focus on the old (detached) child as a 198 * side-effect. 199 */ 200 private static final boolean IGNORE_DETACHED_FOCUSED_CHILD = Build.VERSION.SDK_INT <= 15; 201 202 static final boolean DISPATCH_TEMP_DETACH = false; 203 public static final int HORIZONTAL = 0; 204 public static final int VERTICAL = 1; 205 206 public static final int NO_POSITION = -1; 207 public static final long NO_ID = -1; 208 public static final int INVALID_TYPE = -1; 209 210 /** 211 * Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates 212 * that the RecyclerView should use the standard touch slop for smooth, 213 * continuous scrolling. 214 */ 215 public static final int TOUCH_SLOP_DEFAULT = 0; 216 217 /** 218 * Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates 219 * that the RecyclerView should use the standard touch slop for scrolling 220 * widgets that snap to a page or other coarse-grained barrier. 221 */ 222 public static final int TOUCH_SLOP_PAGING = 1; 223 224 static final int MAX_SCROLL_DURATION = 2000; 225 226 /** 227 * RecyclerView is calculating a scroll. 228 * If there are too many of these in Systrace, some Views inside RecyclerView might be causing 229 * it. Try to avoid using EditText, focusable views or handle them with care. 230 */ 231 static final String TRACE_SCROLL_TAG = "RV Scroll"; 232 233 /** 234 * OnLayout has been called by the View system. 235 * If this shows up too many times in Systrace, make sure the children of RecyclerView do not 236 * update themselves directly. This will cause a full re-layout but when it happens via the 237 * Adapter notifyItemChanged, RecyclerView can avoid full layout calculation. 238 */ 239 private static final String TRACE_ON_LAYOUT_TAG = "RV OnLayout"; 240 241 /** 242 * NotifyDataSetChanged or equal has been called. 243 * If this is taking a long time, try sending granular notify adapter changes instead of just 244 * calling notifyDataSetChanged or setAdapter / swapAdapter. Adding stable ids to your adapter 245 * might help. 246 */ 247 private static final String TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG = "RV FullInvalidate"; 248 249 /** 250 * RecyclerView is doing a layout for partial adapter updates (we know what has changed) 251 * If this is taking a long time, you may have dispatched too many Adapter updates causing too 252 * many Views being rebind. Make sure all are necessary and also prefer using notify*Range 253 * methods. 254 */ 255 private static final String TRACE_HANDLE_ADAPTER_UPDATES_TAG = "RV PartialInvalidate"; 256 257 /** 258 * RecyclerView is rebinding a View. 259 * If this is taking a lot of time, consider optimizing your layout or make sure you are not 260 * doing extra operations in onBindViewHolder call. 261 */ 262 static final String TRACE_BIND_VIEW_TAG = "RV OnBindView"; 263 264 /** 265 * RecyclerView is attempting to pre-populate off screen views. 266 */ 267 static final String TRACE_PREFETCH_TAG = "RV Prefetch"; 268 269 /** 270 * RecyclerView is attempting to pre-populate off screen itemviews within an off screen 271 * RecyclerView. 272 */ 273 static final String TRACE_NESTED_PREFETCH_TAG = "RV Nested Prefetch"; 274 275 /** 276 * RecyclerView is creating a new View. 277 * If too many of these present in Systrace: 278 * - There might be a problem in Recycling (e.g. custom Animations that set transient state and 279 * prevent recycling or ItemAnimator not implementing the contract properly. ({@link 280 * > Adapter#onFailedToRecycleView(ViewHolder)}) 281 * 282 * - There might be too many item view types. 283 * > Try merging them 284 * 285 * - There might be too many itemChange animations and not enough space in RecyclerPool. 286 * >Try increasing your pool size and item cache size. 287 */ 288 static final String TRACE_CREATE_VIEW_TAG = "RV CreateView"; 289 private static final Class<?>[] LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE = 290 new Class[]{Context.class, AttributeSet.class, int.class, int.class}; 291 292 private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver(); 293 294 final Recycler mRecycler = new Recycler(); 295 296 private SavedState mPendingSavedState; 297 298 /** 299 * Handles adapter updates 300 */ 301 AdapterHelper mAdapterHelper; 302 303 /** 304 * Handles abstraction between LayoutManager children and RecyclerView children 305 */ 306 ChildHelper mChildHelper; 307 308 /** 309 * Keeps data about views to be used for animations 310 */ 311 final ViewInfoStore mViewInfoStore = new ViewInfoStore(); 312 313 /** 314 * Prior to L, there is no way to query this variable which is why we override the setter and 315 * track it here. 316 */ 317 boolean mClipToPadding; 318 319 /** 320 * Note: this Runnable is only ever posted if: 321 * 1) We've been through first layout 322 * 2) We know we have a fixed size (mHasFixedSize) 323 * 3) We're attached 324 */ 325 final Runnable mUpdateChildViewsRunnable = new Runnable() { 326 @Override 327 public void run() { 328 if (!mFirstLayoutComplete || isLayoutRequested()) { 329 // a layout request will happen, we should not do layout here. 330 return; 331 } 332 if (!mIsAttached) { 333 requestLayout(); 334 // if we are not attached yet, mark us as requiring layout and skip 335 return; 336 } 337 if (mLayoutFrozen) { 338 mLayoutRequestEaten = true; 339 return; //we'll process updates when ice age ends. 340 } 341 consumePendingUpdateOperations(); 342 } 343 }; 344 345 final Rect mTempRect = new Rect(); 346 private final Rect mTempRect2 = new Rect(); 347 final RectF mTempRectF = new RectF(); 348 Adapter mAdapter; 349 @VisibleForTesting LayoutManager mLayout; 350 RecyclerListener mRecyclerListener; 351 final ArrayList<ItemDecoration> mItemDecorations = new ArrayList<>(); 352 private final ArrayList<OnItemTouchListener> mOnItemTouchListeners = 353 new ArrayList<>(); 354 private OnItemTouchListener mActiveOnItemTouchListener; 355 boolean mIsAttached; 356 boolean mHasFixedSize; 357 @VisibleForTesting boolean mFirstLayoutComplete; 358 359 // Counting lock to control whether we should ignore requestLayout calls from children or not. 360 private int mEatRequestLayout = 0; 361 362 boolean mLayoutRequestEaten; 363 boolean mLayoutFrozen; 364 private boolean mIgnoreMotionEventTillDown; 365 366 // binary OR of change events that were eaten during a layout or scroll. 367 private int mEatenAccessibilityChangeFlags; 368 boolean mAdapterUpdateDuringMeasure; 369 370 private final AccessibilityManager mAccessibilityManager; 371 private List<OnChildAttachStateChangeListener> mOnChildAttachStateListeners; 372 373 /** 374 * Set to true when an adapter data set changed notification is received. 375 * In that case, we cannot run any animations since we don't know what happened until layout. 376 * 377 * Attached items are invalid until next layout, at which point layout will animate/replace 378 * items as necessary, building up content from the (effectively) new adapter from scratch. 379 * 380 * Cached items must be discarded when setting this to true, so that the cache may be freely 381 * used by prefetching until the next layout occurs. 382 * 383 * @see #setDataSetChangedAfterLayout() 384 */ 385 boolean mDataSetHasChangedAfterLayout = false; 386 387 /** 388 * This variable is incremented during a dispatchLayout and/or scroll. 389 * Some methods should not be called during these periods (e.g. adapter data change). 390 * Doing so will create hard to find bugs so we better check it and throw an exception. 391 * 392 * @see #assertInLayoutOrScroll(String) 393 * @see #assertNotInLayoutOrScroll(String) 394 */ 395 private int mLayoutOrScrollCounter = 0; 396 397 /** 398 * Similar to mLayoutOrScrollCounter but logs a warning instead of throwing an exception 399 * (for API compatibility). 400 * <p> 401 * It is a bad practice for a developer to update the data in a scroll callback since it is 402 * potentially called during a layout. 403 */ 404 private int mDispatchScrollCounter = 0; 405 406 private EdgeEffectCompat mLeftGlow, mTopGlow, mRightGlow, mBottomGlow; 407 408 ItemAnimator mItemAnimator = new DefaultItemAnimator(); 409 410 private static final int INVALID_POINTER = -1; 411 412 /** 413 * The RecyclerView is not currently scrolling. 414 * @see #getScrollState() 415 */ 416 public static final int SCROLL_STATE_IDLE = 0; 417 418 /** 419 * The RecyclerView is currently being dragged by outside input such as user touch input. 420 * @see #getScrollState() 421 */ 422 public static final int SCROLL_STATE_DRAGGING = 1; 423 424 /** 425 * The RecyclerView is currently animating to a final position while not under 426 * outside control. 427 * @see #getScrollState() 428 */ 429 public static final int SCROLL_STATE_SETTLING = 2; 430 431 static final long FOREVER_NS = Long.MAX_VALUE; 432 433 // Touch/scrolling handling 434 435 private int mScrollState = SCROLL_STATE_IDLE; 436 private int mScrollPointerId = INVALID_POINTER; 437 private VelocityTracker mVelocityTracker; 438 private int mInitialTouchX; 439 private int mInitialTouchY; 440 private int mLastTouchX; 441 private int mLastTouchY; 442 private int mTouchSlop; 443 private OnFlingListener mOnFlingListener; 444 private final int mMinFlingVelocity; 445 private final int mMaxFlingVelocity; 446 // This value is used when handling generic motion events. 447 private float mScrollFactor = Float.MIN_VALUE; 448 private boolean mPreserveFocusAfterLayout = true; 449 450 final ViewFlinger mViewFlinger = new ViewFlinger(); 451 452 GapWorker mGapWorker; 453 GapWorker.LayoutPrefetchRegistryImpl mPrefetchRegistry = 454 ALLOW_THREAD_GAP_WORK ? new GapWorker.LayoutPrefetchRegistryImpl() : null; 455 456 final State mState = new State(); 457 458 private OnScrollListener mScrollListener; 459 private List<OnScrollListener> mScrollListeners; 460 461 // For use in item animations 462 boolean mItemsAddedOrRemoved = false; 463 boolean mItemsChanged = false; 464 private ItemAnimator.ItemAnimatorListener mItemAnimatorListener = 465 new ItemAnimatorRestoreListener(); 466 boolean mPostedAnimatorRunner = false; 467 RecyclerViewAccessibilityDelegate mAccessibilityDelegate; 468 private ChildDrawingOrderCallback mChildDrawingOrderCallback; 469 470 // simple array to keep min and max child position during a layout calculation 471 // preserved not to create a new one in each layout pass 472 private final int[] mMinMaxLayoutPositions = new int[2]; 473 474 private NestedScrollingChildHelper mScrollingChildHelper; 475 private final int[] mScrollOffset = new int[2]; 476 private final int[] mScrollConsumed = new int[2]; 477 private final int[] mNestedOffsets = new int[2]; 478 479 /** 480 * These are views that had their a11y importance changed during a layout. We defer these events 481 * until the end of the layout because a11y service may make sync calls back to the RV while 482 * the View's state is undefined. 483 */ 484 @VisibleForTesting 485 final List<ViewHolder> mPendingAccessibilityImportanceChange = new ArrayList(); 486 487 private Runnable mItemAnimatorRunner = new Runnable() { 488 @Override 489 public void run() { 490 if (mItemAnimator != null) { 491 mItemAnimator.runPendingAnimations(); 492 } 493 mPostedAnimatorRunner = false; 494 } 495 }; 496 497 static final Interpolator sQuinticInterpolator = new Interpolator() { 498 @Override 499 public float getInterpolation(float t) { 500 t -= 1.0f; 501 return t * t * t * t * t + 1.0f; 502 } 503 }; 504 505 /** 506 * The callback to convert view info diffs into animations. 507 */ 508 private final ViewInfoStore.ProcessCallback mViewInfoProcessCallback = 509 new ViewInfoStore.ProcessCallback() { 510 @Override 511 public void processDisappeared(ViewHolder viewHolder, @NonNull ItemHolderInfo info, 512 @Nullable ItemHolderInfo postInfo) { 513 mRecycler.unscrapView(viewHolder); 514 animateDisappearance(viewHolder, info, postInfo); 515 } 516 @Override 517 public void processAppeared(ViewHolder viewHolder, 518 ItemHolderInfo preInfo, ItemHolderInfo info) { 519 animateAppearance(viewHolder, preInfo, info); 520 } 521 522 @Override 523 public void processPersistent(ViewHolder viewHolder, 524 @NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo) { 525 viewHolder.setIsRecyclable(false); 526 if (mDataSetHasChangedAfterLayout) { 527 // since it was rebound, use change instead as we'll be mapping them from 528 // stable ids. If stable ids were false, we would not be running any 529 // animations 530 if (mItemAnimator.animateChange(viewHolder, viewHolder, preInfo, postInfo)) { 531 postAnimationRunner(); 532 } 533 } else if (mItemAnimator.animatePersistence(viewHolder, preInfo, postInfo)) { 534 postAnimationRunner(); 535 } 536 } 537 @Override 538 public void unused(ViewHolder viewHolder) { 539 mLayout.removeAndRecycleView(viewHolder.itemView, mRecycler); 540 } 541 }; 542 543 public RecyclerView(Context context) { 544 this(context, null); 545 } 546 547 public RecyclerView(Context context, @Nullable AttributeSet attrs) { 548 this(context, attrs, 0); 549 } 550 551 public RecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) { 552 super(context, attrs, defStyle); 553 if (attrs != null) { 554 TypedArray a = context.obtainStyledAttributes(attrs, CLIP_TO_PADDING_ATTR, defStyle, 0); 555 mClipToPadding = a.getBoolean(0, true); 556 a.recycle(); 557 } else { 558 mClipToPadding = true; 559 } 560 setScrollContainer(true); 561 setFocusableInTouchMode(true); 562 563 final ViewConfiguration vc = ViewConfiguration.get(context); 564 mTouchSlop = vc.getScaledTouchSlop(); 565 mMinFlingVelocity = vc.getScaledMinimumFlingVelocity(); 566 mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); 567 setWillNotDraw(getOverScrollMode() == View.OVER_SCROLL_NEVER); 568 569 mItemAnimator.setListener(mItemAnimatorListener); 570 initAdapterManager(); 571 initChildrenHelper(); 572 // If not explicitly specified this view is important for accessibility. 573 if (ViewCompat.getImportantForAccessibility(this) 574 == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 575 ViewCompat.setImportantForAccessibility(this, 576 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); 577 } 578 mAccessibilityManager = (AccessibilityManager) getContext() 579 .getSystemService(Context.ACCESSIBILITY_SERVICE); 580 setAccessibilityDelegateCompat(new RecyclerViewAccessibilityDelegate(this)); 581 // Create the layoutManager if specified. 582 583 boolean nestedScrollingEnabled = true; 584 585 if (attrs != null) { 586 int defStyleRes = 0; 587 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView, 588 defStyle, defStyleRes); 589 String layoutManagerName = a.getString(R.styleable.RecyclerView_layoutManager); 590 int descendantFocusability = a.getInt( 591 R.styleable.RecyclerView_android_descendantFocusability, -1); 592 if (descendantFocusability == -1) { 593 setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); 594 } 595 a.recycle(); 596 createLayoutManager(context, layoutManagerName, attrs, defStyle, defStyleRes); 597 598 if (Build.VERSION.SDK_INT >= 21) { 599 a = context.obtainStyledAttributes(attrs, NESTED_SCROLLING_ATTRS, 600 defStyle, defStyleRes); 601 nestedScrollingEnabled = a.getBoolean(0, true); 602 a.recycle(); 603 } 604 } else { 605 setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS); 606 } 607 608 // Re-set whether nested scrolling is enabled so that it is set on all API levels 609 setNestedScrollingEnabled(nestedScrollingEnabled); 610 } 611 612 /** 613 * Returns the accessibility delegate compatibility implementation used by the RecyclerView. 614 * @return An instance of AccessibilityDelegateCompat used by RecyclerView 615 */ 616 public RecyclerViewAccessibilityDelegate getCompatAccessibilityDelegate() { 617 return mAccessibilityDelegate; 618 } 619 620 /** 621 * Sets the accessibility delegate compatibility implementation used by RecyclerView. 622 * @param accessibilityDelegate The accessibility delegate to be used by RecyclerView. 623 */ 624 public void setAccessibilityDelegateCompat( 625 RecyclerViewAccessibilityDelegate accessibilityDelegate) { 626 mAccessibilityDelegate = accessibilityDelegate; 627 ViewCompat.setAccessibilityDelegate(this, mAccessibilityDelegate); 628 } 629 630 /** 631 * Instantiate and set a LayoutManager, if specified in the attributes. 632 */ 633 private void createLayoutManager(Context context, String className, AttributeSet attrs, 634 int defStyleAttr, int defStyleRes) { 635 if (className != null) { 636 className = className.trim(); 637 if (className.length() != 0) { // Can't use isEmpty since it was added in API 9. 638 className = getFullClassName(context, className); 639 try { 640 ClassLoader classLoader; 641 if (isInEditMode()) { 642 // Stupid layoutlib cannot handle simple class loaders. 643 classLoader = this.getClass().getClassLoader(); 644 } else { 645 classLoader = context.getClassLoader(); 646 } 647 Class<? extends LayoutManager> layoutManagerClass = 648 classLoader.loadClass(className).asSubclass(LayoutManager.class); 649 Constructor<? extends LayoutManager> constructor; 650 Object[] constructorArgs = null; 651 try { 652 constructor = layoutManagerClass 653 .getConstructor(LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE); 654 constructorArgs = new Object[]{context, attrs, defStyleAttr, defStyleRes}; 655 } catch (NoSuchMethodException e) { 656 try { 657 constructor = layoutManagerClass.getConstructor(); 658 } catch (NoSuchMethodException e1) { 659 e1.initCause(e); 660 throw new IllegalStateException(attrs.getPositionDescription() + 661 ": Error creating LayoutManager " + className, e1); 662 } 663 } 664 constructor.setAccessible(true); 665 setLayoutManager(constructor.newInstance(constructorArgs)); 666 } catch (ClassNotFoundException e) { 667 throw new IllegalStateException(attrs.getPositionDescription() 668 + ": Unable to find LayoutManager " + className, e); 669 } catch (InvocationTargetException e) { 670 throw new IllegalStateException(attrs.getPositionDescription() 671 + ": Could not instantiate the LayoutManager: " + className, e); 672 } catch (InstantiationException e) { 673 throw new IllegalStateException(attrs.getPositionDescription() 674 + ": Could not instantiate the LayoutManager: " + className, e); 675 } catch (IllegalAccessException e) { 676 throw new IllegalStateException(attrs.getPositionDescription() 677 + ": Cannot access non-public constructor " + className, e); 678 } catch (ClassCastException e) { 679 throw new IllegalStateException(attrs.getPositionDescription() 680 + ": Class is not a LayoutManager " + className, e); 681 } 682 } 683 } 684 } 685 686 private String getFullClassName(Context context, String className) { 687 if (className.charAt(0) == '.') { 688 return context.getPackageName() + className; 689 } 690 if (className.contains(".")) { 691 return className; 692 } 693 return RecyclerView.class.getPackage().getName() + '.' + className; 694 } 695 696 private void initChildrenHelper() { 697 mChildHelper = new ChildHelper(new ChildHelper.Callback() { 698 @Override 699 public int getChildCount() { 700 return RecyclerView.this.getChildCount(); 701 } 702 703 @Override 704 public void addView(View child, int index) { 705 RecyclerView.this.addView(child, index); 706 dispatchChildAttached(child); 707 } 708 709 @Override 710 public int indexOfChild(View view) { 711 return RecyclerView.this.indexOfChild(view); 712 } 713 714 @Override 715 public void removeViewAt(int index) { 716 final View child = RecyclerView.this.getChildAt(index); 717 if (child != null) { 718 dispatchChildDetached(child); 719 } 720 RecyclerView.this.removeViewAt(index); 721 } 722 723 @Override 724 public View getChildAt(int offset) { 725 return RecyclerView.this.getChildAt(offset); 726 } 727 728 @Override 729 public void removeAllViews() { 730 final int count = getChildCount(); 731 for (int i = 0; i < count; i ++) { 732 dispatchChildDetached(getChildAt(i)); 733 } 734 RecyclerView.this.removeAllViews(); 735 } 736 737 @Override 738 public ViewHolder getChildViewHolder(View view) { 739 return getChildViewHolderInt(view); 740 } 741 742 @Override 743 public void attachViewToParent(View child, int index, 744 ViewGroup.LayoutParams layoutParams) { 745 final ViewHolder vh = getChildViewHolderInt(child); 746 if (vh != null) { 747 if (!vh.isTmpDetached() && !vh.shouldIgnore()) { 748 throw new IllegalArgumentException("Called attach on a child which is not" 749 + " detached: " + vh); 750 } 751 if (DEBUG) { 752 Log.d(TAG, "reAttach " + vh); 753 } 754 vh.clearTmpDetachFlag(); 755 } 756 RecyclerView.this.attachViewToParent(child, index, layoutParams); 757 } 758 759 @Override 760 public void detachViewFromParent(int offset) { 761 final View view = getChildAt(offset); 762 if (view != null) { 763 final ViewHolder vh = getChildViewHolderInt(view); 764 if (vh != null) { 765 if (vh.isTmpDetached() && !vh.shouldIgnore()) { 766 throw new IllegalArgumentException("called detach on an already" 767 + " detached child " + vh); 768 } 769 if (DEBUG) { 770 Log.d(TAG, "tmpDetach " + vh); 771 } 772 vh.addFlags(ViewHolder.FLAG_TMP_DETACHED); 773 } 774 } 775 RecyclerView.this.detachViewFromParent(offset); 776 } 777 778 @Override 779 public void onEnteredHiddenState(View child) { 780 final ViewHolder vh = getChildViewHolderInt(child); 781 if (vh != null) { 782 vh.onEnteredHiddenState(RecyclerView.this); 783 } 784 } 785 786 @Override 787 public void onLeftHiddenState(View child) { 788 final ViewHolder vh = getChildViewHolderInt(child); 789 if (vh != null) { 790 vh.onLeftHiddenState(RecyclerView.this); 791 } 792 } 793 }); 794 } 795 796 void initAdapterManager() { 797 mAdapterHelper = new AdapterHelper(new AdapterHelper.Callback() { 798 @Override 799 public ViewHolder findViewHolder(int position) { 800 final ViewHolder vh = findViewHolderForPosition(position, true); 801 if (vh == null) { 802 return null; 803 } 804 // ensure it is not hidden because for adapter helper, the only thing matter is that 805 // LM thinks view is a child. 806 if (mChildHelper.isHidden(vh.itemView)) { 807 if (DEBUG) { 808 Log.d(TAG, "assuming view holder cannot be find because it is hidden"); 809 } 810 return null; 811 } 812 return vh; 813 } 814 815 @Override 816 public void offsetPositionsForRemovingInvisible(int start, int count) { 817 offsetPositionRecordsForRemove(start, count, true); 818 mItemsAddedOrRemoved = true; 819 mState.mDeletedInvisibleItemCountSincePreviousLayout += count; 820 } 821 822 @Override 823 public void offsetPositionsForRemovingLaidOutOrNewView(int positionStart, int itemCount) { 824 offsetPositionRecordsForRemove(positionStart, itemCount, false); 825 mItemsAddedOrRemoved = true; 826 } 827 828 @Override 829 public void markViewHoldersUpdated(int positionStart, int itemCount, Object payload) { 830 viewRangeUpdate(positionStart, itemCount, payload); 831 mItemsChanged = true; 832 } 833 834 @Override 835 public void onDispatchFirstPass(AdapterHelper.UpdateOp op) { 836 dispatchUpdate(op); 837 } 838 839 void dispatchUpdate(AdapterHelper.UpdateOp op) { 840 switch (op.cmd) { 841 case AdapterHelper.UpdateOp.ADD: 842 mLayout.onItemsAdded(RecyclerView.this, op.positionStart, op.itemCount); 843 break; 844 case AdapterHelper.UpdateOp.REMOVE: 845 mLayout.onItemsRemoved(RecyclerView.this, op.positionStart, op.itemCount); 846 break; 847 case AdapterHelper.UpdateOp.UPDATE: 848 mLayout.onItemsUpdated(RecyclerView.this, op.positionStart, op.itemCount, 849 op.payload); 850 break; 851 case AdapterHelper.UpdateOp.MOVE: 852 mLayout.onItemsMoved(RecyclerView.this, op.positionStart, op.itemCount, 1); 853 break; 854 } 855 } 856 857 @Override 858 public void onDispatchSecondPass(AdapterHelper.UpdateOp op) { 859 dispatchUpdate(op); 860 } 861 862 @Override 863 public void offsetPositionsForAdd(int positionStart, int itemCount) { 864 offsetPositionRecordsForInsert(positionStart, itemCount); 865 mItemsAddedOrRemoved = true; 866 } 867 868 @Override 869 public void offsetPositionsForMove(int from, int to) { 870 offsetPositionRecordsForMove(from, to); 871 // should we create mItemsMoved ? 872 mItemsAddedOrRemoved = true; 873 } 874 }); 875 } 876 877 /** 878 * RecyclerView can perform several optimizations if it can know in advance that RecyclerView's 879 * size is not affected by the adapter contents. RecyclerView can still change its size based 880 * on other factors (e.g. its parent's size) but this size calculation cannot depend on the 881 * size of its children or contents of its adapter (except the number of items in the adapter). 882 * <p> 883 * If your use of RecyclerView falls into this category, set this to {@code true}. It will allow 884 * RecyclerView to avoid invalidating the whole layout when its adapter contents change. 885 * 886 * @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView. 887 */ 888 public void setHasFixedSize(boolean hasFixedSize) { 889 mHasFixedSize = hasFixedSize; 890 } 891 892 /** 893 * @return true if the app has specified that changes in adapter content cannot change 894 * the size of the RecyclerView itself. 895 */ 896 public boolean hasFixedSize() { 897 return mHasFixedSize; 898 } 899 900 @Override 901 public void setClipToPadding(boolean clipToPadding) { 902 if (clipToPadding != mClipToPadding) { 903 invalidateGlows(); 904 } 905 mClipToPadding = clipToPadding; 906 super.setClipToPadding(clipToPadding); 907 if (mFirstLayoutComplete) { 908 requestLayout(); 909 } 910 } 911 912 /** 913 * Returns whether this RecyclerView will clip its children to its padding, and resize (but 914 * not clip) any EdgeEffect to the padded region, if padding is present. 915 * <p> 916 * By default, children are clipped to the padding of their parent 917 * RecyclerView. This clipping behavior is only enabled if padding is non-zero. 918 * 919 * @return true if this RecyclerView clips children to its padding and resizes (but doesn't 920 * clip) any EdgeEffect to the padded region, false otherwise. 921 * 922 * @attr name android:clipToPadding 923 */ 924 @Override 925 public boolean getClipToPadding() { 926 return mClipToPadding; 927 } 928 929 /** 930 * Configure the scrolling touch slop for a specific use case. 931 * 932 * Set up the RecyclerView's scrolling motion threshold based on common usages. 933 * Valid arguments are {@link #TOUCH_SLOP_DEFAULT} and {@link #TOUCH_SLOP_PAGING}. 934 * 935 * @param slopConstant One of the <code>TOUCH_SLOP_</code> constants representing 936 * the intended usage of this RecyclerView 937 */ 938 public void setScrollingTouchSlop(int slopConstant) { 939 final ViewConfiguration vc = ViewConfiguration.get(getContext()); 940 switch (slopConstant) { 941 default: 942 Log.w(TAG, "setScrollingTouchSlop(): bad argument constant " 943 + slopConstant + "; using default value"); 944 // fall-through 945 case TOUCH_SLOP_DEFAULT: 946 mTouchSlop = vc.getScaledTouchSlop(); 947 break; 948 949 case TOUCH_SLOP_PAGING: 950 mTouchSlop = vc.getScaledPagingTouchSlop(); 951 break; 952 } 953 } 954 955 /** 956 * Swaps the current adapter with the provided one. It is similar to 957 * {@link #setAdapter(Adapter)} but assumes existing adapter and the new adapter uses the same 958 * {@link ViewHolder} and does not clear the RecycledViewPool. 959 * <p> 960 * Note that it still calls onAdapterChanged callbacks. 961 * 962 * @param adapter The new adapter to set, or null to set no adapter. 963 * @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing 964 * Views. If adapters have stable ids and/or you want to 965 * animate the disappearing views, you may prefer to set 966 * this to false. 967 * @see #setAdapter(Adapter) 968 */ 969 public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) { 970 // bail out if layout is frozen 971 setLayoutFrozen(false); 972 setAdapterInternal(adapter, true, removeAndRecycleExistingViews); 973 setDataSetChangedAfterLayout(); 974 requestLayout(); 975 } 976 /** 977 * Set a new adapter to provide child views on demand. 978 * <p> 979 * When adapter is changed, all existing views are recycled back to the pool. If the pool has 980 * only one adapter, it will be cleared. 981 * 982 * @param adapter The new adapter to set, or null to set no adapter. 983 * @see #swapAdapter(Adapter, boolean) 984 */ 985 public void setAdapter(Adapter adapter) { 986 // bail out if layout is frozen 987 setLayoutFrozen(false); 988 setAdapterInternal(adapter, false, true); 989 requestLayout(); 990 } 991 992 /** 993 * Removes and recycles all views - both those currently attached, and those in the Recycler. 994 */ 995 void removeAndRecycleViews() { 996 // end all running animations 997 if (mItemAnimator != null) { 998 mItemAnimator.endAnimations(); 999 } 1000 // Since animations are ended, mLayout.children should be equal to 1001 // recyclerView.children. This may not be true if item animator's end does not work as 1002 // expected. (e.g. not release children instantly). It is safer to use mLayout's child 1003 // count. 1004 if (mLayout != null) { 1005 mLayout.removeAndRecycleAllViews(mRecycler); 1006 mLayout.removeAndRecycleScrapInt(mRecycler); 1007 } 1008 // we should clear it here before adapters are swapped to ensure correct callbacks. 1009 mRecycler.clear(); 1010 } 1011 1012 /** 1013 * Replaces the current adapter with the new one and triggers listeners. 1014 * @param adapter The new adapter 1015 * @param compatibleWithPrevious If true, the new adapter is using the same View Holders and 1016 * item types with the current adapter (helps us avoid cache 1017 * invalidation). 1018 * @param removeAndRecycleViews If true, we'll remove and recycle all existing views. If 1019 * compatibleWithPrevious is false, this parameter is ignored. 1020 */ 1021 private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious, 1022 boolean removeAndRecycleViews) { 1023 if (mAdapter != null) { 1024 mAdapter.unregisterAdapterDataObserver(mObserver); 1025 mAdapter.onDetachedFromRecyclerView(this); 1026 } 1027 if (!compatibleWithPrevious || removeAndRecycleViews) { 1028 removeAndRecycleViews(); 1029 } 1030 mAdapterHelper.reset(); 1031 final Adapter oldAdapter = mAdapter; 1032 mAdapter = adapter; 1033 if (adapter != null) { 1034 adapter.registerAdapterDataObserver(mObserver); 1035 adapter.onAttachedToRecyclerView(this); 1036 } 1037 if (mLayout != null) { 1038 mLayout.onAdapterChanged(oldAdapter, mAdapter); 1039 } 1040 mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious); 1041 mState.mStructureChanged = true; 1042 markKnownViewsInvalid(); 1043 } 1044 1045 /** 1046 * Retrieves the previously set adapter or null if no adapter is set. 1047 * 1048 * @return The previously set adapter 1049 * @see #setAdapter(Adapter) 1050 */ 1051 public Adapter getAdapter() { 1052 return mAdapter; 1053 } 1054 1055 /** 1056 * Register a listener that will be notified whenever a child view is recycled. 1057 * 1058 * <p>This listener will be called when a LayoutManager or the RecyclerView decides 1059 * that a child view is no longer needed. If an application associates expensive 1060 * or heavyweight data with item views, this may be a good place to release 1061 * or free those resources.</p> 1062 * 1063 * @param listener Listener to register, or null to clear 1064 */ 1065 public void setRecyclerListener(RecyclerListener listener) { 1066 mRecyclerListener = listener; 1067 } 1068 1069 /** 1070 * <p>Return the offset of the RecyclerView's text baseline from the its top 1071 * boundary. If the LayoutManager of this RecyclerView does not support baseline alignment, 1072 * this method returns -1.</p> 1073 * 1074 * @return the offset of the baseline within the RecyclerView's bounds or -1 1075 * if baseline alignment is not supported 1076 */ 1077 @Override 1078 public int getBaseline() { 1079 if (mLayout != null) { 1080 return mLayout.getBaseline(); 1081 } else { 1082 return super.getBaseline(); 1083 } 1084 } 1085 1086 /** 1087 * Register a listener that will be notified whenever a child view is attached to or detached 1088 * from RecyclerView. 1089 * 1090 * <p>This listener will be called when a LayoutManager or the RecyclerView decides 1091 * that a child view is no longer needed. If an application associates expensive 1092 * or heavyweight data with item views, this may be a good place to release 1093 * or free those resources.</p> 1094 * 1095 * @param listener Listener to register 1096 */ 1097 public void addOnChildAttachStateChangeListener(OnChildAttachStateChangeListener listener) { 1098 if (mOnChildAttachStateListeners == null) { 1099 mOnChildAttachStateListeners = new ArrayList<>(); 1100 } 1101 mOnChildAttachStateListeners.add(listener); 1102 } 1103 1104 /** 1105 * Removes the provided listener from child attached state listeners list. 1106 * 1107 * @param listener Listener to unregister 1108 */ 1109 public void removeOnChildAttachStateChangeListener(OnChildAttachStateChangeListener listener) { 1110 if (mOnChildAttachStateListeners == null) { 1111 return; 1112 } 1113 mOnChildAttachStateListeners.remove(listener); 1114 } 1115 1116 /** 1117 * Removes all listeners that were added via 1118 * {@link #addOnChildAttachStateChangeListener(OnChildAttachStateChangeListener)}. 1119 */ 1120 public void clearOnChildAttachStateChangeListeners() { 1121 if (mOnChildAttachStateListeners != null) { 1122 mOnChildAttachStateListeners.clear(); 1123 } 1124 } 1125 1126 /** 1127 * Set the {@link LayoutManager} that this RecyclerView will use. 1128 * 1129 * <p>In contrast to other adapter-backed views such as {@link android.widget.ListView} 1130 * or {@link android.widget.GridView}, RecyclerView allows client code to provide custom 1131 * layout arrangements for child views. These arrangements are controlled by the 1132 * {@link LayoutManager}. A LayoutManager must be provided for RecyclerView to function.</p> 1133 * 1134 * <p>Several default strategies are provided for common uses such as lists and grids.</p> 1135 * 1136 * @param layout LayoutManager to use 1137 */ 1138 public void setLayoutManager(LayoutManager layout) { 1139 if (layout == mLayout) { 1140 return; 1141 } 1142 stopScroll(); 1143 // TODO We should do this switch a dispatchLayout pass and animate children. There is a good 1144 // chance that LayoutManagers will re-use views. 1145 if (mLayout != null) { 1146 // end all running animations 1147 if (mItemAnimator != null) { 1148 mItemAnimator.endAnimations(); 1149 } 1150 mLayout.removeAndRecycleAllViews(mRecycler); 1151 mLayout.removeAndRecycleScrapInt(mRecycler); 1152 mRecycler.clear(); 1153 1154 if (mIsAttached) { 1155 mLayout.dispatchDetachedFromWindow(this, mRecycler); 1156 } 1157 mLayout.setRecyclerView(null); 1158 mLayout = null; 1159 } else { 1160 mRecycler.clear(); 1161 } 1162 // this is just a defensive measure for faulty item animators. 1163 mChildHelper.removeAllViewsUnfiltered(); 1164 mLayout = layout; 1165 if (layout != null) { 1166 if (layout.mRecyclerView != null) { 1167 throw new IllegalArgumentException("LayoutManager " + layout + 1168 " is already attached to a RecyclerView: " + layout.mRecyclerView); 1169 } 1170 mLayout.setRecyclerView(this); 1171 if (mIsAttached) { 1172 mLayout.dispatchAttachedToWindow(this); 1173 } 1174 } 1175 mRecycler.updateViewCacheSize(); 1176 requestLayout(); 1177 } 1178 1179 /** 1180 * Set a {@link OnFlingListener} for this {@link RecyclerView}. 1181 * <p> 1182 * If the {@link OnFlingListener} is set then it will receive 1183 * calls to {@link #fling(int,int)} and will be able to intercept them. 1184 * 1185 * @param onFlingListener The {@link OnFlingListener} instance. 1186 */ 1187 public void setOnFlingListener(@Nullable OnFlingListener onFlingListener) { 1188 mOnFlingListener = onFlingListener; 1189 } 1190 1191 /** 1192 * Get the current {@link OnFlingListener} from this {@link RecyclerView}. 1193 * 1194 * @return The {@link OnFlingListener} instance currently set (can be null). 1195 */ 1196 @Nullable 1197 public OnFlingListener getOnFlingListener() { 1198 return mOnFlingListener; 1199 } 1200 1201 @Override 1202 protected Parcelable onSaveInstanceState() { 1203 SavedState state = new SavedState(super.onSaveInstanceState()); 1204 if (mPendingSavedState != null) { 1205 state.copyFrom(mPendingSavedState); 1206 } else if (mLayout != null) { 1207 state.mLayoutState = mLayout.onSaveInstanceState(); 1208 } else { 1209 state.mLayoutState = null; 1210 } 1211 1212 return state; 1213 } 1214 1215 @Override 1216 protected void onRestoreInstanceState(Parcelable state) { 1217 if (!(state instanceof SavedState)) { 1218 super.onRestoreInstanceState(state); 1219 return; 1220 } 1221 1222 mPendingSavedState = (SavedState) state; 1223 super.onRestoreInstanceState(mPendingSavedState.getSuperState()); 1224 if (mLayout != null && mPendingSavedState.mLayoutState != null) { 1225 mLayout.onRestoreInstanceState(mPendingSavedState.mLayoutState); 1226 } 1227 } 1228 1229 /** 1230 * Override to prevent freezing of any views created by the adapter. 1231 */ 1232 @Override 1233 protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) { 1234 dispatchFreezeSelfOnly(container); 1235 } 1236 1237 /** 1238 * Override to prevent thawing of any views created by the adapter. 1239 */ 1240 @Override 1241 protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { 1242 dispatchThawSelfOnly(container); 1243 } 1244 1245 /** 1246 * Adds a view to the animatingViews list. 1247 * mAnimatingViews holds the child views that are currently being kept around 1248 * purely for the purpose of being animated out of view. They are drawn as a regular 1249 * part of the child list of the RecyclerView, but they are invisible to the LayoutManager 1250 * as they are managed separately from the regular child views. 1251 * @param viewHolder The ViewHolder to be removed 1252 */ 1253 private void addAnimatingView(ViewHolder viewHolder) { 1254 final View view = viewHolder.itemView; 1255 final boolean alreadyParented = view.getParent() == this; 1256 mRecycler.unscrapView(getChildViewHolder(view)); 1257 if (viewHolder.isTmpDetached()) { 1258 // re-attach 1259 mChildHelper.attachViewToParent(view, -1, view.getLayoutParams(), true); 1260 } else if(!alreadyParented) { 1261 mChildHelper.addView(view, true); 1262 } else { 1263 mChildHelper.hide(view); 1264 } 1265 } 1266 1267 /** 1268 * Removes a view from the animatingViews list. 1269 * @param view The view to be removed 1270 * @see #addAnimatingView(RecyclerView.ViewHolder) 1271 * @return true if an animating view is removed 1272 */ 1273 boolean removeAnimatingView(View view) { 1274 eatRequestLayout(); 1275 final boolean removed = mChildHelper.removeViewIfHidden(view); 1276 if (removed) { 1277 final ViewHolder viewHolder = getChildViewHolderInt(view); 1278 mRecycler.unscrapView(viewHolder); 1279 mRecycler.recycleViewHolderInternal(viewHolder); 1280 if (DEBUG) { 1281 Log.d(TAG, "after removing animated view: " + view + ", " + this); 1282 } 1283 } 1284 // only clear request eaten flag if we removed the view. 1285 resumeRequestLayout(!removed); 1286 return removed; 1287 } 1288 1289 /** 1290 * Return the {@link LayoutManager} currently responsible for 1291 * layout policy for this RecyclerView. 1292 * 1293 * @return The currently bound LayoutManager 1294 */ 1295 public LayoutManager getLayoutManager() { 1296 return mLayout; 1297 } 1298 1299 /** 1300 * Retrieve this RecyclerView's {@link RecycledViewPool}. This method will never return null; 1301 * if no pool is set for this view a new one will be created. See 1302 * {@link #setRecycledViewPool(RecycledViewPool) setRecycledViewPool} for more information. 1303 * 1304 * @return The pool used to store recycled item views for reuse. 1305 * @see #setRecycledViewPool(RecycledViewPool) 1306 */ 1307 public RecycledViewPool getRecycledViewPool() { 1308 return mRecycler.getRecycledViewPool(); 1309 } 1310 1311 /** 1312 * Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views. 1313 * This can be useful if you have multiple RecyclerViews with adapters that use the same 1314 * view types, for example if you have several data sets with the same kinds of item views 1315 * displayed by a {@link android.support.v4.view.ViewPager ViewPager}. 1316 * 1317 * @param pool Pool to set. If this parameter is null a new pool will be created and used. 1318 */ 1319 public void setRecycledViewPool(RecycledViewPool pool) { 1320 mRecycler.setRecycledViewPool(pool); 1321 } 1322 1323 /** 1324 * Sets a new {@link ViewCacheExtension} to be used by the Recycler. 1325 * 1326 * @param extension ViewCacheExtension to be used or null if you want to clear the existing one. 1327 * 1328 * @see {@link ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)} 1329 */ 1330 public void setViewCacheExtension(ViewCacheExtension extension) { 1331 mRecycler.setViewCacheExtension(extension); 1332 } 1333 1334 /** 1335 * Set the number of offscreen views to retain before adding them to the potentially shared 1336 * {@link #getRecycledViewPool() recycled view pool}. 1337 * 1338 * <p>The offscreen view cache stays aware of changes in the attached adapter, allowing 1339 * a LayoutManager to reuse those views unmodified without needing to return to the adapter 1340 * to rebind them.</p> 1341 * 1342 * @param size Number of views to cache offscreen before returning them to the general 1343 * recycled view pool 1344 */ 1345 public void setItemViewCacheSize(int size) { 1346 mRecycler.setViewCacheSize(size); 1347 } 1348 1349 /** 1350 * Return the current scrolling state of the RecyclerView. 1351 * 1352 * @return {@link #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or 1353 * {@link #SCROLL_STATE_SETTLING} 1354 */ 1355 public int getScrollState() { 1356 return mScrollState; 1357 } 1358 1359 void setScrollState(int state) { 1360 if (state == mScrollState) { 1361 return; 1362 } 1363 if (DEBUG) { 1364 Log.d(TAG, "setting scroll state to " + state + " from " + mScrollState, 1365 new Exception()); 1366 } 1367 mScrollState = state; 1368 if (state != SCROLL_STATE_SETTLING) { 1369 stopScrollersInternal(); 1370 } 1371 dispatchOnScrollStateChanged(state); 1372 } 1373 1374 /** 1375 * Add an {@link ItemDecoration} to this RecyclerView. Item decorations can 1376 * affect both measurement and drawing of individual item views. 1377 * 1378 * <p>Item decorations are ordered. Decorations placed earlier in the list will 1379 * be run/queried/drawn first for their effects on item views. Padding added to views 1380 * will be nested; a padding added by an earlier decoration will mean further 1381 * item decorations in the list will be asked to draw/pad within the previous decoration's 1382 * given area.</p> 1383 * 1384 * @param decor Decoration to add 1385 * @param index Position in the decoration chain to insert this decoration at. If this value 1386 * is negative the decoration will be added at the end. 1387 */ 1388 public void addItemDecoration(ItemDecoration decor, int index) { 1389 if (mLayout != null) { 1390 mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or" 1391 + " layout"); 1392 } 1393 if (mItemDecorations.isEmpty()) { 1394 setWillNotDraw(false); 1395 } 1396 if (index < 0) { 1397 mItemDecorations.add(decor); 1398 } else { 1399 mItemDecorations.add(index, decor); 1400 } 1401 markItemDecorInsetsDirty(); 1402 requestLayout(); 1403 } 1404 1405 /** 1406 * Add an {@link ItemDecoration} to this RecyclerView. Item decorations can 1407 * affect both measurement and drawing of individual item views. 1408 * 1409 * <p>Item decorations are ordered. Decorations placed earlier in the list will 1410 * be run/queried/drawn first for their effects on item views. Padding added to views 1411 * will be nested; a padding added by an earlier decoration will mean further 1412 * item decorations in the list will be asked to draw/pad within the previous decoration's 1413 * given area.</p> 1414 * 1415 * @param decor Decoration to add 1416 */ 1417 public void addItemDecoration(ItemDecoration decor) { 1418 addItemDecoration(decor, -1); 1419 } 1420 1421 /** 1422 * Remove an {@link ItemDecoration} from this RecyclerView. 1423 * 1424 * <p>The given decoration will no longer impact the measurement and drawing of 1425 * item views.</p> 1426 * 1427 * @param decor Decoration to remove 1428 * @see #addItemDecoration(ItemDecoration) 1429 */ 1430 public void removeItemDecoration(ItemDecoration decor) { 1431 if (mLayout != null) { 1432 mLayout.assertNotInLayoutOrScroll("Cannot remove item decoration during a scroll or" 1433 + " layout"); 1434 } 1435 mItemDecorations.remove(decor); 1436 if (mItemDecorations.isEmpty()) { 1437 setWillNotDraw(getOverScrollMode() == View.OVER_SCROLL_NEVER); 1438 } 1439 markItemDecorInsetsDirty(); 1440 requestLayout(); 1441 } 1442 1443 /** 1444 * Sets the {@link ChildDrawingOrderCallback} to be used for drawing children. 1445 * <p> 1446 * See {@link ViewGroup#getChildDrawingOrder(int, int)} for details. Calling this method will 1447 * always call {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean)}. The parameter will be 1448 * true if childDrawingOrderCallback is not null, false otherwise. 1449 * <p> 1450 * Note that child drawing order may be overridden by View's elevation. 1451 * 1452 * @param childDrawingOrderCallback The ChildDrawingOrderCallback to be used by the drawing 1453 * system. 1454 */ 1455 public void setChildDrawingOrderCallback(ChildDrawingOrderCallback childDrawingOrderCallback) { 1456 if (childDrawingOrderCallback == mChildDrawingOrderCallback) { 1457 return; 1458 } 1459 mChildDrawingOrderCallback = childDrawingOrderCallback; 1460 setChildrenDrawingOrderEnabled(mChildDrawingOrderCallback != null); 1461 } 1462 1463 /** 1464 * Set a listener that will be notified of any changes in scroll state or position. 1465 * 1466 * @param listener Listener to set or null to clear 1467 * 1468 * @deprecated Use {@link #addOnScrollListener(OnScrollListener)} and 1469 * {@link #removeOnScrollListener(OnScrollListener)} 1470 */ 1471 @Deprecated 1472 public void setOnScrollListener(OnScrollListener listener) { 1473 mScrollListener = listener; 1474 } 1475 1476 /** 1477 * Add a listener that will be notified of any changes in scroll state or position. 1478 * 1479 * <p>Components that add a listener should take care to remove it when finished. 1480 * Other components that take ownership of a view may call {@link #clearOnScrollListeners()} 1481 * to remove all attached listeners.</p> 1482 * 1483 * @param listener listener to set or null to clear 1484 */ 1485 public void addOnScrollListener(OnScrollListener listener) { 1486 if (mScrollListeners == null) { 1487 mScrollListeners = new ArrayList<>(); 1488 } 1489 mScrollListeners.add(listener); 1490 } 1491 1492 /** 1493 * Remove a listener that was notified of any changes in scroll state or position. 1494 * 1495 * @param listener listener to set or null to clear 1496 */ 1497 public void removeOnScrollListener(OnScrollListener listener) { 1498 if (mScrollListeners != null) { 1499 mScrollListeners.remove(listener); 1500 } 1501 } 1502 1503 /** 1504 * Remove all secondary listener that were notified of any changes in scroll state or position. 1505 */ 1506 public void clearOnScrollListeners() { 1507 if (mScrollListeners != null) { 1508 mScrollListeners.clear(); 1509 } 1510 } 1511 1512 /** 1513 * Convenience method to scroll to a certain position. 1514 * 1515 * RecyclerView does not implement scrolling logic, rather forwards the call to 1516 * {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)} 1517 * @param position Scroll to this adapter position 1518 * @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int) 1519 */ 1520 public void scrollToPosition(int position) { 1521 if (mLayoutFrozen) { 1522 return; 1523 } 1524 stopScroll(); 1525 if (mLayout == null) { 1526 Log.e(TAG, "Cannot scroll to position a LayoutManager set. " + 1527 "Call setLayoutManager with a non-null argument."); 1528 return; 1529 } 1530 mLayout.scrollToPosition(position); 1531 awakenScrollBars(); 1532 } 1533 1534 void jumpToPositionForSmoothScroller(int position) { 1535 if (mLayout == null) { 1536 return; 1537 } 1538 mLayout.scrollToPosition(position); 1539 awakenScrollBars(); 1540 } 1541 1542 /** 1543 * Starts a smooth scroll to an adapter position. 1544 * <p> 1545 * To support smooth scrolling, you must override 1546 * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a 1547 * {@link SmoothScroller}. 1548 * <p> 1549 * {@link LayoutManager} is responsible for creating the actual scroll action. If you want to 1550 * provide a custom smooth scroll logic, override 1551 * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your 1552 * LayoutManager. 1553 * 1554 * @param position The adapter position to scroll to 1555 * @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int) 1556 */ 1557 public void smoothScrollToPosition(int position) { 1558 if (mLayoutFrozen) { 1559 return; 1560 } 1561 if (mLayout == null) { 1562 Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " + 1563 "Call setLayoutManager with a non-null argument."); 1564 return; 1565 } 1566 mLayout.smoothScrollToPosition(this, mState, position); 1567 } 1568 1569 @Override 1570 public void scrollTo(int x, int y) { 1571 Log.w(TAG, "RecyclerView does not support scrolling to an absolute position. " 1572 + "Use scrollToPosition instead"); 1573 } 1574 1575 @Override 1576 public void scrollBy(int x, int y) { 1577 if (mLayout == null) { 1578 Log.e(TAG, "Cannot scroll without a LayoutManager set. " + 1579 "Call setLayoutManager with a non-null argument."); 1580 return; 1581 } 1582 if (mLayoutFrozen) { 1583 return; 1584 } 1585 final boolean canScrollHorizontal = mLayout.canScrollHorizontally(); 1586 final boolean canScrollVertical = mLayout.canScrollVertically(); 1587 if (canScrollHorizontal || canScrollVertical) { 1588 scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0, null); 1589 } 1590 } 1591 1592 /** 1593 * Helper method reflect data changes to the state. 1594 * <p> 1595 * Adapter changes during a scroll may trigger a crash because scroll assumes no data change 1596 * but data actually changed. 1597 * <p> 1598 * This method consumes all deferred changes to avoid that case. 1599 */ 1600 void consumePendingUpdateOperations() { 1601 if (!mFirstLayoutComplete || mDataSetHasChangedAfterLayout) { 1602 TraceCompat.beginSection(TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG); 1603 dispatchLayout(); 1604 TraceCompat.endSection(); 1605 return; 1606 } 1607 if (!mAdapterHelper.hasPendingUpdates()) { 1608 return; 1609 } 1610 1611 // if it is only an item change (no add-remove-notifyDataSetChanged) we can check if any 1612 // of the visible items is affected and if not, just ignore the change. 1613 if (mAdapterHelper.hasAnyUpdateTypes(AdapterHelper.UpdateOp.UPDATE) && !mAdapterHelper 1614 .hasAnyUpdateTypes(AdapterHelper.UpdateOp.ADD | AdapterHelper.UpdateOp.REMOVE 1615 | AdapterHelper.UpdateOp.MOVE)) { 1616 TraceCompat.beginSection(TRACE_HANDLE_ADAPTER_UPDATES_TAG); 1617 eatRequestLayout(); 1618 onEnterLayoutOrScroll(); 1619 mAdapterHelper.preProcess(); 1620 if (!mLayoutRequestEaten) { 1621 if (hasUpdatedView()) { 1622 dispatchLayout(); 1623 } else { 1624 // no need to layout, clean state 1625 mAdapterHelper.consumePostponedUpdates(); 1626 } 1627 } 1628 resumeRequestLayout(true); 1629 onExitLayoutOrScroll(); 1630 TraceCompat.endSection(); 1631 } else if (mAdapterHelper.hasPendingUpdates()) { 1632 TraceCompat.beginSection(TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG); 1633 dispatchLayout(); 1634 TraceCompat.endSection(); 1635 } 1636 } 1637 1638 /** 1639 * @return True if an existing view holder needs to be updated 1640 */ 1641 private boolean hasUpdatedView() { 1642 final int childCount = mChildHelper.getChildCount(); 1643 for (int i = 0; i < childCount; i++) { 1644 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 1645 if (holder == null || holder.shouldIgnore()) { 1646 continue; 1647 } 1648 if (holder.isUpdated()) { 1649 return true; 1650 } 1651 } 1652 return false; 1653 } 1654 1655 /** 1656 * Does not perform bounds checking. Used by internal methods that have already validated input. 1657 * <p> 1658 * It also reports any unused scroll request to the related EdgeEffect. 1659 * 1660 * @param x The amount of horizontal scroll request 1661 * @param y The amount of vertical scroll request 1662 * @param ev The originating MotionEvent, or null if not from a touch event. 1663 * 1664 * @return Whether any scroll was consumed in either direction. 1665 */ 1666 boolean scrollByInternal(int x, int y, MotionEvent ev) { 1667 int unconsumedX = 0, unconsumedY = 0; 1668 int consumedX = 0, consumedY = 0; 1669 1670 consumePendingUpdateOperations(); 1671 if (mAdapter != null) { 1672 eatRequestLayout(); 1673 onEnterLayoutOrScroll(); 1674 TraceCompat.beginSection(TRACE_SCROLL_TAG); 1675 if (x != 0) { 1676 consumedX = mLayout.scrollHorizontallyBy(x, mRecycler, mState); 1677 unconsumedX = x - consumedX; 1678 } 1679 if (y != 0) { 1680 consumedY = mLayout.scrollVerticallyBy(y, mRecycler, mState); 1681 unconsumedY = y - consumedY; 1682 } 1683 TraceCompat.endSection(); 1684 repositionShadowingViews(); 1685 onExitLayoutOrScroll(); 1686 resumeRequestLayout(false); 1687 } 1688 if (!mItemDecorations.isEmpty()) { 1689 invalidate(); 1690 } 1691 1692 if (dispatchNestedScroll(consumedX, consumedY, unconsumedX, unconsumedY, mScrollOffset)) { 1693 // Update the last touch co-ords, taking any scroll offset into account 1694 mLastTouchX -= mScrollOffset[0]; 1695 mLastTouchY -= mScrollOffset[1]; 1696 if (ev != null) { 1697 ev.offsetLocation(mScrollOffset[0], mScrollOffset[1]); 1698 } 1699 mNestedOffsets[0] += mScrollOffset[0]; 1700 mNestedOffsets[1] += mScrollOffset[1]; 1701 } else if (getOverScrollMode() != View.OVER_SCROLL_NEVER) { 1702 if (ev != null) { 1703 pullGlows(ev.getX(), unconsumedX, ev.getY(), unconsumedY); 1704 } 1705 considerReleasingGlowsOnScroll(x, y); 1706 } 1707 if (consumedX != 0 || consumedY != 0) { 1708 dispatchOnScrolled(consumedX, consumedY); 1709 } 1710 if (!awakenScrollBars()) { 1711 invalidate(); 1712 } 1713 return consumedX != 0 || consumedY != 0; 1714 } 1715 1716 /** 1717 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal 1718 * range. This value is used to compute the length of the thumb within the scrollbar's track. 1719 * </p> 1720 * 1721 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1722 * {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollExtent()}.</p> 1723 * 1724 * <p>Default implementation returns 0.</p> 1725 * 1726 * <p>If you want to support scroll bars, override 1727 * {@link RecyclerView.LayoutManager#computeHorizontalScrollOffset(RecyclerView.State)} in your 1728 * LayoutManager. </p> 1729 * 1730 * @return The horizontal offset of the scrollbar's thumb 1731 * @see android.support.v7.widget.RecyclerView.LayoutManager#computeHorizontalScrollOffset 1732 * (RecyclerView.State) 1733 */ 1734 @Override 1735 public int computeHorizontalScrollOffset() { 1736 if (mLayout == null) { 1737 return 0; 1738 } 1739 return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollOffset(mState) : 0; 1740 } 1741 1742 /** 1743 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb within the 1744 * horizontal range. This value is used to compute the length of the thumb within the 1745 * scrollbar's track.</p> 1746 * 1747 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1748 * {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollOffset()}.</p> 1749 * 1750 * <p>Default implementation returns 0.</p> 1751 * 1752 * <p>If you want to support scroll bars, override 1753 * {@link RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)} in your 1754 * LayoutManager.</p> 1755 * 1756 * @return The horizontal extent of the scrollbar's thumb 1757 * @see RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State) 1758 */ 1759 @Override 1760 public int computeHorizontalScrollExtent() { 1761 if (mLayout == null) { 1762 return 0; 1763 } 1764 return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollExtent(mState) : 0; 1765 } 1766 1767 /** 1768 * <p>Compute the horizontal range that the horizontal scrollbar represents.</p> 1769 * 1770 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1771 * {@link #computeHorizontalScrollExtent()} and {@link #computeHorizontalScrollOffset()}.</p> 1772 * 1773 * <p>Default implementation returns 0.</p> 1774 * 1775 * <p>If you want to support scroll bars, override 1776 * {@link RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)} in your 1777 * LayoutManager.</p> 1778 * 1779 * @return The total horizontal range represented by the vertical scrollbar 1780 * @see RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State) 1781 */ 1782 @Override 1783 public int computeHorizontalScrollRange() { 1784 if (mLayout == null) { 1785 return 0; 1786 } 1787 return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollRange(mState) : 0; 1788 } 1789 1790 /** 1791 * <p>Compute the vertical offset of the vertical scrollbar's thumb within the vertical range. 1792 * This value is used to compute the length of the thumb within the scrollbar's track. </p> 1793 * 1794 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1795 * {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollExtent()}.</p> 1796 * 1797 * <p>Default implementation returns 0.</p> 1798 * 1799 * <p>If you want to support scroll bars, override 1800 * {@link RecyclerView.LayoutManager#computeVerticalScrollOffset(RecyclerView.State)} in your 1801 * LayoutManager.</p> 1802 * 1803 * @return The vertical offset of the scrollbar's thumb 1804 * @see android.support.v7.widget.RecyclerView.LayoutManager#computeVerticalScrollOffset 1805 * (RecyclerView.State) 1806 */ 1807 @Override 1808 public int computeVerticalScrollOffset() { 1809 if (mLayout == null) { 1810 return 0; 1811 } 1812 return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollOffset(mState) : 0; 1813 } 1814 1815 /** 1816 * <p>Compute the vertical extent of the vertical scrollbar's thumb within the vertical range. 1817 * This value is used to compute the length of the thumb within the scrollbar's track.</p> 1818 * 1819 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1820 * {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollOffset()}.</p> 1821 * 1822 * <p>Default implementation returns 0.</p> 1823 * 1824 * <p>If you want to support scroll bars, override 1825 * {@link RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)} in your 1826 * LayoutManager.</p> 1827 * 1828 * @return The vertical extent of the scrollbar's thumb 1829 * @see RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State) 1830 */ 1831 @Override 1832 public int computeVerticalScrollExtent() { 1833 if (mLayout == null) { 1834 return 0; 1835 } 1836 return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollExtent(mState) : 0; 1837 } 1838 1839 /** 1840 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 1841 * 1842 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1843 * {@link #computeVerticalScrollExtent()} and {@link #computeVerticalScrollOffset()}.</p> 1844 * 1845 * <p>Default implementation returns 0.</p> 1846 * 1847 * <p>If you want to support scroll bars, override 1848 * {@link RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)} in your 1849 * LayoutManager.</p> 1850 * 1851 * @return The total vertical range represented by the vertical scrollbar 1852 * @see RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State) 1853 */ 1854 @Override 1855 public int computeVerticalScrollRange() { 1856 if (mLayout == null) { 1857 return 0; 1858 } 1859 return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollRange(mState) : 0; 1860 } 1861 1862 1863 void eatRequestLayout() { 1864 mEatRequestLayout++; 1865 if (mEatRequestLayout == 1 && !mLayoutFrozen) { 1866 mLayoutRequestEaten = false; 1867 } 1868 } 1869 1870 void resumeRequestLayout(boolean performLayoutChildren) { 1871 if (mEatRequestLayout < 1) { 1872 //noinspection PointlessBooleanExpression 1873 if (DEBUG) { 1874 throw new IllegalStateException("invalid eat request layout count"); 1875 } 1876 mEatRequestLayout = 1; 1877 } 1878 if (!performLayoutChildren) { 1879 // Reset the layout request eaten counter. 1880 // This is necessary since eatRequest calls can be nested in which case the other 1881 // call will override the inner one. 1882 // for instance: 1883 // eat layout for process adapter updates 1884 // eat layout for dispatchLayout 1885 // a bunch of req layout calls arrive 1886 1887 mLayoutRequestEaten = false; 1888 } 1889 if (mEatRequestLayout == 1) { 1890 // when layout is frozen we should delay dispatchLayout() 1891 if (performLayoutChildren && mLayoutRequestEaten && !mLayoutFrozen && 1892 mLayout != null && mAdapter != null) { 1893 dispatchLayout(); 1894 } 1895 if (!mLayoutFrozen) { 1896 mLayoutRequestEaten = false; 1897 } 1898 } 1899 mEatRequestLayout--; 1900 } 1901 1902 /** 1903 * Enable or disable layout and scroll. After <code>setLayoutFrozen(true)</code> is called, 1904 * Layout requests will be postponed until <code>setLayoutFrozen(false)</code> is called; 1905 * child views are not updated when RecyclerView is frozen, {@link #smoothScrollBy(int, int)}, 1906 * {@link #scrollBy(int, int)}, {@link #scrollToPosition(int)} and 1907 * {@link #smoothScrollToPosition(int)} are dropped; TouchEvents and GenericMotionEvents are 1908 * dropped; {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} will not be 1909 * called. 1910 * 1911 * <p> 1912 * <code>setLayoutFrozen(true)</code> does not prevent app from directly calling {@link 1913 * LayoutManager#scrollToPosition(int)}, {@link LayoutManager#smoothScrollToPosition( 1914 * RecyclerView, State, int)}. 1915 * <p> 1916 * {@link #setAdapter(Adapter)} and {@link #swapAdapter(Adapter, boolean)} will automatically 1917 * stop frozen. 1918 * <p> 1919 * Note: Running ItemAnimator is not stopped automatically, it's caller's 1920 * responsibility to call ItemAnimator.end(). 1921 * 1922 * @param frozen true to freeze layout and scroll, false to re-enable. 1923 */ 1924 public void setLayoutFrozen(boolean frozen) { 1925 if (frozen != mLayoutFrozen) { 1926 assertNotInLayoutOrScroll("Do not setLayoutFrozen in layout or scroll"); 1927 if (!frozen) { 1928 mLayoutFrozen = false; 1929 if (mLayoutRequestEaten && mLayout != null && mAdapter != null) { 1930 requestLayout(); 1931 } 1932 mLayoutRequestEaten = false; 1933 } else { 1934 final long now = SystemClock.uptimeMillis(); 1935 MotionEvent cancelEvent = MotionEvent.obtain(now, now, 1936 MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0); 1937 onTouchEvent(cancelEvent); 1938 mLayoutFrozen = true; 1939 mIgnoreMotionEventTillDown = true; 1940 stopScroll(); 1941 } 1942 } 1943 } 1944 1945 /** 1946 * Returns true if layout and scroll are frozen. 1947 * 1948 * @return true if layout and scroll are frozen 1949 * @see #setLayoutFrozen(boolean) 1950 */ 1951 public boolean isLayoutFrozen() { 1952 return mLayoutFrozen; 1953 } 1954 1955 /** 1956 * Animate a scroll by the given amount of pixels along either axis. 1957 * 1958 * @param dx Pixels to scroll horizontally 1959 * @param dy Pixels to scroll vertically 1960 */ 1961 public void smoothScrollBy(int dx, int dy) { 1962 smoothScrollBy(dx, dy, null); 1963 } 1964 1965 /** 1966 * Animate a scroll by the given amount of pixels along either axis. 1967 * 1968 * @param dx Pixels to scroll horizontally 1969 * @param dy Pixels to scroll vertically 1970 * @param interpolator {@link Interpolator} to be used for scrolling. If it is 1971 * {@code null}, RecyclerView is going to use the default interpolator. 1972 */ 1973 public void smoothScrollBy(int dx, int dy, Interpolator interpolator) { 1974 if (mLayout == null) { 1975 Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " + 1976 "Call setLayoutManager with a non-null argument."); 1977 return; 1978 } 1979 if (mLayoutFrozen) { 1980 return; 1981 } 1982 if (!mLayout.canScrollHorizontally()) { 1983 dx = 0; 1984 } 1985 if (!mLayout.canScrollVertically()) { 1986 dy = 0; 1987 } 1988 if (dx != 0 || dy != 0) { 1989 mViewFlinger.smoothScrollBy(dx, dy, interpolator); 1990 } 1991 } 1992 1993 /** 1994 * Begin a standard fling with an initial velocity along each axis in pixels per second. 1995 * If the velocity given is below the system-defined minimum this method will return false 1996 * and no fling will occur. 1997 * 1998 * @param velocityX Initial horizontal velocity in pixels per second 1999 * @param velocityY Initial vertical velocity in pixels per second 2000 * @return true if the fling was started, false if the velocity was too low to fling or 2001 * LayoutManager does not support scrolling in the axis fling is issued. 2002 * 2003 * @see LayoutManager#canScrollVertically() 2004 * @see LayoutManager#canScrollHorizontally() 2005 */ 2006 public boolean fling(int velocityX, int velocityY) { 2007 if (mLayout == null) { 2008 Log.e(TAG, "Cannot fling without a LayoutManager set. " + 2009 "Call setLayoutManager with a non-null argument."); 2010 return false; 2011 } 2012 if (mLayoutFrozen) { 2013 return false; 2014 } 2015 2016 final boolean canScrollHorizontal = mLayout.canScrollHorizontally(); 2017 final boolean canScrollVertical = mLayout.canScrollVertically(); 2018 2019 if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) { 2020 velocityX = 0; 2021 } 2022 if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) { 2023 velocityY = 0; 2024 } 2025 if (velocityX == 0 && velocityY == 0) { 2026 // If we don't have any velocity, return false 2027 return false; 2028 } 2029 2030 if (!dispatchNestedPreFling(velocityX, velocityY)) { 2031 final boolean canScroll = canScrollHorizontal || canScrollVertical; 2032 dispatchNestedFling(velocityX, velocityY, canScroll); 2033 2034 if (mOnFlingListener != null && mOnFlingListener.onFling(velocityX, velocityY)) { 2035 return true; 2036 } 2037 2038 if (canScroll) { 2039 velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity)); 2040 velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity)); 2041 mViewFlinger.fling(velocityX, velocityY); 2042 return true; 2043 } 2044 } 2045 return false; 2046 } 2047 2048 /** 2049 * Stop any current scroll in progress, such as one started by 2050 * {@link #smoothScrollBy(int, int)}, {@link #fling(int, int)} or a touch-initiated fling. 2051 */ 2052 public void stopScroll() { 2053 setScrollState(SCROLL_STATE_IDLE); 2054 stopScrollersInternal(); 2055 } 2056 2057 /** 2058 * Similar to {@link #stopScroll()} but does not set the state. 2059 */ 2060 private void stopScrollersInternal() { 2061 mViewFlinger.stop(); 2062 if (mLayout != null) { 2063 mLayout.stopSmoothScroller(); 2064 } 2065 } 2066 2067 /** 2068 * Returns the minimum velocity to start a fling. 2069 * 2070 * @return The minimum velocity to start a fling 2071 */ 2072 public int getMinFlingVelocity() { 2073 return mMinFlingVelocity; 2074 } 2075 2076 2077 /** 2078 * Returns the maximum fling velocity used by this RecyclerView. 2079 * 2080 * @return The maximum fling velocity used by this RecyclerView. 2081 */ 2082 public int getMaxFlingVelocity() { 2083 return mMaxFlingVelocity; 2084 } 2085 2086 /** 2087 * Apply a pull to relevant overscroll glow effects 2088 */ 2089 private void pullGlows(float x, float overscrollX, float y, float overscrollY) { 2090 boolean invalidate = false; 2091 if (overscrollX < 0) { 2092 ensureLeftGlow(); 2093 if (mLeftGlow.onPull(-overscrollX / getWidth(), 1f - y / getHeight())) { 2094 invalidate = true; 2095 } 2096 } else if (overscrollX > 0) { 2097 ensureRightGlow(); 2098 if (mRightGlow.onPull(overscrollX / getWidth(), y / getHeight())) { 2099 invalidate = true; 2100 } 2101 } 2102 2103 if (overscrollY < 0) { 2104 ensureTopGlow(); 2105 if (mTopGlow.onPull(-overscrollY / getHeight(), x / getWidth())) { 2106 invalidate = true; 2107 } 2108 } else if (overscrollY > 0) { 2109 ensureBottomGlow(); 2110 if (mBottomGlow.onPull(overscrollY / getHeight(), 1f - x / getWidth())) { 2111 invalidate = true; 2112 } 2113 } 2114 2115 if (invalidate || overscrollX != 0 || overscrollY != 0) { 2116 ViewCompat.postInvalidateOnAnimation(this); 2117 } 2118 } 2119 2120 private void releaseGlows() { 2121 boolean needsInvalidate = false; 2122 if (mLeftGlow != null) needsInvalidate = mLeftGlow.onRelease(); 2123 if (mTopGlow != null) needsInvalidate |= mTopGlow.onRelease(); 2124 if (mRightGlow != null) needsInvalidate |= mRightGlow.onRelease(); 2125 if (mBottomGlow != null) needsInvalidate |= mBottomGlow.onRelease(); 2126 if (needsInvalidate) { 2127 ViewCompat.postInvalidateOnAnimation(this); 2128 } 2129 } 2130 2131 void considerReleasingGlowsOnScroll(int dx, int dy) { 2132 boolean needsInvalidate = false; 2133 if (mLeftGlow != null && !mLeftGlow.isFinished() && dx > 0) { 2134 needsInvalidate = mLeftGlow.onRelease(); 2135 } 2136 if (mRightGlow != null && !mRightGlow.isFinished() && dx < 0) { 2137 needsInvalidate |= mRightGlow.onRelease(); 2138 } 2139 if (mTopGlow != null && !mTopGlow.isFinished() && dy > 0) { 2140 needsInvalidate |= mTopGlow.onRelease(); 2141 } 2142 if (mBottomGlow != null && !mBottomGlow.isFinished() && dy < 0) { 2143 needsInvalidate |= mBottomGlow.onRelease(); 2144 } 2145 if (needsInvalidate) { 2146 ViewCompat.postInvalidateOnAnimation(this); 2147 } 2148 } 2149 2150 void absorbGlows(int velocityX, int velocityY) { 2151 if (velocityX < 0) { 2152 ensureLeftGlow(); 2153 mLeftGlow.onAbsorb(-velocityX); 2154 } else if (velocityX > 0) { 2155 ensureRightGlow(); 2156 mRightGlow.onAbsorb(velocityX); 2157 } 2158 2159 if (velocityY < 0) { 2160 ensureTopGlow(); 2161 mTopGlow.onAbsorb(-velocityY); 2162 } else if (velocityY > 0) { 2163 ensureBottomGlow(); 2164 mBottomGlow.onAbsorb(velocityY); 2165 } 2166 2167 if (velocityX != 0 || velocityY != 0) { 2168 ViewCompat.postInvalidateOnAnimation(this); 2169 } 2170 } 2171 2172 void ensureLeftGlow() { 2173 if (mLeftGlow != null) { 2174 return; 2175 } 2176 mLeftGlow = new EdgeEffectCompat(getContext()); 2177 if (mClipToPadding) { 2178 mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), 2179 getMeasuredWidth() - getPaddingLeft() - getPaddingRight()); 2180 } else { 2181 mLeftGlow.setSize(getMeasuredHeight(), getMeasuredWidth()); 2182 } 2183 } 2184 2185 void ensureRightGlow() { 2186 if (mRightGlow != null) { 2187 return; 2188 } 2189 mRightGlow = new EdgeEffectCompat(getContext()); 2190 if (mClipToPadding) { 2191 mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), 2192 getMeasuredWidth() - getPaddingLeft() - getPaddingRight()); 2193 } else { 2194 mRightGlow.setSize(getMeasuredHeight(), getMeasuredWidth()); 2195 } 2196 } 2197 2198 void ensureTopGlow() { 2199 if (mTopGlow != null) { 2200 return; 2201 } 2202 mTopGlow = new EdgeEffectCompat(getContext()); 2203 if (mClipToPadding) { 2204 mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), 2205 getMeasuredHeight() - getPaddingTop() - getPaddingBottom()); 2206 } else { 2207 mTopGlow.setSize(getMeasuredWidth(), getMeasuredHeight()); 2208 } 2209 2210 } 2211 2212 void ensureBottomGlow() { 2213 if (mBottomGlow != null) { 2214 return; 2215 } 2216 mBottomGlow = new EdgeEffectCompat(getContext()); 2217 if (mClipToPadding) { 2218 mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), 2219 getMeasuredHeight() - getPaddingTop() - getPaddingBottom()); 2220 } else { 2221 mBottomGlow.setSize(getMeasuredWidth(), getMeasuredHeight()); 2222 } 2223 } 2224 2225 void invalidateGlows() { 2226 mLeftGlow = mRightGlow = mTopGlow = mBottomGlow = null; 2227 } 2228 2229 /** 2230 * Since RecyclerView is a collection ViewGroup that includes virtual children (items that are 2231 * in the Adapter but not visible in the UI), it employs a more involved focus search strategy 2232 * that differs from other ViewGroups. 2233 * <p> 2234 * It first does a focus search within the RecyclerView. If this search finds a View that is in 2235 * the focus direction with respect to the currently focused View, RecyclerView returns that 2236 * child as the next focus target. When it cannot find such child, it calls 2237 * {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} to layout more Views 2238 * in the focus search direction. If LayoutManager adds a View that matches the 2239 * focus search criteria, it will be returned as the focus search result. Otherwise, 2240 * RecyclerView will call parent to handle the focus search like a regular ViewGroup. 2241 * <p> 2242 * When the direction is {@link View#FOCUS_FORWARD} or {@link View#FOCUS_BACKWARD}, a View that 2243 * is not in the focus direction is still valid focus target which may not be the desired 2244 * behavior if the Adapter has more children in the focus direction. To handle this case, 2245 * RecyclerView converts the focus direction to an absolute direction and makes a preliminary 2246 * focus search in that direction. If there are no Views to gain focus, it will call 2247 * {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} before running a 2248 * focus search with the original (relative) direction. This allows RecyclerView to provide 2249 * better candidates to the focus search while still allowing the view system to take focus from 2250 * the RecyclerView and give it to a more suitable child if such child exists. 2251 * 2252 * @param focused The view that currently has focus 2253 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 2254 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, {@link View#FOCUS_FORWARD}, 2255 * {@link View#FOCUS_BACKWARD} or 0 for not applicable. 2256 * 2257 * @return A new View that can be the next focus after the focused View 2258 */ 2259 @Override 2260 public View focusSearch(View focused, int direction) { 2261 View result = mLayout.onInterceptFocusSearch(focused, direction); 2262 if (result != null) { 2263 return result; 2264 } 2265 final boolean canRunFocusFailure = mAdapter != null && mLayout != null 2266 && !isComputingLayout() && !mLayoutFrozen; 2267 2268 final FocusFinder ff = FocusFinder.getInstance(); 2269 if (canRunFocusFailure 2270 && (direction == View.FOCUS_FORWARD || direction == View.FOCUS_BACKWARD)) { 2271 // convert direction to absolute direction and see if we have a view there and if not 2272 // tell LayoutManager to add if it can. 2273 boolean needsFocusFailureLayout = false; 2274 if (mLayout.canScrollVertically()) { 2275 final int absDir = 2276 direction == View.FOCUS_FORWARD ? View.FOCUS_DOWN : View.FOCUS_UP; 2277 final View found = ff.findNextFocus(this, focused, absDir); 2278 needsFocusFailureLayout = found == null; 2279 if (FORCE_ABS_FOCUS_SEARCH_DIRECTION) { 2280 // Workaround for broken FOCUS_BACKWARD in API 15 and older devices. 2281 direction = absDir; 2282 } 2283 } 2284 if (!needsFocusFailureLayout && mLayout.canScrollHorizontally()) { 2285 boolean rtl = mLayout.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; 2286 final int absDir = (direction == View.FOCUS_FORWARD) ^ rtl 2287 ? View.FOCUS_RIGHT : View.FOCUS_LEFT; 2288 final View found = ff.findNextFocus(this, focused, absDir); 2289 needsFocusFailureLayout = found == null; 2290 if (FORCE_ABS_FOCUS_SEARCH_DIRECTION) { 2291 // Workaround for broken FOCUS_BACKWARD in API 15 and older devices. 2292 direction = absDir; 2293 } 2294 } 2295 if (needsFocusFailureLayout) { 2296 consumePendingUpdateOperations(); 2297 final View focusedItemView = findContainingItemView(focused); 2298 if (focusedItemView == null) { 2299 // panic, focused view is not a child anymore, cannot call super. 2300 return null; 2301 } 2302 eatRequestLayout(); 2303 mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState); 2304 resumeRequestLayout(false); 2305 } 2306 result = ff.findNextFocus(this, focused, direction); 2307 } else { 2308 result = ff.findNextFocus(this, focused, direction); 2309 if (result == null && canRunFocusFailure) { 2310 consumePendingUpdateOperations(); 2311 final View focusedItemView = findContainingItemView(focused); 2312 if (focusedItemView == null) { 2313 // panic, focused view is not a child anymore, cannot call super. 2314 return null; 2315 } 2316 eatRequestLayout(); 2317 result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState); 2318 resumeRequestLayout(false); 2319 } 2320 } 2321 return isPreferredNextFocus(focused, result, direction) 2322 ? result : super.focusSearch(focused, direction); 2323 } 2324 2325 /** 2326 * Checks if the new focus candidate is a good enough candidate such that RecyclerView will 2327 * assign it as the next focus View instead of letting view hierarchy decide. 2328 * A good candidate means a View that is aligned in the focus direction wrt the focused View 2329 * and is not the RecyclerView itself. 2330 * When this method returns false, RecyclerView will let the parent make the decision so the 2331 * same View may still get the focus as a result of that search. 2332 */ 2333 private boolean isPreferredNextFocus(View focused, View next, int direction) { 2334 if (next == null || next == this) { 2335 return false; 2336 } 2337 if (focused == null) { 2338 return true; 2339 } 2340 2341 if(direction == View.FOCUS_FORWARD || direction == View.FOCUS_BACKWARD) { 2342 final boolean rtl = mLayout.getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL; 2343 final int absHorizontal = (direction == View.FOCUS_FORWARD) ^ rtl 2344 ? View.FOCUS_RIGHT : View.FOCUS_LEFT; 2345 if (isPreferredNextFocusAbsolute(focused, next, absHorizontal)) { 2346 return true; 2347 } 2348 if (direction == View.FOCUS_FORWARD) { 2349 return isPreferredNextFocusAbsolute(focused, next, View.FOCUS_DOWN); 2350 } else { 2351 return isPreferredNextFocusAbsolute(focused, next, View.FOCUS_UP); 2352 } 2353 } else { 2354 return isPreferredNextFocusAbsolute(focused, next, direction); 2355 } 2356 2357 } 2358 2359 /** 2360 * Logic taken from FocusSearch#isCandidate 2361 */ 2362 private boolean isPreferredNextFocusAbsolute(View focused, View next, int direction) { 2363 mTempRect.set(0, 0, focused.getWidth(), focused.getHeight()); 2364 mTempRect2.set(0, 0, next.getWidth(), next.getHeight()); 2365 offsetDescendantRectToMyCoords(focused, mTempRect); 2366 offsetDescendantRectToMyCoords(next, mTempRect2); 2367 switch (direction) { 2368 case View.FOCUS_LEFT: 2369 return (mTempRect.right > mTempRect2.right 2370 || mTempRect.left >= mTempRect2.right) 2371 && mTempRect.left > mTempRect2.left; 2372 case View.FOCUS_RIGHT: 2373 return (mTempRect.left < mTempRect2.left 2374 || mTempRect.right <= mTempRect2.left) 2375 && mTempRect.right < mTempRect2.right; 2376 case View.FOCUS_UP: 2377 return (mTempRect.bottom > mTempRect2.bottom 2378 || mTempRect.top >= mTempRect2.bottom) 2379 && mTempRect.top > mTempRect2.top; 2380 case View.FOCUS_DOWN: 2381 return (mTempRect.top < mTempRect2.top 2382 || mTempRect.bottom <= mTempRect2.top) 2383 && mTempRect.bottom < mTempRect2.bottom; 2384 } 2385 throw new IllegalArgumentException("direction must be absolute. received:" + direction); 2386 } 2387 2388 @Override 2389 public void requestChildFocus(View child, View focused) { 2390 if (!mLayout.onRequestChildFocus(this, mState, child, focused) && focused != null) { 2391 mTempRect.set(0, 0, focused.getWidth(), focused.getHeight()); 2392 2393 // get item decor offsets w/o refreshing. If they are invalid, there will be another 2394 // layout pass to fix them, then it is LayoutManager's responsibility to keep focused 2395 // View in viewport. 2396 final ViewGroup.LayoutParams focusedLayoutParams = focused.getLayoutParams(); 2397 if (focusedLayoutParams instanceof LayoutParams) { 2398 // if focused child has item decors, use them. Otherwise, ignore. 2399 final LayoutParams lp = (LayoutParams) focusedLayoutParams; 2400 if (!lp.mInsetsDirty) { 2401 final Rect insets = lp.mDecorInsets; 2402 mTempRect.left -= insets.left; 2403 mTempRect.right += insets.right; 2404 mTempRect.top -= insets.top; 2405 mTempRect.bottom += insets.bottom; 2406 } 2407 } 2408 2409 offsetDescendantRectToMyCoords(focused, mTempRect); 2410 offsetRectIntoDescendantCoords(child, mTempRect); 2411 requestChildRectangleOnScreen(child, mTempRect, !mFirstLayoutComplete); 2412 } 2413 super.requestChildFocus(child, focused); 2414 } 2415 2416 @Override 2417 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { 2418 return mLayout.requestChildRectangleOnScreen(this, child, rect, immediate); 2419 } 2420 2421 @Override 2422 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 2423 if (mLayout == null || !mLayout.onAddFocusables(this, views, direction, focusableMode)) { 2424 super.addFocusables(views, direction, focusableMode); 2425 } 2426 } 2427 2428 @Override 2429 protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 2430 if (isComputingLayout()) { 2431 // if we are in the middle of a layout calculation, don't let any child take focus. 2432 // RV will handle it after layout calculation is finished. 2433 return false; 2434 } 2435 return super.onRequestFocusInDescendants(direction, previouslyFocusedRect); 2436 } 2437 2438 @Override 2439 protected void onAttachedToWindow() { 2440 super.onAttachedToWindow(); 2441 mLayoutOrScrollCounter = 0; 2442 mIsAttached = true; 2443 mFirstLayoutComplete = mFirstLayoutComplete && !isLayoutRequested(); 2444 if (mLayout != null) { 2445 mLayout.dispatchAttachedToWindow(this); 2446 } 2447 mPostedAnimatorRunner = false; 2448 2449 if (ALLOW_THREAD_GAP_WORK) { 2450 // Register with gap worker 2451 mGapWorker = GapWorker.sGapWorker.get(); 2452 if (mGapWorker == null) { 2453 mGapWorker = new GapWorker(); 2454 2455 // break 60 fps assumption if data from display appears valid 2456 // NOTE: we only do this query once, statically, because it's very expensive (> 1ms) 2457 Display display = ViewCompat.getDisplay(this); 2458 float refreshRate = 60.0f; 2459 if (!isInEditMode() && display != null) { 2460 float displayRefreshRate = display.getRefreshRate(); 2461 if (displayRefreshRate >= 30.0f) { 2462 refreshRate = displayRefreshRate; 2463 } 2464 } 2465 mGapWorker.mFrameIntervalNs = (long) (1000000000 / refreshRate); 2466 GapWorker.sGapWorker.set(mGapWorker); 2467 } 2468 mGapWorker.add(this); 2469 } 2470 } 2471 2472 @Override 2473 protected void onDetachedFromWindow() { 2474 super.onDetachedFromWindow(); 2475 if (mItemAnimator != null) { 2476 mItemAnimator.endAnimations(); 2477 } 2478 stopScroll(); 2479 mIsAttached = false; 2480 if (mLayout != null) { 2481 mLayout.dispatchDetachedFromWindow(this, mRecycler); 2482 } 2483 mPendingAccessibilityImportanceChange.clear(); 2484 removeCallbacks(mItemAnimatorRunner); 2485 mViewInfoStore.onDetach(); 2486 2487 if (ALLOW_THREAD_GAP_WORK) { 2488 // Unregister with gap worker 2489 mGapWorker.remove(this); 2490 mGapWorker = null; 2491 } 2492 } 2493 2494 /** 2495 * Returns true if RecyclerView is attached to window. 2496 */ 2497 // @override 2498 public boolean isAttachedToWindow() { 2499 return mIsAttached; 2500 } 2501 2502 /** 2503 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 2504 * {@link IllegalStateException} if it <b>is not</b>. 2505 * 2506 * @param message The message for the exception. Can be null. 2507 * @see #assertNotInLayoutOrScroll(String) 2508 */ 2509 void assertInLayoutOrScroll(String message) { 2510 if (!isComputingLayout()) { 2511 if (message == null) { 2512 throw new IllegalStateException("Cannot call this method unless RecyclerView is " 2513 + "computing a layout or scrolling"); 2514 } 2515 throw new IllegalStateException(message); 2516 2517 } 2518 } 2519 2520 /** 2521 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 2522 * {@link IllegalStateException} if it <b>is</b>. 2523 * 2524 * @param message The message for the exception. Can be null. 2525 * @see #assertInLayoutOrScroll(String) 2526 */ 2527 void assertNotInLayoutOrScroll(String message) { 2528 if (isComputingLayout()) { 2529 if (message == null) { 2530 throw new IllegalStateException("Cannot call this method while RecyclerView is " 2531 + "computing a layout or scrolling"); 2532 } 2533 throw new IllegalStateException(message); 2534 } 2535 if (mDispatchScrollCounter > 0) { 2536 Log.w(TAG, "Cannot call this method in a scroll callback. Scroll callbacks might be run" 2537 + " during a measure & layout pass where you cannot change the RecyclerView" 2538 + " data. Any method call that might change the structure of the RecyclerView" 2539 + " or the adapter contents should be postponed to the next frame.", 2540 new IllegalStateException("")); 2541 } 2542 } 2543 2544 /** 2545 * Add an {@link OnItemTouchListener} to intercept touch events before they are dispatched 2546 * to child views or this view's standard scrolling behavior. 2547 * 2548 * <p>Client code may use listeners to implement item manipulation behavior. Once a listener 2549 * returns true from 2550 * {@link OnItemTouchListener#onInterceptTouchEvent(RecyclerView, MotionEvent)} its 2551 * {@link OnItemTouchListener#onTouchEvent(RecyclerView, MotionEvent)} method will be called 2552 * for each incoming MotionEvent until the end of the gesture.</p> 2553 * 2554 * @param listener Listener to add 2555 * @see SimpleOnItemTouchListener 2556 */ 2557 public void addOnItemTouchListener(OnItemTouchListener listener) { 2558 mOnItemTouchListeners.add(listener); 2559 } 2560 2561 /** 2562 * Remove an {@link OnItemTouchListener}. It will no longer be able to intercept touch events. 2563 * 2564 * @param listener Listener to remove 2565 */ 2566 public void removeOnItemTouchListener(OnItemTouchListener listener) { 2567 mOnItemTouchListeners.remove(listener); 2568 if (mActiveOnItemTouchListener == listener) { 2569 mActiveOnItemTouchListener = null; 2570 } 2571 } 2572 2573 private boolean dispatchOnItemTouchIntercept(MotionEvent e) { 2574 final int action = e.getAction(); 2575 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_DOWN) { 2576 mActiveOnItemTouchListener = null; 2577 } 2578 2579 final int listenerCount = mOnItemTouchListeners.size(); 2580 for (int i = 0; i < listenerCount; i++) { 2581 final OnItemTouchListener listener = mOnItemTouchListeners.get(i); 2582 if (listener.onInterceptTouchEvent(this, e) && action != MotionEvent.ACTION_CANCEL) { 2583 mActiveOnItemTouchListener = listener; 2584 return true; 2585 } 2586 } 2587 return false; 2588 } 2589 2590 private boolean dispatchOnItemTouch(MotionEvent e) { 2591 final int action = e.getAction(); 2592 if (mActiveOnItemTouchListener != null) { 2593 if (action == MotionEvent.ACTION_DOWN) { 2594 // Stale state from a previous gesture, we're starting a new one. Clear it. 2595 mActiveOnItemTouchListener = null; 2596 } else { 2597 mActiveOnItemTouchListener.onTouchEvent(this, e); 2598 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 2599 // Clean up for the next gesture. 2600 mActiveOnItemTouchListener = null; 2601 } 2602 return true; 2603 } 2604 } 2605 2606 // Listeners will have already received the ACTION_DOWN via dispatchOnItemTouchIntercept 2607 // as called from onInterceptTouchEvent; skip it. 2608 if (action != MotionEvent.ACTION_DOWN) { 2609 final int listenerCount = mOnItemTouchListeners.size(); 2610 for (int i = 0; i < listenerCount; i++) { 2611 final OnItemTouchListener listener = mOnItemTouchListeners.get(i); 2612 if (listener.onInterceptTouchEvent(this, e)) { 2613 mActiveOnItemTouchListener = listener; 2614 return true; 2615 } 2616 } 2617 } 2618 return false; 2619 } 2620 2621 @Override 2622 public boolean onInterceptTouchEvent(MotionEvent e) { 2623 if (mLayoutFrozen) { 2624 // When layout is frozen, RV does not intercept the motion event. 2625 // A child view e.g. a button may still get the click. 2626 return false; 2627 } 2628 if (dispatchOnItemTouchIntercept(e)) { 2629 cancelTouch(); 2630 return true; 2631 } 2632 2633 if (mLayout == null) { 2634 return false; 2635 } 2636 2637 final boolean canScrollHorizontally = mLayout.canScrollHorizontally(); 2638 final boolean canScrollVertically = mLayout.canScrollVertically(); 2639 2640 if (mVelocityTracker == null) { 2641 mVelocityTracker = VelocityTracker.obtain(); 2642 } 2643 mVelocityTracker.addMovement(e); 2644 2645 final int action = MotionEventCompat.getActionMasked(e); 2646 final int actionIndex = MotionEventCompat.getActionIndex(e); 2647 2648 switch (action) { 2649 case MotionEvent.ACTION_DOWN: 2650 if (mIgnoreMotionEventTillDown) { 2651 mIgnoreMotionEventTillDown = false; 2652 } 2653 mScrollPointerId = e.getPointerId(0); 2654 mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f); 2655 mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f); 2656 2657 if (mScrollState == SCROLL_STATE_SETTLING) { 2658 getParent().requestDisallowInterceptTouchEvent(true); 2659 setScrollState(SCROLL_STATE_DRAGGING); 2660 } 2661 2662 // Clear the nested offsets 2663 mNestedOffsets[0] = mNestedOffsets[1] = 0; 2664 2665 int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE; 2666 if (canScrollHorizontally) { 2667 nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL; 2668 } 2669 if (canScrollVertically) { 2670 nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL; 2671 } 2672 startNestedScroll(nestedScrollAxis); 2673 break; 2674 2675 case MotionEventCompat.ACTION_POINTER_DOWN: 2676 mScrollPointerId = e.getPointerId(actionIndex); 2677 mInitialTouchX = mLastTouchX = (int) (e.getX(actionIndex) + 0.5f); 2678 mInitialTouchY = mLastTouchY = (int) (e.getY(actionIndex) + 0.5f); 2679 break; 2680 2681 case MotionEvent.ACTION_MOVE: { 2682 final int index = e.findPointerIndex(mScrollPointerId); 2683 if (index < 0) { 2684 Log.e(TAG, "Error processing scroll; pointer index for id " + 2685 mScrollPointerId + " not found. Did any MotionEvents get skipped?"); 2686 return false; 2687 } 2688 2689 final int x = (int) (e.getX(index) + 0.5f); 2690 final int y = (int) (e.getY(index) + 0.5f); 2691 if (mScrollState != SCROLL_STATE_DRAGGING) { 2692 final int dx = x - mInitialTouchX; 2693 final int dy = y - mInitialTouchY; 2694 boolean startScroll = false; 2695 if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) { 2696 mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1); 2697 startScroll = true; 2698 } 2699 if (canScrollVertically && Math.abs(dy) > mTouchSlop) { 2700 mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1); 2701 startScroll = true; 2702 } 2703 if (startScroll) { 2704 setScrollState(SCROLL_STATE_DRAGGING); 2705 } 2706 } 2707 } break; 2708 2709 case MotionEventCompat.ACTION_POINTER_UP: { 2710 onPointerUp(e); 2711 } break; 2712 2713 case MotionEvent.ACTION_UP: { 2714 mVelocityTracker.clear(); 2715 stopNestedScroll(); 2716 } break; 2717 2718 case MotionEvent.ACTION_CANCEL: { 2719 cancelTouch(); 2720 } 2721 } 2722 return mScrollState == SCROLL_STATE_DRAGGING; 2723 } 2724 2725 @Override 2726 public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { 2727 final int listenerCount = mOnItemTouchListeners.size(); 2728 for (int i = 0; i < listenerCount; i++) { 2729 final OnItemTouchListener listener = mOnItemTouchListeners.get(i); 2730 listener.onRequestDisallowInterceptTouchEvent(disallowIntercept); 2731 } 2732 super.requestDisallowInterceptTouchEvent(disallowIntercept); 2733 } 2734 2735 @Override 2736 public boolean onTouchEvent(MotionEvent e) { 2737 if (mLayoutFrozen || mIgnoreMotionEventTillDown) { 2738 return false; 2739 } 2740 if (dispatchOnItemTouch(e)) { 2741 cancelTouch(); 2742 return true; 2743 } 2744 2745 if (mLayout == null) { 2746 return false; 2747 } 2748 2749 final boolean canScrollHorizontally = mLayout.canScrollHorizontally(); 2750 final boolean canScrollVertically = mLayout.canScrollVertically(); 2751 2752 if (mVelocityTracker == null) { 2753 mVelocityTracker = VelocityTracker.obtain(); 2754 } 2755 boolean eventAddedToVelocityTracker = false; 2756 2757 final MotionEvent vtev = MotionEvent.obtain(e); 2758 final int action = MotionEventCompat.getActionMasked(e); 2759 final int actionIndex = MotionEventCompat.getActionIndex(e); 2760 2761 if (action == MotionEvent.ACTION_DOWN) { 2762 mNestedOffsets[0] = mNestedOffsets[1] = 0; 2763 } 2764 vtev.offsetLocation(mNestedOffsets[0], mNestedOffsets[1]); 2765 2766 switch (action) { 2767 case MotionEvent.ACTION_DOWN: { 2768 mScrollPointerId = e.getPointerId(0); 2769 mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f); 2770 mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f); 2771 2772 int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE; 2773 if (canScrollHorizontally) { 2774 nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL; 2775 } 2776 if (canScrollVertically) { 2777 nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL; 2778 } 2779 startNestedScroll(nestedScrollAxis); 2780 } break; 2781 2782 case MotionEventCompat.ACTION_POINTER_DOWN: { 2783 mScrollPointerId = e.getPointerId(actionIndex); 2784 mInitialTouchX = mLastTouchX = (int) (e.getX(actionIndex) + 0.5f); 2785 mInitialTouchY = mLastTouchY = (int) (e.getY(actionIndex) + 0.5f); 2786 } break; 2787 2788 case MotionEvent.ACTION_MOVE: { 2789 final int index = e.findPointerIndex(mScrollPointerId); 2790 if (index < 0) { 2791 Log.e(TAG, "Error processing scroll; pointer index for id " + 2792 mScrollPointerId + " not found. Did any MotionEvents get skipped?"); 2793 return false; 2794 } 2795 2796 final int x = (int) (e.getX(index) + 0.5f); 2797 final int y = (int) (e.getY(index) + 0.5f); 2798 int dx = mLastTouchX - x; 2799 int dy = mLastTouchY - y; 2800 2801 if (dispatchNestedPreScroll(dx, dy, mScrollConsumed, mScrollOffset)) { 2802 dx -= mScrollConsumed[0]; 2803 dy -= mScrollConsumed[1]; 2804 vtev.offsetLocation(mScrollOffset[0], mScrollOffset[1]); 2805 // Updated the nested offsets 2806 mNestedOffsets[0] += mScrollOffset[0]; 2807 mNestedOffsets[1] += mScrollOffset[1]; 2808 } 2809 2810 if (mScrollState != SCROLL_STATE_DRAGGING) { 2811 boolean startScroll = false; 2812 if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) { 2813 if (dx > 0) { 2814 dx -= mTouchSlop; 2815 } else { 2816 dx += mTouchSlop; 2817 } 2818 startScroll = true; 2819 } 2820 if (canScrollVertically && Math.abs(dy) > mTouchSlop) { 2821 if (dy > 0) { 2822 dy -= mTouchSlop; 2823 } else { 2824 dy += mTouchSlop; 2825 } 2826 startScroll = true; 2827 } 2828 if (startScroll) { 2829 setScrollState(SCROLL_STATE_DRAGGING); 2830 } 2831 } 2832 2833 if (mScrollState == SCROLL_STATE_DRAGGING) { 2834 mLastTouchX = x - mScrollOffset[0]; 2835 mLastTouchY = y - mScrollOffset[1]; 2836 2837 if (scrollByInternal( 2838 canScrollHorizontally ? dx : 0, 2839 canScrollVertically ? dy : 0, 2840 vtev)) { 2841 getParent().requestDisallowInterceptTouchEvent(true); 2842 } 2843 if (mGapWorker != null && (dx != 0 || dy != 0)) { 2844 mGapWorker.postFromTraversal(this, dx, dy); 2845 } 2846 } 2847 } break; 2848 2849 case MotionEventCompat.ACTION_POINTER_UP: { 2850 onPointerUp(e); 2851 } break; 2852 2853 case MotionEvent.ACTION_UP: { 2854 mVelocityTracker.addMovement(vtev); 2855 eventAddedToVelocityTracker = true; 2856 mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity); 2857 final float xvel = canScrollHorizontally ? 2858 -VelocityTrackerCompat.getXVelocity(mVelocityTracker, mScrollPointerId) : 0; 2859 final float yvel = canScrollVertically ? 2860 -VelocityTrackerCompat.getYVelocity(mVelocityTracker, mScrollPointerId) : 0; 2861 if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) { 2862 setScrollState(SCROLL_STATE_IDLE); 2863 } 2864 resetTouch(); 2865 } break; 2866 2867 case MotionEvent.ACTION_CANCEL: { 2868 cancelTouch(); 2869 } break; 2870 } 2871 2872 if (!eventAddedToVelocityTracker) { 2873 mVelocityTracker.addMovement(vtev); 2874 } 2875 vtev.recycle(); 2876 2877 return true; 2878 } 2879 2880 private void resetTouch() { 2881 if (mVelocityTracker != null) { 2882 mVelocityTracker.clear(); 2883 } 2884 stopNestedScroll(); 2885 releaseGlows(); 2886 } 2887 2888 private void cancelTouch() { 2889 resetTouch(); 2890 setScrollState(SCROLL_STATE_IDLE); 2891 } 2892 2893 private void onPointerUp(MotionEvent e) { 2894 final int actionIndex = MotionEventCompat.getActionIndex(e); 2895 if (e.getPointerId(actionIndex) == mScrollPointerId) { 2896 // Pick a new pointer to pick up the slack. 2897 final int newIndex = actionIndex == 0 ? 1 : 0; 2898 mScrollPointerId = e.getPointerId(newIndex); 2899 mInitialTouchX = mLastTouchX = (int) (e.getX(newIndex) + 0.5f); 2900 mInitialTouchY = mLastTouchY = (int) (e.getY(newIndex) + 0.5f); 2901 } 2902 } 2903 2904 // @Override 2905 public boolean onGenericMotionEvent(MotionEvent event) { 2906 if (mLayout == null) { 2907 return false; 2908 } 2909 if (mLayoutFrozen) { 2910 return false; 2911 } 2912 if ((event.getSource() & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) { 2913 if (event.getAction() == MotionEventCompat.ACTION_SCROLL) { 2914 final float vScroll, hScroll; 2915 if (mLayout.canScrollVertically()) { 2916 // Inverse the sign of the vertical scroll to align the scroll orientation 2917 // with AbsListView. 2918 vScroll = -MotionEventCompat 2919 .getAxisValue(event, MotionEventCompat.AXIS_VSCROLL); 2920 } else { 2921 vScroll = 0f; 2922 } 2923 if (mLayout.canScrollHorizontally()) { 2924 hScroll = MotionEventCompat 2925 .getAxisValue(event, MotionEventCompat.AXIS_HSCROLL); 2926 } else { 2927 hScroll = 0f; 2928 } 2929 2930 if (vScroll != 0 || hScroll != 0) { 2931 final float scrollFactor = getScrollFactor(); 2932 scrollByInternal((int) (hScroll * scrollFactor), 2933 (int) (vScroll * scrollFactor), event); 2934 } 2935 } 2936 } 2937 return false; 2938 } 2939 2940 /** 2941 * Ported from View.getVerticalScrollFactor. 2942 */ 2943 private float getScrollFactor() { 2944 if (mScrollFactor == Float.MIN_VALUE) { 2945 TypedValue outValue = new TypedValue(); 2946 if (getContext().getTheme().resolveAttribute( 2947 android.R.attr.listPreferredItemHeight, outValue, true)) { 2948 mScrollFactor = outValue.getDimension( 2949 getContext().getResources().getDisplayMetrics()); 2950 } else { 2951 return 0; //listPreferredItemHeight is not defined, no generic scrolling 2952 } 2953 } 2954 return mScrollFactor; 2955 } 2956 2957 @Override 2958 protected void onMeasure(int widthSpec, int heightSpec) { 2959 if (mLayout == null) { 2960 defaultOnMeasure(widthSpec, heightSpec); 2961 return; 2962 } 2963 if (mLayout.mAutoMeasure) { 2964 final int widthMode = MeasureSpec.getMode(widthSpec); 2965 final int heightMode = MeasureSpec.getMode(heightSpec); 2966 final boolean skipMeasure = widthMode == MeasureSpec.EXACTLY 2967 && heightMode == MeasureSpec.EXACTLY; 2968 mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec); 2969 if (skipMeasure || mAdapter == null) { 2970 return; 2971 } 2972 if (mState.mLayoutStep == State.STEP_START) { 2973 dispatchLayoutStep1(); 2974 } 2975 // set dimensions in 2nd step. Pre-layout should happen with old dimensions for 2976 // consistency 2977 mLayout.setMeasureSpecs(widthSpec, heightSpec); 2978 mState.mIsMeasuring = true; 2979 dispatchLayoutStep2(); 2980 2981 // now we can get the width and height from the children. 2982 mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec); 2983 2984 // if RecyclerView has non-exact width and height and if there is at least one child 2985 // which also has non-exact width & height, we have to re-measure. 2986 if (mLayout.shouldMeasureTwice()) { 2987 mLayout.setMeasureSpecs( 2988 MeasureSpec.makeMeasureSpec(getMeasuredWidth(), MeasureSpec.EXACTLY), 2989 MeasureSpec.makeMeasureSpec(getMeasuredHeight(), MeasureSpec.EXACTLY)); 2990 mState.mIsMeasuring = true; 2991 dispatchLayoutStep2(); 2992 // now we can get the width and height from the children. 2993 mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec); 2994 } 2995 } else { 2996 if (mHasFixedSize) { 2997 mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec); 2998 return; 2999 } 3000 // custom onMeasure 3001 if (mAdapterUpdateDuringMeasure) { 3002 eatRequestLayout(); 3003 onEnterLayoutOrScroll(); 3004 processAdapterUpdatesAndSetAnimationFlags(); 3005 onExitLayoutOrScroll(); 3006 3007 if (mState.mRunPredictiveAnimations) { 3008 mState.mInPreLayout = true; 3009 } else { 3010 // consume remaining updates to provide a consistent state with the layout pass. 3011 mAdapterHelper.consumeUpdatesInOnePass(); 3012 mState.mInPreLayout = false; 3013 } 3014 mAdapterUpdateDuringMeasure = false; 3015 resumeRequestLayout(false); 3016 } 3017 3018 if (mAdapter != null) { 3019 mState.mItemCount = mAdapter.getItemCount(); 3020 } else { 3021 mState.mItemCount = 0; 3022 } 3023 eatRequestLayout(); 3024 mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec); 3025 resumeRequestLayout(false); 3026 mState.mInPreLayout = false; // clear 3027 } 3028 } 3029 3030 /** 3031 * Used when onMeasure is called before layout manager is set 3032 */ 3033 void defaultOnMeasure(int widthSpec, int heightSpec) { 3034 // calling LayoutManager here is not pretty but that API is already public and it is better 3035 // than creating another method since this is internal. 3036 final int width = LayoutManager.chooseSize(widthSpec, 3037 getPaddingLeft() + getPaddingRight(), 3038 ViewCompat.getMinimumWidth(this)); 3039 final int height = LayoutManager.chooseSize(heightSpec, 3040 getPaddingTop() + getPaddingBottom(), 3041 ViewCompat.getMinimumHeight(this)); 3042 3043 setMeasuredDimension(width, height); 3044 } 3045 3046 @Override 3047 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 3048 super.onSizeChanged(w, h, oldw, oldh); 3049 if (w != oldw || h != oldh) { 3050 invalidateGlows(); 3051 // layout's w/h are updated during measure/layout steps. 3052 } 3053 } 3054 3055 /** 3056 * Sets the {@link ItemAnimator} that will handle animations involving changes 3057 * to the items in this RecyclerView. By default, RecyclerView instantiates and 3058 * uses an instance of {@link DefaultItemAnimator}. Whether item animations are 3059 * enabled for the RecyclerView depends on the ItemAnimator and whether 3060 * the LayoutManager {@link LayoutManager#supportsPredictiveItemAnimations() 3061 * supports item animations}. 3062 * 3063 * @param animator The ItemAnimator being set. If null, no animations will occur 3064 * when changes occur to the items in this RecyclerView. 3065 */ 3066 public void setItemAnimator(ItemAnimator animator) { 3067 if (mItemAnimator != null) { 3068 mItemAnimator.endAnimations(); 3069 mItemAnimator.setListener(null); 3070 } 3071 mItemAnimator = animator; 3072 if (mItemAnimator != null) { 3073 mItemAnimator.setListener(mItemAnimatorListener); 3074 } 3075 } 3076 3077 void onEnterLayoutOrScroll() { 3078 mLayoutOrScrollCounter ++; 3079 } 3080 3081 void onExitLayoutOrScroll() { 3082 mLayoutOrScrollCounter --; 3083 if (mLayoutOrScrollCounter < 1) { 3084 if (DEBUG && mLayoutOrScrollCounter < 0) { 3085 throw new IllegalStateException("layout or scroll counter cannot go below zero." 3086 + "Some calls are not matching"); 3087 } 3088 mLayoutOrScrollCounter = 0; 3089 dispatchContentChangedIfNecessary(); 3090 dispatchPendingImportantForAccessibilityChanges(); 3091 } 3092 } 3093 3094 boolean isAccessibilityEnabled() { 3095 return mAccessibilityManager != null && mAccessibilityManager.isEnabled(); 3096 } 3097 3098 private void dispatchContentChangedIfNecessary() { 3099 final int flags = mEatenAccessibilityChangeFlags; 3100 mEatenAccessibilityChangeFlags = 0; 3101 if (flags != 0 && isAccessibilityEnabled()) { 3102 final AccessibilityEvent event = AccessibilityEvent.obtain(); 3103 event.setEventType(AccessibilityEventCompat.TYPE_WINDOW_CONTENT_CHANGED); 3104 AccessibilityEventCompat.setContentChangeTypes(event, flags); 3105 sendAccessibilityEventUnchecked(event); 3106 } 3107 } 3108 3109 /** 3110 * Returns whether RecyclerView is currently computing a layout. 3111 * <p> 3112 * If this method returns true, it means that RecyclerView is in a lockdown state and any 3113 * attempt to update adapter contents will result in an exception because adapter contents 3114 * cannot be changed while RecyclerView is trying to compute the layout. 3115 * <p> 3116 * It is very unlikely that your code will be running during this state as it is 3117 * called by the framework when a layout traversal happens or RecyclerView starts to scroll 3118 * in response to system events (touch, accessibility etc). 3119 * <p> 3120 * This case may happen if you have some custom logic to change adapter contents in 3121 * response to a View callback (e.g. focus change callback) which might be triggered during a 3122 * layout calculation. In these cases, you should just postpone the change using a Handler or a 3123 * similar mechanism. 3124 * 3125 * @return <code>true</code> if RecyclerView is currently computing a layout, <code>false</code> 3126 * otherwise 3127 */ 3128 public boolean isComputingLayout() { 3129 return mLayoutOrScrollCounter > 0; 3130 } 3131 3132 /** 3133 * Returns true if an accessibility event should not be dispatched now. This happens when an 3134 * accessibility request arrives while RecyclerView does not have a stable state which is very 3135 * hard to handle for a LayoutManager. Instead, this method records necessary information about 3136 * the event and dispatches a window change event after the critical section is finished. 3137 * 3138 * @return True if the accessibility event should be postponed. 3139 */ 3140 boolean shouldDeferAccessibilityEvent(AccessibilityEvent event) { 3141 if (isComputingLayout()) { 3142 int type = 0; 3143 if (event != null) { 3144 type = AccessibilityEventCompat.getContentChangeTypes(event); 3145 } 3146 if (type == 0) { 3147 type = AccessibilityEventCompat.CONTENT_CHANGE_TYPE_UNDEFINED; 3148 } 3149 mEatenAccessibilityChangeFlags |= type; 3150 return true; 3151 } 3152 return false; 3153 } 3154 3155 @Override 3156 public void sendAccessibilityEventUnchecked(AccessibilityEvent event) { 3157 if (shouldDeferAccessibilityEvent(event)) { 3158 return; 3159 } 3160 super.sendAccessibilityEventUnchecked(event); 3161 } 3162 3163 /** 3164 * Gets the current ItemAnimator for this RecyclerView. A null return value 3165 * indicates that there is no animator and that item changes will happen without 3166 * any animations. By default, RecyclerView instantiates and 3167 * uses an instance of {@link DefaultItemAnimator}. 3168 * 3169 * @return ItemAnimator The current ItemAnimator. If null, no animations will occur 3170 * when changes occur to the items in this RecyclerView. 3171 */ 3172 public ItemAnimator getItemAnimator() { 3173 return mItemAnimator; 3174 } 3175 3176 /** 3177 * Post a runnable to the next frame to run pending item animations. Only the first such 3178 * request will be posted, governed by the mPostedAnimatorRunner flag. 3179 */ 3180 void postAnimationRunner() { 3181 if (!mPostedAnimatorRunner && mIsAttached) { 3182 ViewCompat.postOnAnimation(this, mItemAnimatorRunner); 3183 mPostedAnimatorRunner = true; 3184 } 3185 } 3186 3187 private boolean predictiveItemAnimationsEnabled() { 3188 return (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations()); 3189 } 3190 3191 /** 3192 * Consumes adapter updates and calculates which type of animations we want to run. 3193 * Called in onMeasure and dispatchLayout. 3194 * <p> 3195 * This method may process only the pre-layout state of updates or all of them. 3196 */ 3197 private void processAdapterUpdatesAndSetAnimationFlags() { 3198 if (mDataSetHasChangedAfterLayout) { 3199 // Processing these items have no value since data set changed unexpectedly. 3200 // Instead, we just reset it. 3201 mAdapterHelper.reset(); 3202 mLayout.onItemsChanged(this); 3203 } 3204 // simple animations are a subset of advanced animations (which will cause a 3205 // pre-layout step) 3206 // If layout supports predictive animations, pre-process to decide if we want to run them 3207 if (predictiveItemAnimationsEnabled()) { 3208 mAdapterHelper.preProcess(); 3209 } else { 3210 mAdapterHelper.consumeUpdatesInOnePass(); 3211 } 3212 boolean animationTypeSupported = mItemsAddedOrRemoved || mItemsChanged; 3213 mState.mRunSimpleAnimations = mFirstLayoutComplete 3214 && mItemAnimator != null 3215 && (mDataSetHasChangedAfterLayout 3216 || animationTypeSupported 3217 || mLayout.mRequestedSimpleAnimations) 3218 && (!mDataSetHasChangedAfterLayout 3219 || mAdapter.hasStableIds()); 3220 mState.mRunPredictiveAnimations = mState.mRunSimpleAnimations 3221 && animationTypeSupported 3222 && !mDataSetHasChangedAfterLayout 3223 && predictiveItemAnimationsEnabled(); 3224 } 3225 3226 /** 3227 * Wrapper around layoutChildren() that handles animating changes caused by layout. 3228 * Animations work on the assumption that there are five different kinds of items 3229 * in play: 3230 * PERSISTENT: items are visible before and after layout 3231 * REMOVED: items were visible before layout and were removed by the app 3232 * ADDED: items did not exist before layout and were added by the app 3233 * DISAPPEARING: items exist in the data set before/after, but changed from 3234 * visible to non-visible in the process of layout (they were moved off 3235 * screen as a side-effect of other changes) 3236 * APPEARING: items exist in the data set before/after, but changed from 3237 * non-visible to visible in the process of layout (they were moved on 3238 * screen as a side-effect of other changes) 3239 * The overall approach figures out what items exist before/after layout and 3240 * infers one of the five above states for each of the items. Then the animations 3241 * are set up accordingly: 3242 * PERSISTENT views are animated via 3243 * {@link ItemAnimator#animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)} 3244 * DISAPPEARING views are animated via 3245 * {@link ItemAnimator#animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)} 3246 * APPEARING views are animated via 3247 * {@link ItemAnimator#animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)} 3248 * and changed views are animated via 3249 * {@link ItemAnimator#animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)}. 3250 */ 3251 void dispatchLayout() { 3252 if (mAdapter == null) { 3253 Log.e(TAG, "No adapter attached; skipping layout"); 3254 // leave the state in START 3255 return; 3256 } 3257 if (mLayout == null) { 3258 Log.e(TAG, "No layout manager attached; skipping layout"); 3259 // leave the state in START 3260 return; 3261 } 3262 mState.mIsMeasuring = false; 3263 if (mState.mLayoutStep == State.STEP_START) { 3264 dispatchLayoutStep1(); 3265 mLayout.setExactMeasureSpecsFrom(this); 3266 dispatchLayoutStep2(); 3267 } else if (mAdapterHelper.hasUpdates() || mLayout.getWidth() != getWidth() || 3268 mLayout.getHeight() != getHeight()) { 3269 // First 2 steps are done in onMeasure but looks like we have to run again due to 3270 // changed size. 3271 mLayout.setExactMeasureSpecsFrom(this); 3272 dispatchLayoutStep2(); 3273 } else { 3274 // always make sure we sync them (to ensure mode is exact) 3275 mLayout.setExactMeasureSpecsFrom(this); 3276 } 3277 dispatchLayoutStep3(); 3278 } 3279 3280 private void saveFocusInfo() { 3281 View child = null; 3282 if (mPreserveFocusAfterLayout && hasFocus() && mAdapter != null) { 3283 child = getFocusedChild(); 3284 } 3285 3286 final ViewHolder focusedVh = child == null ? null : findContainingViewHolder(child); 3287 if (focusedVh == null) { 3288 resetFocusInfo(); 3289 } else { 3290 mState.mFocusedItemId = mAdapter.hasStableIds() ? focusedVh.getItemId() : NO_ID; 3291 // mFocusedItemPosition should hold the current adapter position of the previously 3292 // focused item. If the item is removed, we store the previous adapter position of the 3293 // removed item. 3294 mState.mFocusedItemPosition = mDataSetHasChangedAfterLayout ? NO_POSITION : 3295 (focusedVh.isRemoved() ? focusedVh.mOldPosition 3296 : focusedVh.getAdapterPosition()); 3297 mState.mFocusedSubChildId = getDeepestFocusedViewWithId(focusedVh.itemView); 3298 } 3299 } 3300 3301 private void resetFocusInfo() { 3302 mState.mFocusedItemId = NO_ID; 3303 mState.mFocusedItemPosition = NO_POSITION; 3304 mState.mFocusedSubChildId = View.NO_ID; 3305 } 3306 3307 /** 3308 * Finds the best view candidate to request focus on using mFocusedItemPosition index of the 3309 * previously focused item. It first traverses the adapter forward to find a focusable candidate 3310 * and if no such candidate is found, it reverses the focus search direction for the items 3311 * before the mFocusedItemPosition'th index; 3312 * @return The best candidate to request focus on, or null if no such candidate exists. Null 3313 * indicates all the existing adapter items are unfocusable. 3314 */ 3315 @Nullable 3316 private View findNextViewToFocus() { 3317 int startFocusSearchIndex = mState.mFocusedItemPosition != -1 ? mState.mFocusedItemPosition 3318 : 0; 3319 ViewHolder nextFocus; 3320 final int itemCount = mState.getItemCount(); 3321 for (int i = startFocusSearchIndex; i < itemCount; i++) { 3322 nextFocus = findViewHolderForAdapterPosition(i); 3323 if (nextFocus == null) { 3324 break; 3325 } 3326 if (nextFocus.itemView.hasFocusable()) { 3327 return nextFocus.itemView; 3328 } 3329 } 3330 final int limit = Math.min(itemCount, startFocusSearchIndex); 3331 for (int i = limit - 1; i >= 0; i--) { 3332 nextFocus = findViewHolderForAdapterPosition(i); 3333 if (nextFocus == null) { 3334 return null; 3335 } 3336 if (nextFocus.itemView.hasFocusable()) { 3337 return nextFocus.itemView; 3338 } 3339 } 3340 return null; 3341 } 3342 3343 private void recoverFocusFromState() { 3344 if (!mPreserveFocusAfterLayout || mAdapter == null || !hasFocus() 3345 || getDescendantFocusability() == FOCUS_BLOCK_DESCENDANTS 3346 || (getDescendantFocusability() == FOCUS_BEFORE_DESCENDANTS && isFocused())) { 3347 // No-op if either of these cases happens: 3348 // 1. RV has no focus, or 2. RV blocks focus to its children, or 3. RV takes focus 3349 // before its children and is focused (i.e. it already stole the focus away from its 3350 // descendants). 3351 return; 3352 } 3353 // only recover focus if RV itself has the focus or the focused view is hidden 3354 if (!isFocused()) { 3355 final View focusedChild = getFocusedChild(); 3356 if (IGNORE_DETACHED_FOCUSED_CHILD 3357 && (focusedChild.getParent() == null || !focusedChild.hasFocus())) { 3358 // Special handling of API 15-. A focused child can be invalid because mFocus is not 3359 // cleared when the child is detached (mParent = null), 3360 // This happens because clearFocus on API 15- does not invalidate mFocus of its 3361 // parent when this child is detached. 3362 // For API 16+, this is not an issue because requestFocus takes care of clearing the 3363 // prior detached focused child. For API 15- the problem happens in 2 cases because 3364 // clearChild does not call clearChildFocus on RV: 1. setFocusable(false) is called 3365 // for the current focused item which calls clearChild or 2. when the prior focused 3366 // child is removed, removeDetachedView called in layout step 3 which calls 3367 // clearChild. We should ignore this invalid focused child in all our calculations 3368 // for the next view to receive focus, and apply the focus recovery logic instead. 3369 if (mChildHelper.getChildCount() == 0) { 3370 // No children left. Request focus on the RV itself since one of its children 3371 // was holding focus previously. 3372 requestFocus(); 3373 return; 3374 } 3375 } else if (!mChildHelper.isHidden(focusedChild)) { 3376 // If the currently focused child is hidden, apply the focus recovery logic. 3377 // Otherwise return, i.e. the currently (unhidden) focused child is good enough :/. 3378 return; 3379 } 3380 } 3381 ViewHolder focusTarget = null; 3382 // RV first attempts to locate the previously focused item to request focus on using 3383 // mFocusedItemId. If such an item no longer exists, it then makes a best-effort attempt to 3384 // find the next best candidate to request focus on based on mFocusedItemPosition. 3385 if (mState.mFocusedItemId != NO_ID && mAdapter.hasStableIds()) { 3386 focusTarget = findViewHolderForItemId(mState.mFocusedItemId); 3387 } 3388 View viewToFocus = null; 3389 if (focusTarget == null || mChildHelper.isHidden(focusTarget.itemView) 3390 || !focusTarget.itemView.hasFocusable()) { 3391 if (mChildHelper.getChildCount() > 0) { 3392 // At this point, RV has focus and either of these conditions are true: 3393 // 1. There's no previously focused item either because RV received focused before 3394 // layout, or the previously focused item was removed, or RV doesn't have stable IDs 3395 // 2. Previous focus child is hidden, or 3. Previous focused child is no longer 3396 // focusable. In either of these cases, we make sure that RV still passes down the 3397 // focus to one of its focusable children using a best-effort algorithm. 3398 viewToFocus = findNextViewToFocus(); 3399 } 3400 } else { 3401 // looks like the focused item has been replaced with another view that represents the 3402 // same item in the adapter. Request focus on that. 3403 viewToFocus = focusTarget.itemView; 3404 } 3405 3406 if (viewToFocus != null) { 3407 if (mState.mFocusedSubChildId != NO_ID) { 3408 View child = viewToFocus.findViewById(mState.mFocusedSubChildId); 3409 if (child != null && child.isFocusable()) { 3410 viewToFocus = child; 3411 } 3412 } 3413 viewToFocus.requestFocus(); 3414 } 3415 } 3416 3417 private int getDeepestFocusedViewWithId(View view) { 3418 int lastKnownId = view.getId(); 3419 while (!view.isFocused() && view instanceof ViewGroup && view.hasFocus()) { 3420 view = ((ViewGroup) view).getFocusedChild(); 3421 final int id = view.getId(); 3422 if (id != View.NO_ID) { 3423 lastKnownId = view.getId(); 3424 } 3425 } 3426 return lastKnownId; 3427 } 3428 3429 /** 3430 * The first step of a layout where we; 3431 * - process adapter updates 3432 * - decide which animation should run 3433 * - save information about current views 3434 * - If necessary, run predictive layout and save its information 3435 */ 3436 private void dispatchLayoutStep1() { 3437 mState.assertLayoutStep(State.STEP_START); 3438 mState.mIsMeasuring = false; 3439 eatRequestLayout(); 3440 mViewInfoStore.clear(); 3441 onEnterLayoutOrScroll(); 3442 processAdapterUpdatesAndSetAnimationFlags(); 3443 saveFocusInfo(); 3444 mState.mTrackOldChangeHolders = mState.mRunSimpleAnimations && mItemsChanged; 3445 mItemsAddedOrRemoved = mItemsChanged = false; 3446 mState.mInPreLayout = mState.mRunPredictiveAnimations; 3447 mState.mItemCount = mAdapter.getItemCount(); 3448 findMinMaxChildLayoutPositions(mMinMaxLayoutPositions); 3449 3450 if (mState.mRunSimpleAnimations) { 3451 // Step 0: Find out where all non-removed items are, pre-layout 3452 int count = mChildHelper.getChildCount(); 3453 for (int i = 0; i < count; ++i) { 3454 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 3455 if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) { 3456 continue; 3457 } 3458 final ItemHolderInfo animationInfo = mItemAnimator 3459 .recordPreLayoutInformation(mState, holder, 3460 ItemAnimator.buildAdapterChangeFlagsForAnimations(holder), 3461 holder.getUnmodifiedPayloads()); 3462 mViewInfoStore.addToPreLayout(holder, animationInfo); 3463 if (mState.mTrackOldChangeHolders && holder.isUpdated() && !holder.isRemoved() 3464 && !holder.shouldIgnore() && !holder.isInvalid()) { 3465 long key = getChangedHolderKey(holder); 3466 // This is NOT the only place where a ViewHolder is added to old change holders 3467 // list. There is another case where: 3468 // * A VH is currently hidden but not deleted 3469 // * The hidden item is changed in the adapter 3470 // * Layout manager decides to layout the item in the pre-Layout pass (step1) 3471 // When this case is detected, RV will un-hide that view and add to the old 3472 // change holders list. 3473 mViewInfoStore.addToOldChangeHolders(key, holder); 3474 } 3475 } 3476 } 3477 if (mState.mRunPredictiveAnimations) { 3478 // Step 1: run prelayout: This will use the old positions of items. The layout manager 3479 // is expected to layout everything, even removed items (though not to add removed 3480 // items back to the container). This gives the pre-layout position of APPEARING views 3481 // which come into existence as part of the real layout. 3482 3483 // Save old positions so that LayoutManager can run its mapping logic. 3484 saveOldPositions(); 3485 final boolean didStructureChange = mState.mStructureChanged; 3486 mState.mStructureChanged = false; 3487 // temporarily disable flag because we are asking for previous layout 3488 mLayout.onLayoutChildren(mRecycler, mState); 3489 mState.mStructureChanged = didStructureChange; 3490 3491 for (int i = 0; i < mChildHelper.getChildCount(); ++i) { 3492 final View child = mChildHelper.getChildAt(i); 3493 final ViewHolder viewHolder = getChildViewHolderInt(child); 3494 if (viewHolder.shouldIgnore()) { 3495 continue; 3496 } 3497 if (!mViewInfoStore.isInPreLayout(viewHolder)) { 3498 int flags = ItemAnimator.buildAdapterChangeFlagsForAnimations(viewHolder); 3499 boolean wasHidden = viewHolder 3500 .hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST); 3501 if (!wasHidden) { 3502 flags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT; 3503 } 3504 final ItemHolderInfo animationInfo = mItemAnimator.recordPreLayoutInformation( 3505 mState, viewHolder, flags, viewHolder.getUnmodifiedPayloads()); 3506 if (wasHidden) { 3507 recordAnimationInfoIfBouncedHiddenView(viewHolder, animationInfo); 3508 } else { 3509 mViewInfoStore.addToAppearedInPreLayoutHolders(viewHolder, animationInfo); 3510 } 3511 } 3512 } 3513 // we don't process disappearing list because they may re-appear in post layout pass. 3514 clearOldPositions(); 3515 } else { 3516 clearOldPositions(); 3517 } 3518 onExitLayoutOrScroll(); 3519 resumeRequestLayout(false); 3520 mState.mLayoutStep = State.STEP_LAYOUT; 3521 } 3522 3523 /** 3524 * The second layout step where we do the actual layout of the views for the final state. 3525 * This step might be run multiple times if necessary (e.g. measure). 3526 */ 3527 private void dispatchLayoutStep2() { 3528 eatRequestLayout(); 3529 onEnterLayoutOrScroll(); 3530 mState.assertLayoutStep(State.STEP_LAYOUT | State.STEP_ANIMATIONS); 3531 mAdapterHelper.consumeUpdatesInOnePass(); 3532 mState.mItemCount = mAdapter.getItemCount(); 3533 mState.mDeletedInvisibleItemCountSincePreviousLayout = 0; 3534 3535 // Step 2: Run layout 3536 mState.mInPreLayout = false; 3537 mLayout.onLayoutChildren(mRecycler, mState); 3538 3539 mState.mStructureChanged = false; 3540 mPendingSavedState = null; 3541 3542 // onLayoutChildren may have caused client code to disable item animations; re-check 3543 mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null; 3544 mState.mLayoutStep = State.STEP_ANIMATIONS; 3545 onExitLayoutOrScroll(); 3546 resumeRequestLayout(false); 3547 } 3548 3549 /** 3550 * The final step of the layout where we save the information about views for animations, 3551 * trigger animations and do any necessary cleanup. 3552 */ 3553 private void dispatchLayoutStep3() { 3554 mState.assertLayoutStep(State.STEP_ANIMATIONS); 3555 eatRequestLayout(); 3556 onEnterLayoutOrScroll(); 3557 mState.mLayoutStep = State.STEP_START; 3558 if (mState.mRunSimpleAnimations) { 3559 // Step 3: Find out where things are now, and process change animations. 3560 // traverse list in reverse because we may call animateChange in the loop which may 3561 // remove the target view holder. 3562 for (int i = mChildHelper.getChildCount() - 1; i >= 0; i--) { 3563 ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 3564 if (holder.shouldIgnore()) { 3565 continue; 3566 } 3567 long key = getChangedHolderKey(holder); 3568 final ItemHolderInfo animationInfo = mItemAnimator 3569 .recordPostLayoutInformation(mState, holder); 3570 ViewHolder oldChangeViewHolder = mViewInfoStore.getFromOldChangeHolders(key); 3571 if (oldChangeViewHolder != null && !oldChangeViewHolder.shouldIgnore()) { 3572 // run a change animation 3573 3574 // If an Item is CHANGED but the updated version is disappearing, it creates 3575 // a conflicting case. 3576 // Since a view that is marked as disappearing is likely to be going out of 3577 // bounds, we run a change animation. Both views will be cleaned automatically 3578 // once their animations finish. 3579 // On the other hand, if it is the same view holder instance, we run a 3580 // disappearing animation instead because we are not going to rebind the updated 3581 // VH unless it is enforced by the layout manager. 3582 final boolean oldDisappearing = mViewInfoStore.isDisappearing( 3583 oldChangeViewHolder); 3584 final boolean newDisappearing = mViewInfoStore.isDisappearing(holder); 3585 if (oldDisappearing && oldChangeViewHolder == holder) { 3586 // run disappear animation instead of change 3587 mViewInfoStore.addToPostLayout(holder, animationInfo); 3588 } else { 3589 final ItemHolderInfo preInfo = mViewInfoStore.popFromPreLayout( 3590 oldChangeViewHolder); 3591 // we add and remove so that any post info is merged. 3592 mViewInfoStore.addToPostLayout(holder, animationInfo); 3593 ItemHolderInfo postInfo = mViewInfoStore.popFromPostLayout(holder); 3594 if (preInfo == null) { 3595 handleMissingPreInfoForChangeError(key, holder, oldChangeViewHolder); 3596 } else { 3597 animateChange(oldChangeViewHolder, holder, preInfo, postInfo, 3598 oldDisappearing, newDisappearing); 3599 } 3600 } 3601 } else { 3602 mViewInfoStore.addToPostLayout(holder, animationInfo); 3603 } 3604 } 3605 3606 // Step 4: Process view info lists and trigger animations 3607 mViewInfoStore.process(mViewInfoProcessCallback); 3608 } 3609 3610 mLayout.removeAndRecycleScrapInt(mRecycler); 3611 mState.mPreviousLayoutItemCount = mState.mItemCount; 3612 mDataSetHasChangedAfterLayout = false; 3613 mState.mRunSimpleAnimations = false; 3614 3615 mState.mRunPredictiveAnimations = false; 3616 mLayout.mRequestedSimpleAnimations = false; 3617 if (mRecycler.mChangedScrap != null) { 3618 mRecycler.mChangedScrap.clear(); 3619 } 3620 if (mLayout.mPrefetchMaxObservedInInitialPrefetch) { 3621 // Initial prefetch has expanded cache, so reset until next prefetch. 3622 // This prevents initial prefetches from expanding the cache permanently. 3623 mLayout.mPrefetchMaxCountObserved = 0; 3624 mLayout.mPrefetchMaxObservedInInitialPrefetch = false; 3625 mRecycler.updateViewCacheSize(); 3626 } 3627 3628 mLayout.onLayoutCompleted(mState); 3629 onExitLayoutOrScroll(); 3630 resumeRequestLayout(false); 3631 mViewInfoStore.clear(); 3632 if (didChildRangeChange(mMinMaxLayoutPositions[0], mMinMaxLayoutPositions[1])) { 3633 dispatchOnScrolled(0, 0); 3634 } 3635 recoverFocusFromState(); 3636 resetFocusInfo(); 3637 } 3638 3639 /** 3640 * This handles the case where there is an unexpected VH missing in the pre-layout map. 3641 * <p> 3642 * We might be able to detect the error in the application which will help the developer to 3643 * resolve the issue. 3644 * <p> 3645 * If it is not an expected error, we at least print an error to notify the developer and ignore 3646 * the animation. 3647 * 3648 * https://code.google.com/p/android/issues/detail?id=193958 3649 * 3650 * @param key The change key 3651 * @param holder Current ViewHolder 3652 * @param oldChangeViewHolder Changed ViewHolder 3653 */ 3654 private void handleMissingPreInfoForChangeError(long key, 3655 ViewHolder holder, ViewHolder oldChangeViewHolder) { 3656 // check if two VH have the same key, if so, print that as an error 3657 final int childCount = mChildHelper.getChildCount(); 3658 for (int i = 0; i < childCount; i++) { 3659 View view = mChildHelper.getChildAt(i); 3660 ViewHolder other = getChildViewHolderInt(view); 3661 if (other == holder) { 3662 continue; 3663 } 3664 final long otherKey = getChangedHolderKey(other); 3665 if (otherKey == key) { 3666 if (mAdapter != null && mAdapter.hasStableIds()) { 3667 throw new IllegalStateException("Two different ViewHolders have the same stable" 3668 + " ID. Stable IDs in your adapter MUST BE unique and SHOULD NOT" 3669 + " change.\n ViewHolder 1:" + other + " \n View Holder 2:" + holder); 3670 } else { 3671 throw new IllegalStateException("Two different ViewHolders have the same change" 3672 + " ID. This might happen due to inconsistent Adapter update events or" 3673 + " if the LayoutManager lays out the same View multiple times." 3674 + "\n ViewHolder 1:" + other + " \n View Holder 2:" + holder); 3675 } 3676 } 3677 } 3678 // Very unlikely to happen but if it does, notify the developer. 3679 Log.e(TAG, "Problem while matching changed view holders with the new" 3680 + "ones. The pre-layout information for the change holder " + oldChangeViewHolder 3681 + " cannot be found but it is necessary for " + holder); 3682 } 3683 3684 /** 3685 * Records the animation information for a view holder that was bounced from hidden list. It 3686 * also clears the bounce back flag. 3687 */ 3688 void recordAnimationInfoIfBouncedHiddenView(ViewHolder viewHolder, 3689 ItemHolderInfo animationInfo) { 3690 // looks like this view bounced back from hidden list! 3691 viewHolder.setFlags(0, ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST); 3692 if (mState.mTrackOldChangeHolders && viewHolder.isUpdated() 3693 && !viewHolder.isRemoved() && !viewHolder.shouldIgnore()) { 3694 long key = getChangedHolderKey(viewHolder); 3695 mViewInfoStore.addToOldChangeHolders(key, viewHolder); 3696 } 3697 mViewInfoStore.addToPreLayout(viewHolder, animationInfo); 3698 } 3699 3700 private void findMinMaxChildLayoutPositions(int[] into) { 3701 final int count = mChildHelper.getChildCount(); 3702 if (count == 0) { 3703 into[0] = NO_POSITION; 3704 into[1] = NO_POSITION; 3705 return; 3706 } 3707 int minPositionPreLayout = Integer.MAX_VALUE; 3708 int maxPositionPreLayout = Integer.MIN_VALUE; 3709 for (int i = 0; i < count; ++i) { 3710 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 3711 if (holder.shouldIgnore()) { 3712 continue; 3713 } 3714 final int pos = holder.getLayoutPosition(); 3715 if (pos < minPositionPreLayout) { 3716 minPositionPreLayout = pos; 3717 } 3718 if (pos > maxPositionPreLayout) { 3719 maxPositionPreLayout = pos; 3720 } 3721 } 3722 into[0] = minPositionPreLayout; 3723 into[1] = maxPositionPreLayout; 3724 } 3725 3726 private boolean didChildRangeChange(int minPositionPreLayout, int maxPositionPreLayout) { 3727 findMinMaxChildLayoutPositions(mMinMaxLayoutPositions); 3728 return mMinMaxLayoutPositions[0] != minPositionPreLayout || 3729 mMinMaxLayoutPositions[1] != maxPositionPreLayout; 3730 } 3731 3732 @Override 3733 protected void removeDetachedView(View child, boolean animate) { 3734 ViewHolder vh = getChildViewHolderInt(child); 3735 if (vh != null) { 3736 if (vh.isTmpDetached()) { 3737 vh.clearTmpDetachFlag(); 3738 } else if (!vh.shouldIgnore()) { 3739 throw new IllegalArgumentException("Called removeDetachedView with a view which" 3740 + " is not flagged as tmp detached." + vh); 3741 } 3742 } 3743 dispatchChildDetached(child); 3744 super.removeDetachedView(child, animate); 3745 } 3746 3747 /** 3748 * Returns a unique key to be used while handling change animations. 3749 * It might be child's position or stable id depending on the adapter type. 3750 */ 3751 long getChangedHolderKey(ViewHolder holder) { 3752 return mAdapter.hasStableIds() ? holder.getItemId() : holder.mPosition; 3753 } 3754 3755 void animateAppearance(@NonNull ViewHolder itemHolder, 3756 @Nullable ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo) { 3757 itemHolder.setIsRecyclable(false); 3758 if (mItemAnimator.animateAppearance(itemHolder, preLayoutInfo, postLayoutInfo)) { 3759 postAnimationRunner(); 3760 } 3761 } 3762 3763 void animateDisappearance(@NonNull ViewHolder holder, 3764 @NonNull ItemHolderInfo preLayoutInfo, @Nullable ItemHolderInfo postLayoutInfo) { 3765 addAnimatingView(holder); 3766 holder.setIsRecyclable(false); 3767 if (mItemAnimator.animateDisappearance(holder, preLayoutInfo, postLayoutInfo)) { 3768 postAnimationRunner(); 3769 } 3770 } 3771 3772 private void animateChange(@NonNull ViewHolder oldHolder, @NonNull ViewHolder newHolder, 3773 @NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo, 3774 boolean oldHolderDisappearing, boolean newHolderDisappearing) { 3775 oldHolder.setIsRecyclable(false); 3776 if (oldHolderDisappearing) { 3777 addAnimatingView(oldHolder); 3778 } 3779 if (oldHolder != newHolder) { 3780 if (newHolderDisappearing) { 3781 addAnimatingView(newHolder); 3782 } 3783 oldHolder.mShadowedHolder = newHolder; 3784 // old holder should disappear after animation ends 3785 addAnimatingView(oldHolder); 3786 mRecycler.unscrapView(oldHolder); 3787 newHolder.setIsRecyclable(false); 3788 newHolder.mShadowingHolder = oldHolder; 3789 } 3790 if (mItemAnimator.animateChange(oldHolder, newHolder, preInfo, postInfo)) { 3791 postAnimationRunner(); 3792 } 3793 } 3794 3795 @Override 3796 protected void onLayout(boolean changed, int l, int t, int r, int b) { 3797 TraceCompat.beginSection(TRACE_ON_LAYOUT_TAG); 3798 dispatchLayout(); 3799 TraceCompat.endSection(); 3800 mFirstLayoutComplete = true; 3801 } 3802 3803 @Override 3804 public void requestLayout() { 3805 if (mEatRequestLayout == 0 && !mLayoutFrozen) { 3806 super.requestLayout(); 3807 } else { 3808 mLayoutRequestEaten = true; 3809 } 3810 } 3811 3812 void markItemDecorInsetsDirty() { 3813 final int childCount = mChildHelper.getUnfilteredChildCount(); 3814 for (int i = 0; i < childCount; i++) { 3815 final View child = mChildHelper.getUnfilteredChildAt(i); 3816 ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true; 3817 } 3818 mRecycler.markItemDecorInsetsDirty(); 3819 } 3820 3821 @Override 3822 public void draw(Canvas c) { 3823 super.draw(c); 3824 3825 final int count = mItemDecorations.size(); 3826 for (int i = 0; i < count; i++) { 3827 mItemDecorations.get(i).onDrawOver(c, this, mState); 3828 } 3829 // TODO If padding is not 0 and clipChildrenToPadding is false, to draw glows properly, we 3830 // need find children closest to edges. Not sure if it is worth the effort. 3831 boolean needsInvalidate = false; 3832 if (mLeftGlow != null && !mLeftGlow.isFinished()) { 3833 final int restore = c.save(); 3834 final int padding = mClipToPadding ? getPaddingBottom() : 0; 3835 c.rotate(270); 3836 c.translate(-getHeight() + padding, 0); 3837 needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c); 3838 c.restoreToCount(restore); 3839 } 3840 if (mTopGlow != null && !mTopGlow.isFinished()) { 3841 final int restore = c.save(); 3842 if (mClipToPadding) { 3843 c.translate(getPaddingLeft(), getPaddingTop()); 3844 } 3845 needsInvalidate |= mTopGlow != null && mTopGlow.draw(c); 3846 c.restoreToCount(restore); 3847 } 3848 if (mRightGlow != null && !mRightGlow.isFinished()) { 3849 final int restore = c.save(); 3850 final int width = getWidth(); 3851 final int padding = mClipToPadding ? getPaddingTop() : 0; 3852 c.rotate(90); 3853 c.translate(-padding, -width); 3854 needsInvalidate |= mRightGlow != null && mRightGlow.draw(c); 3855 c.restoreToCount(restore); 3856 } 3857 if (mBottomGlow != null && !mBottomGlow.isFinished()) { 3858 final int restore = c.save(); 3859 c.rotate(180); 3860 if (mClipToPadding) { 3861 c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom()); 3862 } else { 3863 c.translate(-getWidth(), -getHeight()); 3864 } 3865 needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c); 3866 c.restoreToCount(restore); 3867 } 3868 3869 // If some views are animating, ItemDecorators are likely to move/change with them. 3870 // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's 3871 // display lists are not invalidated. 3872 if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 && 3873 mItemAnimator.isRunning()) { 3874 needsInvalidate = true; 3875 } 3876 3877 if (needsInvalidate) { 3878 ViewCompat.postInvalidateOnAnimation(this); 3879 } 3880 } 3881 3882 @Override 3883 public void onDraw(Canvas c) { 3884 super.onDraw(c); 3885 3886 final int count = mItemDecorations.size(); 3887 for (int i = 0; i < count; i++) { 3888 mItemDecorations.get(i).onDraw(c, this, mState); 3889 } 3890 } 3891 3892 @Override 3893 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 3894 return p instanceof LayoutParams && mLayout.checkLayoutParams((LayoutParams) p); 3895 } 3896 3897 @Override 3898 protected ViewGroup.LayoutParams generateDefaultLayoutParams() { 3899 if (mLayout == null) { 3900 throw new IllegalStateException("RecyclerView has no LayoutManager"); 3901 } 3902 return mLayout.generateDefaultLayoutParams(); 3903 } 3904 3905 @Override 3906 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { 3907 if (mLayout == null) { 3908 throw new IllegalStateException("RecyclerView has no LayoutManager"); 3909 } 3910 return mLayout.generateLayoutParams(getContext(), attrs); 3911 } 3912 3913 @Override 3914 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 3915 if (mLayout == null) { 3916 throw new IllegalStateException("RecyclerView has no LayoutManager"); 3917 } 3918 return mLayout.generateLayoutParams(p); 3919 } 3920 3921 /** 3922 * Returns true if RecyclerView is currently running some animations. 3923 * <p> 3924 * If you want to be notified when animations are finished, use 3925 * {@link ItemAnimator#isRunning(ItemAnimator.ItemAnimatorFinishedListener)}. 3926 * 3927 * @return True if there are some item animations currently running or waiting to be started. 3928 */ 3929 public boolean isAnimating() { 3930 return mItemAnimator != null && mItemAnimator.isRunning(); 3931 } 3932 3933 void saveOldPositions() { 3934 final int childCount = mChildHelper.getUnfilteredChildCount(); 3935 for (int i = 0; i < childCount; i++) { 3936 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 3937 if (DEBUG && holder.mPosition == -1 && !holder.isRemoved()) { 3938 throw new IllegalStateException("view holder cannot have position -1 unless it" 3939 + " is removed"); 3940 } 3941 if (!holder.shouldIgnore()) { 3942 holder.saveOldPosition(); 3943 } 3944 } 3945 } 3946 3947 void clearOldPositions() { 3948 final int childCount = mChildHelper.getUnfilteredChildCount(); 3949 for (int i = 0; i < childCount; i++) { 3950 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 3951 if (!holder.shouldIgnore()) { 3952 holder.clearOldPosition(); 3953 } 3954 } 3955 mRecycler.clearOldPositions(); 3956 } 3957 3958 void offsetPositionRecordsForMove(int from, int to) { 3959 final int childCount = mChildHelper.getUnfilteredChildCount(); 3960 final int start, end, inBetweenOffset; 3961 if (from < to) { 3962 start = from; 3963 end = to; 3964 inBetweenOffset = -1; 3965 } else { 3966 start = to; 3967 end = from; 3968 inBetweenOffset = 1; 3969 } 3970 3971 for (int i = 0; i < childCount; i++) { 3972 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 3973 if (holder == null || holder.mPosition < start || holder.mPosition > end) { 3974 continue; 3975 } 3976 if (DEBUG) { 3977 Log.d(TAG, "offsetPositionRecordsForMove attached child " + i + " holder " + 3978 holder); 3979 } 3980 if (holder.mPosition == from) { 3981 holder.offsetPosition(to - from, false); 3982 } else { 3983 holder.offsetPosition(inBetweenOffset, false); 3984 } 3985 3986 mState.mStructureChanged = true; 3987 } 3988 mRecycler.offsetPositionRecordsForMove(from, to); 3989 requestLayout(); 3990 } 3991 3992 void offsetPositionRecordsForInsert(int positionStart, int itemCount) { 3993 final int childCount = mChildHelper.getUnfilteredChildCount(); 3994 for (int i = 0; i < childCount; i++) { 3995 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 3996 if (holder != null && !holder.shouldIgnore() && holder.mPosition >= positionStart) { 3997 if (DEBUG) { 3998 Log.d(TAG, "offsetPositionRecordsForInsert attached child " + i + " holder " + 3999 holder + " now at position " + (holder.mPosition + itemCount)); 4000 } 4001 holder.offsetPosition(itemCount, false); 4002 mState.mStructureChanged = true; 4003 } 4004 } 4005 mRecycler.offsetPositionRecordsForInsert(positionStart, itemCount); 4006 requestLayout(); 4007 } 4008 4009 void offsetPositionRecordsForRemove(int positionStart, int itemCount, 4010 boolean applyToPreLayout) { 4011 final int positionEnd = positionStart + itemCount; 4012 final int childCount = mChildHelper.getUnfilteredChildCount(); 4013 for (int i = 0; i < childCount; i++) { 4014 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 4015 if (holder != null && !holder.shouldIgnore()) { 4016 if (holder.mPosition >= positionEnd) { 4017 if (DEBUG) { 4018 Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i + 4019 " holder " + holder + " now at position " + 4020 (holder.mPosition - itemCount)); 4021 } 4022 holder.offsetPosition(-itemCount, applyToPreLayout); 4023 mState.mStructureChanged = true; 4024 } else if (holder.mPosition >= positionStart) { 4025 if (DEBUG) { 4026 Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i + 4027 " holder " + holder + " now REMOVED"); 4028 } 4029 holder.flagRemovedAndOffsetPosition(positionStart - 1, -itemCount, 4030 applyToPreLayout); 4031 mState.mStructureChanged = true; 4032 } 4033 } 4034 } 4035 mRecycler.offsetPositionRecordsForRemove(positionStart, itemCount, applyToPreLayout); 4036 requestLayout(); 4037 } 4038 4039 /** 4040 * Rebind existing views for the given range, or create as needed. 4041 * 4042 * @param positionStart Adapter position to start at 4043 * @param itemCount Number of views that must explicitly be rebound 4044 */ 4045 void viewRangeUpdate(int positionStart, int itemCount, Object payload) { 4046 final int childCount = mChildHelper.getUnfilteredChildCount(); 4047 final int positionEnd = positionStart + itemCount; 4048 4049 for (int i = 0; i < childCount; i++) { 4050 final View child = mChildHelper.getUnfilteredChildAt(i); 4051 final ViewHolder holder = getChildViewHolderInt(child); 4052 if (holder == null || holder.shouldIgnore()) { 4053 continue; 4054 } 4055 if (holder.mPosition >= positionStart && holder.mPosition < positionEnd) { 4056 // We re-bind these view holders after pre-processing is complete so that 4057 // ViewHolders have their final positions assigned. 4058 holder.addFlags(ViewHolder.FLAG_UPDATE); 4059 holder.addChangePayload(payload); 4060 // lp cannot be null since we get ViewHolder from it. 4061 ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true; 4062 } 4063 } 4064 mRecycler.viewRangeUpdate(positionStart, itemCount); 4065 } 4066 4067 boolean canReuseUpdatedViewHolder(ViewHolder viewHolder) { 4068 return mItemAnimator == null || mItemAnimator.canReuseUpdatedViewHolder(viewHolder, 4069 viewHolder.getUnmodifiedPayloads()); 4070 } 4071 4072 4073 /** 4074 * Call this method to signal that *all* adapter content has changed (generally, because of 4075 * swapAdapter, or notifyDataSetChanged), and that once layout occurs, all attached items should 4076 * be discarded or animated. Note that this work is deferred because RecyclerView requires a 4077 * layout to resolve non-incremental changes to the data set. 4078 * 4079 * Attached items are labeled as position unknown, and may no longer be cached. 4080 * 4081 * It is still possible for items to be prefetched while mDataSetHasChangedAfterLayout == true, 4082 * so calling this method *must* be associated with marking the cache invalid, so that the 4083 * only valid items that remain in the cache, once layout occurs, are prefetched items. 4084 */ 4085 void setDataSetChangedAfterLayout() { 4086 if (mDataSetHasChangedAfterLayout) { 4087 return; 4088 } 4089 mDataSetHasChangedAfterLayout = true; 4090 final int childCount = mChildHelper.getUnfilteredChildCount(); 4091 for (int i = 0; i < childCount; i++) { 4092 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 4093 if (holder != null && !holder.shouldIgnore()) { 4094 holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN); 4095 } 4096 } 4097 mRecycler.setAdapterPositionsAsUnknown(); 4098 4099 // immediately mark all views as invalid, so prefetched views can be 4100 // differentiated from views bound to previous data set - both in children, and cache 4101 markKnownViewsInvalid(); 4102 } 4103 4104 /** 4105 * Mark all known views as invalid. Used in response to a, "the whole world might have changed" 4106 * data change event. 4107 */ 4108 void markKnownViewsInvalid() { 4109 final int childCount = mChildHelper.getUnfilteredChildCount(); 4110 for (int i = 0; i < childCount; i++) { 4111 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 4112 if (holder != null && !holder.shouldIgnore()) { 4113 holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID); 4114 } 4115 } 4116 markItemDecorInsetsDirty(); 4117 mRecycler.markKnownViewsInvalid(); 4118 } 4119 4120 /** 4121 * Invalidates all ItemDecorations. If RecyclerView has item decorations, calling this method 4122 * will trigger a {@link #requestLayout()} call. 4123 */ 4124 public void invalidateItemDecorations() { 4125 if (mItemDecorations.size() == 0) { 4126 return; 4127 } 4128 if (mLayout != null) { 4129 mLayout.assertNotInLayoutOrScroll("Cannot invalidate item decorations during a scroll" 4130 + " or layout"); 4131 } 4132 markItemDecorInsetsDirty(); 4133 requestLayout(); 4134 } 4135 4136 /** 4137 * Returns true if the RecyclerView should attempt to preserve currently focused Adapter Item's 4138 * focus even if the View representing the Item is replaced during a layout calculation. 4139 * <p> 4140 * By default, this value is {@code true}. 4141 * 4142 * @return True if the RecyclerView will try to preserve focused Item after a layout if it loses 4143 * focus. 4144 * 4145 * @see #setPreserveFocusAfterLayout(boolean) 4146 */ 4147 public boolean getPreserveFocusAfterLayout() { 4148 return mPreserveFocusAfterLayout; 4149 } 4150 4151 /** 4152 * Set whether the RecyclerView should try to keep the same Item focused after a layout 4153 * calculation or not. 4154 * <p> 4155 * Usually, LayoutManagers keep focused views visible before and after layout but sometimes, 4156 * views may lose focus during a layout calculation as their state changes or they are replaced 4157 * with another view due to type change or animation. In these cases, RecyclerView can request 4158 * focus on the new view automatically. 4159 * 4160 * @param preserveFocusAfterLayout Whether RecyclerView should preserve focused Item during a 4161 * layout calculations. Defaults to true. 4162 * 4163 * @see #getPreserveFocusAfterLayout() 4164 */ 4165 public void setPreserveFocusAfterLayout(boolean preserveFocusAfterLayout) { 4166 mPreserveFocusAfterLayout = preserveFocusAfterLayout; 4167 } 4168 4169 /** 4170 * Retrieve the {@link ViewHolder} for the given child view. 4171 * 4172 * @param child Child of this RecyclerView to query for its ViewHolder 4173 * @return The child view's ViewHolder 4174 */ 4175 public ViewHolder getChildViewHolder(View child) { 4176 final ViewParent parent = child.getParent(); 4177 if (parent != null && parent != this) { 4178 throw new IllegalArgumentException("View " + child + " is not a direct child of " + 4179 this); 4180 } 4181 return getChildViewHolderInt(child); 4182 } 4183 4184 /** 4185 * Traverses the ancestors of the given view and returns the item view that contains it and 4186 * also a direct child of the RecyclerView. This returned view can be used to get the 4187 * ViewHolder by calling {@link #getChildViewHolder(View)}. 4188 * 4189 * @param view The view that is a descendant of the RecyclerView. 4190 * 4191 * @return The direct child of the RecyclerView which contains the given view or null if the 4192 * provided view is not a descendant of this RecyclerView. 4193 * 4194 * @see #getChildViewHolder(View) 4195 * @see #findContainingViewHolder(View) 4196 */ 4197 @Nullable 4198 public View findContainingItemView(View view) { 4199 ViewParent parent = view.getParent(); 4200 while (parent != null && parent != this && parent instanceof View) { 4201 view = (View) parent; 4202 parent = view.getParent(); 4203 } 4204 return parent == this ? view : null; 4205 } 4206 4207 /** 4208 * Returns the ViewHolder that contains the given view. 4209 * 4210 * @param view The view that is a descendant of the RecyclerView. 4211 * 4212 * @return The ViewHolder that contains the given view or null if the provided view is not a 4213 * descendant of this RecyclerView. 4214 */ 4215 @Nullable 4216 public ViewHolder findContainingViewHolder(View view) { 4217 View itemView = findContainingItemView(view); 4218 return itemView == null ? null : getChildViewHolder(itemView); 4219 } 4220 4221 4222 static ViewHolder getChildViewHolderInt(View child) { 4223 if (child == null) { 4224 return null; 4225 } 4226 return ((LayoutParams) child.getLayoutParams()).mViewHolder; 4227 } 4228 4229 /** 4230 * @deprecated use {@link #getChildAdapterPosition(View)} or 4231 * {@link #getChildLayoutPosition(View)}. 4232 */ 4233 @Deprecated 4234 public int getChildPosition(View child) { 4235 return getChildAdapterPosition(child); 4236 } 4237 4238 /** 4239 * Return the adapter position that the given child view corresponds to. 4240 * 4241 * @param child Child View to query 4242 * @return Adapter position corresponding to the given view or {@link #NO_POSITION} 4243 */ 4244 public int getChildAdapterPosition(View child) { 4245 final ViewHolder holder = getChildViewHolderInt(child); 4246 return holder != null ? holder.getAdapterPosition() : NO_POSITION; 4247 } 4248 4249 /** 4250 * Return the adapter position of the given child view as of the latest completed layout pass. 4251 * <p> 4252 * This position may not be equal to Item's adapter position if there are pending changes 4253 * in the adapter which have not been reflected to the layout yet. 4254 * 4255 * @param child Child View to query 4256 * @return Adapter position of the given View as of last layout pass or {@link #NO_POSITION} if 4257 * the View is representing a removed item. 4258 */ 4259 public int getChildLayoutPosition(View child) { 4260 final ViewHolder holder = getChildViewHolderInt(child); 4261 return holder != null ? holder.getLayoutPosition() : NO_POSITION; 4262 } 4263 4264 /** 4265 * Return the stable item id that the given child view corresponds to. 4266 * 4267 * @param child Child View to query 4268 * @return Item id corresponding to the given view or {@link #NO_ID} 4269 */ 4270 public long getChildItemId(View child) { 4271 if (mAdapter == null || !mAdapter.hasStableIds()) { 4272 return NO_ID; 4273 } 4274 final ViewHolder holder = getChildViewHolderInt(child); 4275 return holder != null ? holder.getItemId() : NO_ID; 4276 } 4277 4278 /** 4279 * @deprecated use {@link #findViewHolderForLayoutPosition(int)} or 4280 * {@link #findViewHolderForAdapterPosition(int)} 4281 */ 4282 @Deprecated 4283 public ViewHolder findViewHolderForPosition(int position) { 4284 return findViewHolderForPosition(position, false); 4285 } 4286 4287 /** 4288 * Return the ViewHolder for the item in the given position of the data set as of the latest 4289 * layout pass. 4290 * <p> 4291 * This method checks only the children of RecyclerView. If the item at the given 4292 * <code>position</code> is not laid out, it <em>will not</em> create a new one. 4293 * <p> 4294 * Note that when Adapter contents change, ViewHolder positions are not updated until the 4295 * next layout calculation. If there are pending adapter updates, the return value of this 4296 * method may not match your adapter contents. You can use 4297 * #{@link ViewHolder#getAdapterPosition()} to get the current adapter position of a ViewHolder. 4298 * <p> 4299 * When the ItemAnimator is running a change animation, there might be 2 ViewHolders 4300 * with the same layout position representing the same Item. In this case, the updated 4301 * ViewHolder will be returned. 4302 * 4303 * @param position The position of the item in the data set of the adapter 4304 * @return The ViewHolder at <code>position</code> or null if there is no such item 4305 */ 4306 public ViewHolder findViewHolderForLayoutPosition(int position) { 4307 return findViewHolderForPosition(position, false); 4308 } 4309 4310 /** 4311 * Return the ViewHolder for the item in the given position of the data set. Unlike 4312 * {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending 4313 * adapter changes that may not be reflected to the layout yet. On the other hand, if 4314 * {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been 4315 * calculated yet, this method will return <code>null</code> since the new positions of views 4316 * are unknown until the layout is calculated. 4317 * <p> 4318 * This method checks only the children of RecyclerView. If the item at the given 4319 * <code>position</code> is not laid out, it <em>will not</em> create a new one. 4320 * <p> 4321 * When the ItemAnimator is running a change animation, there might be 2 ViewHolders 4322 * representing the same Item. In this case, the updated ViewHolder will be returned. 4323 * 4324 * @param position The position of the item in the data set of the adapter 4325 * @return The ViewHolder at <code>position</code> or null if there is no such item 4326 */ 4327 public ViewHolder findViewHolderForAdapterPosition(int position) { 4328 if (mDataSetHasChangedAfterLayout) { 4329 return null; 4330 } 4331 final int childCount = mChildHelper.getUnfilteredChildCount(); 4332 // hidden VHs are not preferred but if that is the only one we find, we rather return it 4333 ViewHolder hidden = null; 4334 for (int i = 0; i < childCount; i++) { 4335 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 4336 if (holder != null && !holder.isRemoved() && getAdapterPositionFor(holder) == position) { 4337 if (mChildHelper.isHidden(holder.itemView)) { 4338 hidden = holder; 4339 } else { 4340 return holder; 4341 } 4342 } 4343 } 4344 return hidden; 4345 } 4346 4347 ViewHolder findViewHolderForPosition(int position, boolean checkNewPosition) { 4348 final int childCount = mChildHelper.getUnfilteredChildCount(); 4349 ViewHolder hidden = null; 4350 for (int i = 0; i < childCount; i++) { 4351 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 4352 if (holder != null && !holder.isRemoved()) { 4353 if (checkNewPosition) { 4354 if (holder.mPosition != position) { 4355 continue; 4356 } 4357 } else if (holder.getLayoutPosition() != position) { 4358 continue; 4359 } 4360 if (mChildHelper.isHidden(holder.itemView)) { 4361 hidden = holder; 4362 } else { 4363 return holder; 4364 } 4365 } 4366 } 4367 // This method should not query cached views. It creates a problem during adapter updates 4368 // when we are dealing with already laid out views. Also, for the public method, it is more 4369 // reasonable to return null if position is not laid out. 4370 return hidden; 4371 } 4372 4373 /** 4374 * Return the ViewHolder for the item with the given id. The RecyclerView must 4375 * use an Adapter with {@link Adapter#setHasStableIds(boolean) stableIds} to 4376 * return a non-null value. 4377 * <p> 4378 * This method checks only the children of RecyclerView. If the item with the given 4379 * <code>id</code> is not laid out, it <em>will not</em> create a new one. 4380 * 4381 * When the ItemAnimator is running a change animation, there might be 2 ViewHolders with the 4382 * same id. In this case, the updated ViewHolder will be returned. 4383 * 4384 * @param id The id for the requested item 4385 * @return The ViewHolder with the given <code>id</code> or null if there is no such item 4386 */ 4387 public ViewHolder findViewHolderForItemId(long id) { 4388 if (mAdapter == null || !mAdapter.hasStableIds()) { 4389 return null; 4390 } 4391 final int childCount = mChildHelper.getUnfilteredChildCount(); 4392 ViewHolder hidden = null; 4393 for (int i = 0; i < childCount; i++) { 4394 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 4395 if (holder != null && !holder.isRemoved() && holder.getItemId() == id) { 4396 if (mChildHelper.isHidden(holder.itemView)) { 4397 hidden = holder; 4398 } else { 4399 return holder; 4400 } 4401 } 4402 } 4403 return hidden; 4404 } 4405 4406 /** 4407 * Find the topmost view under the given point. 4408 * 4409 * @param x Horizontal position in pixels to search 4410 * @param y Vertical position in pixels to search 4411 * @return The child view under (x, y) or null if no matching child is found 4412 */ 4413 public View findChildViewUnder(float x, float y) { 4414 final int count = mChildHelper.getChildCount(); 4415 for (int i = count - 1; i >= 0; i--) { 4416 final View child = mChildHelper.getChildAt(i); 4417 final float translationX = ViewCompat.getTranslationX(child); 4418 final float translationY = ViewCompat.getTranslationY(child); 4419 if (x >= child.getLeft() + translationX && 4420 x <= child.getRight() + translationX && 4421 y >= child.getTop() + translationY && 4422 y <= child.getBottom() + translationY) { 4423 return child; 4424 } 4425 } 4426 return null; 4427 } 4428 4429 @Override 4430 public boolean drawChild(Canvas canvas, View child, long drawingTime) { 4431 return super.drawChild(canvas, child, drawingTime); 4432 } 4433 4434 /** 4435 * Offset the bounds of all child views by <code>dy</code> pixels. 4436 * Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}. 4437 * 4438 * @param dy Vertical pixel offset to apply to the bounds of all child views 4439 */ 4440 public void offsetChildrenVertical(int dy) { 4441 final int childCount = mChildHelper.getChildCount(); 4442 for (int i = 0; i < childCount; i++) { 4443 mChildHelper.getChildAt(i).offsetTopAndBottom(dy); 4444 } 4445 } 4446 4447 /** 4448 * Called when an item view is attached to this RecyclerView. 4449 * 4450 * <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications 4451 * of child views as they become attached. This will be called before a 4452 * {@link LayoutManager} measures or lays out the view and is a good time to perform these 4453 * changes.</p> 4454 * 4455 * @param child Child view that is now attached to this RecyclerView and its associated window 4456 */ 4457 public void onChildAttachedToWindow(View child) { 4458 } 4459 4460 /** 4461 * Called when an item view is detached from this RecyclerView. 4462 * 4463 * <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications 4464 * of child views as they become detached. This will be called as a 4465 * {@link LayoutManager} fully detaches the child view from the parent and its window.</p> 4466 * 4467 * @param child Child view that is now detached from this RecyclerView and its associated window 4468 */ 4469 public void onChildDetachedFromWindow(View child) { 4470 } 4471 4472 /** 4473 * Offset the bounds of all child views by <code>dx</code> pixels. 4474 * Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}. 4475 * 4476 * @param dx Horizontal pixel offset to apply to the bounds of all child views 4477 */ 4478 public void offsetChildrenHorizontal(int dx) { 4479 final int childCount = mChildHelper.getChildCount(); 4480 for (int i = 0; i < childCount; i++) { 4481 mChildHelper.getChildAt(i).offsetLeftAndRight(dx); 4482 } 4483 } 4484 4485 /** 4486 * Returns the bounds of the view including its decoration and margins. 4487 * 4488 * @param view The view element to check 4489 * @param outBounds A rect that will receive the bounds of the element including its 4490 * decoration and margins. 4491 */ 4492 public void getDecoratedBoundsWithMargins(View view, Rect outBounds) { 4493 getDecoratedBoundsWithMarginsInt(view, outBounds); 4494 } 4495 4496 static void getDecoratedBoundsWithMarginsInt(View view, Rect outBounds) { 4497 final LayoutParams lp = (LayoutParams) view.getLayoutParams(); 4498 final Rect insets = lp.mDecorInsets; 4499 outBounds.set(view.getLeft() - insets.left - lp.leftMargin, 4500 view.getTop() - insets.top - lp.topMargin, 4501 view.getRight() + insets.right + lp.rightMargin, 4502 view.getBottom() + insets.bottom + lp.bottomMargin); 4503 } 4504 4505 Rect getItemDecorInsetsForChild(View child) { 4506 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 4507 if (!lp.mInsetsDirty) { 4508 return lp.mDecorInsets; 4509 } 4510 4511 if (mState.isPreLayout() && (lp.isItemChanged() || lp.isViewInvalid())) { 4512 // changed/invalid items should not be updated until they are rebound. 4513 return lp.mDecorInsets; 4514 } 4515 final Rect insets = lp.mDecorInsets; 4516 insets.set(0, 0, 0, 0); 4517 final int decorCount = mItemDecorations.size(); 4518 for (int i = 0; i < decorCount; i++) { 4519 mTempRect.set(0, 0, 0, 0); 4520 mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState); 4521 insets.left += mTempRect.left; 4522 insets.top += mTempRect.top; 4523 insets.right += mTempRect.right; 4524 insets.bottom += mTempRect.bottom; 4525 } 4526 lp.mInsetsDirty = false; 4527 return insets; 4528 } 4529 4530 /** 4531 * Called when the scroll position of this RecyclerView changes. Subclasses should use 4532 * this method to respond to scrolling within the adapter's data set instead of an explicit 4533 * listener. 4534 * 4535 * <p>This method will always be invoked before listeners. If a subclass needs to perform 4536 * any additional upkeep or bookkeeping after scrolling but before listeners run, 4537 * this is a good place to do so.</p> 4538 * 4539 * <p>This differs from {@link View#onScrollChanged(int, int, int, int)} in that it receives 4540 * the distance scrolled in either direction within the adapter's data set instead of absolute 4541 * scroll coordinates. Since RecyclerView cannot compute the absolute scroll position from 4542 * any arbitrary point in the data set, <code>onScrollChanged</code> will always receive 4543 * the current {@link View#getScrollX()} and {@link View#getScrollY()} values which 4544 * do not correspond to the data set scroll position. However, some subclasses may choose 4545 * to use these fields as special offsets.</p> 4546 * 4547 * @param dx horizontal distance scrolled in pixels 4548 * @param dy vertical distance scrolled in pixels 4549 */ 4550 public void onScrolled(int dx, int dy) { 4551 // Do nothing 4552 } 4553 4554 void dispatchOnScrolled(int hresult, int vresult) { 4555 mDispatchScrollCounter ++; 4556 // Pass the current scrollX/scrollY values; no actual change in these properties occurred 4557 // but some general-purpose code may choose to respond to changes this way. 4558 final int scrollX = getScrollX(); 4559 final int scrollY = getScrollY(); 4560 onScrollChanged(scrollX, scrollY, scrollX, scrollY); 4561 4562 // Pass the real deltas to onScrolled, the RecyclerView-specific method. 4563 onScrolled(hresult, vresult); 4564 4565 // Invoke listeners last. Subclassed view methods always handle the event first. 4566 // All internal state is consistent by the time listeners are invoked. 4567 if (mScrollListener != null) { 4568 mScrollListener.onScrolled(this, hresult, vresult); 4569 } 4570 if (mScrollListeners != null) { 4571 for (int i = mScrollListeners.size() - 1; i >= 0; i--) { 4572 mScrollListeners.get(i).onScrolled(this, hresult, vresult); 4573 } 4574 } 4575 mDispatchScrollCounter --; 4576 } 4577 4578 /** 4579 * Called when the scroll state of this RecyclerView changes. Subclasses should use this 4580 * method to respond to state changes instead of an explicit listener. 4581 * 4582 * <p>This method will always be invoked before listeners, but after the LayoutManager 4583 * responds to the scroll state change.</p> 4584 * 4585 * @param state the new scroll state, one of {@link #SCROLL_STATE_IDLE}, 4586 * {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING} 4587 */ 4588 public void onScrollStateChanged(int state) { 4589 // Do nothing 4590 } 4591 4592 void dispatchOnScrollStateChanged(int state) { 4593 // Let the LayoutManager go first; this allows it to bring any properties into 4594 // a consistent state before the RecyclerView subclass responds. 4595 if (mLayout != null) { 4596 mLayout.onScrollStateChanged(state); 4597 } 4598 4599 // Let the RecyclerView subclass handle this event next; any LayoutManager property 4600 // changes will be reflected by this time. 4601 onScrollStateChanged(state); 4602 4603 // Listeners go last. All other internal state is consistent by this point. 4604 if (mScrollListener != null) { 4605 mScrollListener.onScrollStateChanged(this, state); 4606 } 4607 if (mScrollListeners != null) { 4608 for (int i = mScrollListeners.size() - 1; i >= 0; i--) { 4609 mScrollListeners.get(i).onScrollStateChanged(this, state); 4610 } 4611 } 4612 } 4613 4614 /** 4615 * Returns whether there are pending adapter updates which are not yet applied to the layout. 4616 * <p> 4617 * If this method returns <code>true</code>, it means that what user is currently seeing may not 4618 * reflect them adapter contents (depending on what has changed). 4619 * You may use this information to defer or cancel some operations. 4620 * <p> 4621 * This method returns true if RecyclerView has not yet calculated the first layout after it is 4622 * attached to the Window or the Adapter has been replaced. 4623 * 4624 * @return True if there are some adapter updates which are not yet reflected to layout or false 4625 * if layout is up to date. 4626 */ 4627 public boolean hasPendingAdapterUpdates() { 4628 return !mFirstLayoutComplete || mDataSetHasChangedAfterLayout 4629 || mAdapterHelper.hasPendingUpdates(); 4630 } 4631 4632 class ViewFlinger implements Runnable { 4633 private int mLastFlingX; 4634 private int mLastFlingY; 4635 private ScrollerCompat mScroller; 4636 Interpolator mInterpolator = sQuinticInterpolator; 4637 4638 4639 // When set to true, postOnAnimation callbacks are delayed until the run method completes 4640 private boolean mEatRunOnAnimationRequest = false; 4641 4642 // Tracks if postAnimationCallback should be re-attached when it is done 4643 private boolean mReSchedulePostAnimationCallback = false; 4644 4645 public ViewFlinger() { 4646 mScroller = ScrollerCompat.create(getContext(), sQuinticInterpolator); 4647 } 4648 4649 @Override 4650 public void run() { 4651 if (mLayout == null) { 4652 stop(); 4653 return; // no layout, cannot scroll. 4654 } 4655 disableRunOnAnimationRequests(); 4656 consumePendingUpdateOperations(); 4657 // keep a local reference so that if it is changed during onAnimation method, it won't 4658 // cause unexpected behaviors 4659 final ScrollerCompat scroller = mScroller; 4660 final SmoothScroller smoothScroller = mLayout.mSmoothScroller; 4661 if (scroller.computeScrollOffset()) { 4662 final int x = scroller.getCurrX(); 4663 final int y = scroller.getCurrY(); 4664 final int dx = x - mLastFlingX; 4665 final int dy = y - mLastFlingY; 4666 int hresult = 0; 4667 int vresult = 0; 4668 mLastFlingX = x; 4669 mLastFlingY = y; 4670 int overscrollX = 0, overscrollY = 0; 4671 if (mAdapter != null) { 4672 eatRequestLayout(); 4673 onEnterLayoutOrScroll(); 4674 TraceCompat.beginSection(TRACE_SCROLL_TAG); 4675 if (dx != 0) { 4676 hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState); 4677 overscrollX = dx - hresult; 4678 } 4679 if (dy != 0) { 4680 vresult = mLayout.scrollVerticallyBy(dy, mRecycler, mState); 4681 overscrollY = dy - vresult; 4682 } 4683 TraceCompat.endSection(); 4684 repositionShadowingViews(); 4685 4686 onExitLayoutOrScroll(); 4687 resumeRequestLayout(false); 4688 4689 if (smoothScroller != null && !smoothScroller.isPendingInitialRun() && 4690 smoothScroller.isRunning()) { 4691 final int adapterSize = mState.getItemCount(); 4692 if (adapterSize == 0) { 4693 smoothScroller.stop(); 4694 } else if (smoothScroller.getTargetPosition() >= adapterSize) { 4695 smoothScroller.setTargetPosition(adapterSize - 1); 4696 smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY); 4697 } else { 4698 smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY); 4699 } 4700 } 4701 } 4702 if (!mItemDecorations.isEmpty()) { 4703 invalidate(); 4704 } 4705 if (getOverScrollMode() != View.OVER_SCROLL_NEVER) { 4706 considerReleasingGlowsOnScroll(dx, dy); 4707 } 4708 if (overscrollX != 0 || overscrollY != 0) { 4709 final int vel = (int) scroller.getCurrVelocity(); 4710 4711 int velX = 0; 4712 if (overscrollX != x) { 4713 velX = overscrollX < 0 ? -vel : overscrollX > 0 ? vel : 0; 4714 } 4715 4716 int velY = 0; 4717 if (overscrollY != y) { 4718 velY = overscrollY < 0 ? -vel : overscrollY > 0 ? vel : 0; 4719 } 4720 4721 if (getOverScrollMode() != View.OVER_SCROLL_NEVER) { 4722 absorbGlows(velX, velY); 4723 } 4724 if ((velX != 0 || overscrollX == x || scroller.getFinalX() == 0) && 4725 (velY != 0 || overscrollY == y || scroller.getFinalY() == 0)) { 4726 scroller.abortAnimation(); 4727 } 4728 } 4729 if (hresult != 0 || vresult != 0) { 4730 dispatchOnScrolled(hresult, vresult); 4731 } 4732 4733 if (!awakenScrollBars()) { 4734 invalidate(); 4735 } 4736 4737 final boolean fullyConsumedVertical = dy != 0 && mLayout.canScrollVertically() 4738 && vresult == dy; 4739 final boolean fullyConsumedHorizontal = dx != 0 && mLayout.canScrollHorizontally() 4740 && hresult == dx; 4741 final boolean fullyConsumedAny = (dx == 0 && dy == 0) || fullyConsumedHorizontal 4742 || fullyConsumedVertical; 4743 4744 if (scroller.isFinished() || !fullyConsumedAny) { 4745 setScrollState(SCROLL_STATE_IDLE); // setting state to idle will stop this. 4746 if (ALLOW_THREAD_GAP_WORK) { 4747 mPrefetchRegistry.clearPrefetchPositions(); 4748 } 4749 } else { 4750 postOnAnimation(); 4751 if (mGapWorker != null) { 4752 mGapWorker.postFromTraversal(RecyclerView.this, dx, dy); 4753 } 4754 } 4755 } 4756 // call this after the onAnimation is complete not to have inconsistent callbacks etc. 4757 if (smoothScroller != null) { 4758 if (smoothScroller.isPendingInitialRun()) { 4759 smoothScroller.onAnimation(0, 0); 4760 } 4761 if (!mReSchedulePostAnimationCallback) { 4762 smoothScroller.stop(); //stop if it does not trigger any scroll 4763 } 4764 } 4765 enableRunOnAnimationRequests(); 4766 } 4767 4768 private void disableRunOnAnimationRequests() { 4769 mReSchedulePostAnimationCallback = false; 4770 mEatRunOnAnimationRequest = true; 4771 } 4772 4773 private void enableRunOnAnimationRequests() { 4774 mEatRunOnAnimationRequest = false; 4775 if (mReSchedulePostAnimationCallback) { 4776 postOnAnimation(); 4777 } 4778 } 4779 4780 void postOnAnimation() { 4781 if (mEatRunOnAnimationRequest) { 4782 mReSchedulePostAnimationCallback = true; 4783 } else { 4784 removeCallbacks(this); 4785 ViewCompat.postOnAnimation(RecyclerView.this, this); 4786 } 4787 } 4788 4789 public void fling(int velocityX, int velocityY) { 4790 setScrollState(SCROLL_STATE_SETTLING); 4791 mLastFlingX = mLastFlingY = 0; 4792 mScroller.fling(0, 0, velocityX, velocityY, 4793 Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); 4794 postOnAnimation(); 4795 } 4796 4797 public void smoothScrollBy(int dx, int dy) { 4798 smoothScrollBy(dx, dy, 0, 0); 4799 } 4800 4801 public void smoothScrollBy(int dx, int dy, int vx, int vy) { 4802 smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, vx, vy)); 4803 } 4804 4805 private float distanceInfluenceForSnapDuration(float f) { 4806 f -= 0.5f; // center the values about 0. 4807 f *= 0.3f * Math.PI / 2.0f; 4808 return (float) Math.sin(f); 4809 } 4810 4811 private int computeScrollDuration(int dx, int dy, int vx, int vy) { 4812 final int absDx = Math.abs(dx); 4813 final int absDy = Math.abs(dy); 4814 final boolean horizontal = absDx > absDy; 4815 final int velocity = (int) Math.sqrt(vx * vx + vy * vy); 4816 final int delta = (int) Math.sqrt(dx * dx + dy * dy); 4817 final int containerSize = horizontal ? getWidth() : getHeight(); 4818 final int halfContainerSize = containerSize / 2; 4819 final float distanceRatio = Math.min(1.f, 1.f * delta / containerSize); 4820 final float distance = halfContainerSize + halfContainerSize * 4821 distanceInfluenceForSnapDuration(distanceRatio); 4822 4823 final int duration; 4824 if (velocity > 0) { 4825 duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 4826 } else { 4827 float absDelta = (float) (horizontal ? absDx : absDy); 4828 duration = (int) (((absDelta / containerSize) + 1) * 300); 4829 } 4830 return Math.min(duration, MAX_SCROLL_DURATION); 4831 } 4832 4833 public void smoothScrollBy(int dx, int dy, int duration) { 4834 smoothScrollBy(dx, dy, duration, sQuinticInterpolator); 4835 } 4836 4837 public void smoothScrollBy(int dx, int dy, Interpolator interpolator) { 4838 smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, 0, 0), 4839 interpolator == null ? sQuinticInterpolator : interpolator); 4840 } 4841 4842 public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) { 4843 if (mInterpolator != interpolator) { 4844 mInterpolator = interpolator; 4845 mScroller = ScrollerCompat.create(getContext(), interpolator); 4846 } 4847 setScrollState(SCROLL_STATE_SETTLING); 4848 mLastFlingX = mLastFlingY = 0; 4849 mScroller.startScroll(0, 0, dx, dy, duration); 4850 postOnAnimation(); 4851 } 4852 4853 public void stop() { 4854 removeCallbacks(this); 4855 mScroller.abortAnimation(); 4856 } 4857 4858 } 4859 4860 void repositionShadowingViews() { 4861 // Fix up shadow views used by change animations 4862 int count = mChildHelper.getChildCount(); 4863 for (int i = 0; i < count; i++) { 4864 View view = mChildHelper.getChildAt(i); 4865 ViewHolder holder = getChildViewHolder(view); 4866 if (holder != null && holder.mShadowingHolder != null) { 4867 View shadowingView = holder.mShadowingHolder.itemView; 4868 int left = view.getLeft(); 4869 int top = view.getTop(); 4870 if (left != shadowingView.getLeft() || 4871 top != shadowingView.getTop()) { 4872 shadowingView.layout(left, top, 4873 left + shadowingView.getWidth(), 4874 top + shadowingView.getHeight()); 4875 } 4876 } 4877 } 4878 } 4879 4880 private class RecyclerViewDataObserver extends AdapterDataObserver { 4881 RecyclerViewDataObserver() { 4882 } 4883 4884 @Override 4885 public void onChanged() { 4886 assertNotInLayoutOrScroll(null); 4887 mState.mStructureChanged = true; 4888 4889 setDataSetChangedAfterLayout(); 4890 if (!mAdapterHelper.hasPendingUpdates()) { 4891 requestLayout(); 4892 } 4893 } 4894 4895 @Override 4896 public void onItemRangeChanged(int positionStart, int itemCount, Object payload) { 4897 assertNotInLayoutOrScroll(null); 4898 if (mAdapterHelper.onItemRangeChanged(positionStart, itemCount, payload)) { 4899 triggerUpdateProcessor(); 4900 } 4901 } 4902 4903 @Override 4904 public void onItemRangeInserted(int positionStart, int itemCount) { 4905 assertNotInLayoutOrScroll(null); 4906 if (mAdapterHelper.onItemRangeInserted(positionStart, itemCount)) { 4907 triggerUpdateProcessor(); 4908 } 4909 } 4910 4911 @Override 4912 public void onItemRangeRemoved(int positionStart, int itemCount) { 4913 assertNotInLayoutOrScroll(null); 4914 if (mAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) { 4915 triggerUpdateProcessor(); 4916 } 4917 } 4918 4919 @Override 4920 public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { 4921 assertNotInLayoutOrScroll(null); 4922 if (mAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) { 4923 triggerUpdateProcessor(); 4924 } 4925 } 4926 4927 void triggerUpdateProcessor() { 4928 if (POST_UPDATES_ON_ANIMATION && mHasFixedSize && mIsAttached) { 4929 ViewCompat.postOnAnimation(RecyclerView.this, mUpdateChildViewsRunnable); 4930 } else { 4931 mAdapterUpdateDuringMeasure = true; 4932 requestLayout(); 4933 } 4934 } 4935 } 4936 4937 /** 4938 * RecycledViewPool lets you share Views between multiple RecyclerViews. 4939 * <p> 4940 * If you want to recycle views across RecyclerViews, create an instance of RecycledViewPool 4941 * and use {@link RecyclerView#setRecycledViewPool(RecycledViewPool)}. 4942 * <p> 4943 * RecyclerView automatically creates a pool for itself if you don't provide one. 4944 * 4945 */ 4946 public static class RecycledViewPool { 4947 private static final int DEFAULT_MAX_SCRAP = 5; 4948 4949 /** 4950 * Tracks both pooled holders, as well as create/bind timing metadata for the given type. 4951 * 4952 * Note that this tracks running averages of create/bind time across all RecyclerViews 4953 * (and, indirectly, Adapters) that use this pool. 4954 * 4955 * 1) This enables us to track average create and bind times across multiple adapters. Even 4956 * though create (and especially bind) may behave differently for different Adapter 4957 * subclasses, sharing the pool is a strong signal that they'll perform similarly, per type. 4958 * 4959 * 2) If {@link #willBindInTime(int, long, long)} returns false for one view, it will return 4960 * false for all other views of its type for the same deadline. This prevents items 4961 * constructed by {@link GapWorker} prefetch from being bound to a lower priority prefetch. 4962 */ 4963 static class ScrapData { 4964 ArrayList<ViewHolder> mScrapHeap = new ArrayList<>(); 4965 int mMaxScrap = DEFAULT_MAX_SCRAP; 4966 long mCreateRunningAverageNs = 0; 4967 long mBindRunningAverageNs = 0; 4968 } 4969 SparseArray<ScrapData> mScrap = new SparseArray<>(); 4970 4971 private int mAttachCount = 0; 4972 4973 public void clear() { 4974 for (int i = 0; i < mScrap.size(); i++) { 4975 ScrapData data = mScrap.valueAt(i); 4976 data.mScrapHeap.clear(); 4977 } 4978 } 4979 4980 public void setMaxRecycledViews(int viewType, int max) { 4981 ScrapData scrapData = getScrapDataForType(viewType); 4982 scrapData.mMaxScrap = max; 4983 final ArrayList<ViewHolder> scrapHeap = scrapData.mScrapHeap; 4984 if (scrapHeap != null) { 4985 while (scrapHeap.size() > max) { 4986 scrapHeap.remove(scrapHeap.size() - 1); 4987 } 4988 } 4989 } 4990 4991 /** 4992 * Returns the current number of Views held by the RecycledViewPool of the given view type. 4993 */ 4994 public int getRecycledViewCount(int viewType) { 4995 return getScrapDataForType(viewType).mScrapHeap.size(); 4996 } 4997 4998 public ViewHolder getRecycledView(int viewType) { 4999 final ScrapData scrapData = mScrap.get(viewType); 5000 if (scrapData != null && !scrapData.mScrapHeap.isEmpty()) { 5001 final ArrayList<ViewHolder> scrapHeap = scrapData.mScrapHeap; 5002 return scrapHeap.remove(scrapHeap.size() - 1); 5003 } 5004 return null; 5005 } 5006 5007 int size() { 5008 int count = 0; 5009 for (int i = 0; i < mScrap.size(); i ++) { 5010 ArrayList<ViewHolder> viewHolders = mScrap.valueAt(i).mScrapHeap; 5011 if (viewHolders != null) { 5012 count += viewHolders.size(); 5013 } 5014 } 5015 return count; 5016 } 5017 5018 public void putRecycledView(ViewHolder scrap) { 5019 final int viewType = scrap.getItemViewType(); 5020 final ArrayList scrapHeap = getScrapDataForType(viewType).mScrapHeap; 5021 if (mScrap.get(viewType).mMaxScrap <= scrapHeap.size()) { 5022 return; 5023 } 5024 if (DEBUG && scrapHeap.contains(scrap)) { 5025 throw new IllegalArgumentException("this scrap item already exists"); 5026 } 5027 scrap.resetInternal(); 5028 scrapHeap.add(scrap); 5029 } 5030 5031 long runningAverage(long oldAverage, long newValue) { 5032 if (oldAverage == 0) { 5033 return newValue; 5034 } 5035 return (oldAverage / 4 * 3) + (newValue / 4); 5036 } 5037 5038 void factorInCreateTime(int viewType, long createTimeNs) { 5039 ScrapData scrapData = getScrapDataForType(viewType); 5040 scrapData.mCreateRunningAverageNs = runningAverage( 5041 scrapData.mCreateRunningAverageNs, createTimeNs); 5042 } 5043 5044 void factorInBindTime(int viewType, long bindTimeNs) { 5045 ScrapData scrapData = getScrapDataForType(viewType); 5046 scrapData.mBindRunningAverageNs = runningAverage( 5047 scrapData.mBindRunningAverageNs, bindTimeNs); 5048 } 5049 5050 boolean willCreateInTime(int viewType, long approxCurrentNs, long deadlineNs) { 5051 long expectedDurationNs = getScrapDataForType(viewType).mCreateRunningAverageNs; 5052 return expectedDurationNs == 0 || (approxCurrentNs + expectedDurationNs < deadlineNs); 5053 } 5054 5055 boolean willBindInTime(int viewType, long approxCurrentNs, long deadlineNs) { 5056 long expectedDurationNs = getScrapDataForType(viewType).mBindRunningAverageNs; 5057 return expectedDurationNs == 0 || (approxCurrentNs + expectedDurationNs < deadlineNs); 5058 } 5059 5060 void attach(Adapter adapter) { 5061 mAttachCount++; 5062 } 5063 5064 void detach() { 5065 mAttachCount--; 5066 } 5067 5068 5069 /** 5070 * Detaches the old adapter and attaches the new one. 5071 * <p> 5072 * RecycledViewPool will clear its cache if it has only one adapter attached and the new 5073 * adapter uses a different ViewHolder than the oldAdapter. 5074 * 5075 * @param oldAdapter The previous adapter instance. Will be detached. 5076 * @param newAdapter The new adapter instance. Will be attached. 5077 * @param compatibleWithPrevious True if both oldAdapter and newAdapter are using the same 5078 * ViewHolder and view types. 5079 */ 5080 void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter, 5081 boolean compatibleWithPrevious) { 5082 if (oldAdapter != null) { 5083 detach(); 5084 } 5085 if (!compatibleWithPrevious && mAttachCount == 0) { 5086 clear(); 5087 } 5088 if (newAdapter != null) { 5089 attach(newAdapter); 5090 } 5091 } 5092 5093 private ScrapData getScrapDataForType(int viewType) { 5094 ScrapData scrapData = mScrap.get(viewType); 5095 if (scrapData == null) { 5096 scrapData = new ScrapData(); 5097 mScrap.put(viewType, scrapData); 5098 } 5099 return scrapData; 5100 } 5101 } 5102 5103 /** 5104 * Utility method for finding an internal RecyclerView, if present 5105 */ 5106 @Nullable 5107 static RecyclerView findNestedRecyclerView(@NonNull View view) { 5108 if (!(view instanceof ViewGroup)) { 5109 return null; 5110 } 5111 if (view instanceof RecyclerView) { 5112 return (RecyclerView) view; 5113 } 5114 final ViewGroup parent = (ViewGroup) view; 5115 final int count = parent.getChildCount(); 5116 for (int i = 0; i < count; i++) { 5117 final View child = parent.getChildAt(i); 5118 final RecyclerView descendant = findNestedRecyclerView(child); 5119 if (descendant != null) { 5120 return descendant; 5121 } 5122 } 5123 return null; 5124 } 5125 5126 /** 5127 * Utility method for clearing holder's internal RecyclerView, if present 5128 */ 5129 static void clearNestedRecyclerViewIfNotNested(@NonNull ViewHolder holder) { 5130 if (holder.mNestedRecyclerView != null) { 5131 View item = holder.mNestedRecyclerView.get(); 5132 while (item != null) { 5133 if (item == holder.itemView) { 5134 return; // match found, don't need to clear 5135 } 5136 5137 ViewParent parent = item.getParent(); 5138 if (parent instanceof View) { 5139 item = (View) parent; 5140 } else { 5141 item = null; 5142 } 5143 } 5144 holder.mNestedRecyclerView = null; // not nested 5145 } 5146 } 5147 5148 /** 5149 * Time base for deadline-aware work scheduling. Overridable for testing. 5150 * 5151 * Will return 0 to avoid cost of System.nanoTime where deadline-aware work scheduling 5152 * isn't relevant. 5153 */ 5154 long getNanoTime() { 5155 if (ALLOW_THREAD_GAP_WORK) { 5156 return System.nanoTime(); 5157 } else { 5158 return 0; 5159 } 5160 } 5161 5162 /** 5163 * A Recycler is responsible for managing scrapped or detached item views for reuse. 5164 * 5165 * <p>A "scrapped" view is a view that is still attached to its parent RecyclerView but 5166 * that has been marked for removal or reuse.</p> 5167 * 5168 * <p>Typical use of a Recycler by a {@link LayoutManager} will be to obtain views for 5169 * an adapter's data set representing the data at a given position or item ID. 5170 * If the view to be reused is considered "dirty" the adapter will be asked to rebind it. 5171 * If not, the view can be quickly reused by the LayoutManager with no further work. 5172 * Clean views that have not {@link android.view.View#isLayoutRequested() requested layout} 5173 * may be repositioned by a LayoutManager without remeasurement.</p> 5174 */ 5175 public final class Recycler { 5176 final ArrayList<ViewHolder> mAttachedScrap = new ArrayList<>(); 5177 ArrayList<ViewHolder> mChangedScrap = null; 5178 5179 final ArrayList<ViewHolder> mCachedViews = new ArrayList<ViewHolder>(); 5180 5181 private final List<ViewHolder> 5182 mUnmodifiableAttachedScrap = Collections.unmodifiableList(mAttachedScrap); 5183 5184 private int mRequestedCacheMax = DEFAULT_CACHE_SIZE; 5185 int mViewCacheMax = DEFAULT_CACHE_SIZE; 5186 5187 RecycledViewPool mRecyclerPool; 5188 5189 private ViewCacheExtension mViewCacheExtension; 5190 5191 static final int DEFAULT_CACHE_SIZE = 2; 5192 5193 /** 5194 * Clear scrap views out of this recycler. Detached views contained within a 5195 * recycled view pool will remain. 5196 */ 5197 public void clear() { 5198 mAttachedScrap.clear(); 5199 recycleAndClearCachedViews(); 5200 } 5201 5202 /** 5203 * Set the maximum number of detached, valid views we should retain for later use. 5204 * 5205 * @param viewCount Number of views to keep before sending views to the shared pool 5206 */ 5207 public void setViewCacheSize(int viewCount) { 5208 mRequestedCacheMax = viewCount; 5209 updateViewCacheSize(); 5210 } 5211 5212 void updateViewCacheSize() { 5213 int extraCache = mLayout != null ? mLayout.mPrefetchMaxCountObserved : 0; 5214 mViewCacheMax = mRequestedCacheMax + extraCache; 5215 5216 // first, try the views that can be recycled 5217 for (int i = mCachedViews.size() - 1; 5218 i >= 0 && mCachedViews.size() > mViewCacheMax; i--) { 5219 recycleCachedViewAt(i); 5220 } 5221 } 5222 5223 /** 5224 * Returns an unmodifiable list of ViewHolders that are currently in the scrap list. 5225 * 5226 * @return List of ViewHolders in the scrap list. 5227 */ 5228 public List<ViewHolder> getScrapList() { 5229 return mUnmodifiableAttachedScrap; 5230 } 5231 5232 /** 5233 * Helper method for getViewForPosition. 5234 * <p> 5235 * Checks whether a given view holder can be used for the provided position. 5236 * 5237 * @param holder ViewHolder 5238 * @return true if ViewHolder matches the provided position, false otherwise 5239 */ 5240 boolean validateViewHolderForOffsetPosition(ViewHolder holder) { 5241 // if it is a removed holder, nothing to verify since we cannot ask adapter anymore 5242 // if it is not removed, verify the type and id. 5243 if (holder.isRemoved()) { 5244 if (DEBUG && !mState.isPreLayout()) { 5245 throw new IllegalStateException("should not receive a removed view unless it" 5246 + " is pre layout"); 5247 } 5248 return mState.isPreLayout(); 5249 } 5250 if (holder.mPosition < 0 || holder.mPosition >= mAdapter.getItemCount()) { 5251 throw new IndexOutOfBoundsException("Inconsistency detected. Invalid view holder " 5252 + "adapter position" + holder); 5253 } 5254 if (!mState.isPreLayout()) { 5255 // don't check type if it is pre-layout. 5256 final int type = mAdapter.getItemViewType(holder.mPosition); 5257 if (type != holder.getItemViewType()) { 5258 return false; 5259 } 5260 } 5261 if (mAdapter.hasStableIds()) { 5262 return holder.getItemId() == mAdapter.getItemId(holder.mPosition); 5263 } 5264 return true; 5265 } 5266 5267 /** 5268 * Attempts to bind view, and account for relevant timing information. If 5269 * deadlineNs != FOREVER_NS, this method may fail to bind, and return false. 5270 * 5271 * @param holder Holder to be bound. 5272 * @param offsetPosition Position of item to be bound. 5273 * @param position Pre-layout position of item to be bound. 5274 * @param deadlineNs Time, relative to getNanoTime(), by which bind/create work should 5275 * complete. If FOREVER_NS is passed, this method will not fail to 5276 * bind the holder. 5277 * @return 5278 */ 5279 private boolean tryBindViewHolderByDeadline(ViewHolder holder, int offsetPosition, 5280 int position, long deadlineNs) { 5281 holder.mOwnerRecyclerView = RecyclerView.this; 5282 final int viewType = holder.getItemViewType(); 5283 long startBindNs = getNanoTime(); 5284 if (deadlineNs != FOREVER_NS 5285 && !mRecyclerPool.willBindInTime(viewType, startBindNs, deadlineNs)) { 5286 // abort - we have a deadline we can't meet 5287 return false; 5288 } 5289 mAdapter.bindViewHolder(holder, offsetPosition); 5290 long endBindNs = getNanoTime(); 5291 mRecyclerPool.factorInBindTime(holder.getItemViewType(), endBindNs - startBindNs); 5292 attachAccessibilityDelegate(holder.itemView); 5293 if (mState.isPreLayout()) { 5294 holder.mPreLayoutPosition = position; 5295 } 5296 return true; 5297 } 5298 5299 /** 5300 * Binds the given View to the position. The View can be a View previously retrieved via 5301 * {@link #getViewForPosition(int)} or created by 5302 * {@link Adapter#onCreateViewHolder(ViewGroup, int)}. 5303 * <p> 5304 * Generally, a LayoutManager should acquire its views via {@link #getViewForPosition(int)} 5305 * and let the RecyclerView handle caching. This is a helper method for LayoutManager who 5306 * wants to handle its own recycling logic. 5307 * <p> 5308 * Note that, {@link #getViewForPosition(int)} already binds the View to the position so 5309 * you don't need to call this method unless you want to bind this View to another position. 5310 * 5311 * @param view The view to update. 5312 * @param position The position of the item to bind to this View. 5313 */ 5314 public void bindViewToPosition(View view, int position) { 5315 ViewHolder holder = getChildViewHolderInt(view); 5316 if (holder == null) { 5317 throw new IllegalArgumentException("The view does not have a ViewHolder. You cannot" 5318 + " pass arbitrary views to this method, they should be created by the " 5319 + "Adapter"); 5320 } 5321 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 5322 if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) { 5323 throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item " 5324 + "position " + position + "(offset:" + offsetPosition + ")." 5325 + "state:" + mState.getItemCount()); 5326 } 5327 tryBindViewHolderByDeadline(holder, offsetPosition, position, FOREVER_NS); 5328 5329 final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); 5330 final LayoutParams rvLayoutParams; 5331 if (lp == null) { 5332 rvLayoutParams = (LayoutParams) generateDefaultLayoutParams(); 5333 holder.itemView.setLayoutParams(rvLayoutParams); 5334 } else if (!checkLayoutParams(lp)) { 5335 rvLayoutParams = (LayoutParams) generateLayoutParams(lp); 5336 holder.itemView.setLayoutParams(rvLayoutParams); 5337 } else { 5338 rvLayoutParams = (LayoutParams) lp; 5339 } 5340 5341 rvLayoutParams.mInsetsDirty = true; 5342 rvLayoutParams.mViewHolder = holder; 5343 rvLayoutParams.mPendingInvalidate = holder.itemView.getParent() == null; 5344 } 5345 5346 /** 5347 * RecyclerView provides artificial position range (item count) in pre-layout state and 5348 * automatically maps these positions to {@link Adapter} positions when 5349 * {@link #getViewForPosition(int)} or {@link #bindViewToPosition(View, int)} is called. 5350 * <p> 5351 * Usually, LayoutManager does not need to worry about this. However, in some cases, your 5352 * LayoutManager may need to call some custom component with item positions in which 5353 * case you need the actual adapter position instead of the pre layout position. You 5354 * can use this method to convert a pre-layout position to adapter (post layout) position. 5355 * <p> 5356 * Note that if the provided position belongs to a deleted ViewHolder, this method will 5357 * return -1. 5358 * <p> 5359 * Calling this method in post-layout state returns the same value back. 5360 * 5361 * @param position The pre-layout position to convert. Must be greater or equal to 0 and 5362 * less than {@link State#getItemCount()}. 5363 */ 5364 public int convertPreLayoutPositionToPostLayout(int position) { 5365 if (position < 0 || position >= mState.getItemCount()) { 5366 throw new IndexOutOfBoundsException("invalid position " + position + ". State " 5367 + "item count is " + mState.getItemCount()); 5368 } 5369 if (!mState.isPreLayout()) { 5370 return position; 5371 } 5372 return mAdapterHelper.findPositionOffset(position); 5373 } 5374 5375 /** 5376 * Obtain a view initialized for the given position. 5377 * 5378 * This method should be used by {@link LayoutManager} implementations to obtain 5379 * views to represent data from an {@link Adapter}. 5380 * <p> 5381 * The Recycler may reuse a scrap or detached view from a shared pool if one is 5382 * available for the correct view type. If the adapter has not indicated that the 5383 * data at the given position has changed, the Recycler will attempt to hand back 5384 * a scrap view that was previously initialized for that data without rebinding. 5385 * 5386 * @param position Position to obtain a view for 5387 * @return A view representing the data at <code>position</code> from <code>adapter</code> 5388 */ 5389 public View getViewForPosition(int position) { 5390 return getViewForPosition(position, false); 5391 } 5392 5393 View getViewForPosition(int position, boolean dryRun) { 5394 return tryGetViewHolderForPositionByDeadline(position, dryRun, FOREVER_NS).itemView; 5395 } 5396 5397 /** 5398 * Attempts to get the ViewHolder for the given position, either from the Recycler scrap, 5399 * cache, the RecycledViewPool, or creating it directly. 5400 * <p> 5401 * If a deadlineNs other than {@link #FOREVER_NS} is passed, this method early return 5402 * rather than constructing or binding a ViewHolder if it doesn't think it has time. 5403 * If a ViewHolder must be constructed and not enough time remains, null is returned. If a 5404 * ViewHolder is aquired and must be bound but not enough time remains, an unbound holder is 5405 * returned. Use {@link ViewHolder#isBound()} on the returned object to check for this. 5406 * 5407 * @param position Position of ViewHolder to be returned. 5408 * @param dryRun True if the ViewHolder should not be removed from scrap/cache/ 5409 * @param deadlineNs Time, relative to getNanoTime(), by which bind/create work should 5410 * complete. If FOREVER_NS is passed, this method will not fail to 5411 * create/bind the holder if needed. 5412 * 5413 * @return ViewHolder for requested position 5414 */ 5415 @Nullable 5416 ViewHolder tryGetViewHolderForPositionByDeadline(int position, 5417 boolean dryRun, long deadlineNs) { 5418 if (position < 0 || position >= mState.getItemCount()) { 5419 throw new IndexOutOfBoundsException("Invalid item position " + position 5420 + "(" + position + "). Item count:" + mState.getItemCount()); 5421 } 5422 boolean fromScrapOrHiddenOrCache = false; 5423 ViewHolder holder = null; 5424 // 0) If there is a changed scrap, try to find from there 5425 if (mState.isPreLayout()) { 5426 holder = getChangedScrapViewForPosition(position); 5427 fromScrapOrHiddenOrCache = holder != null; 5428 } 5429 // 1) Find by position from scrap/hidden list/cache 5430 if (holder == null) { 5431 holder = getScrapOrHiddenOrCachedHolderForPosition(position, dryRun); 5432 if (holder != null) { 5433 if (!validateViewHolderForOffsetPosition(holder)) { 5434 // recycle holder (and unscrap if relevant) since it can't be used 5435 if (!dryRun) { 5436 // we would like to recycle this but need to make sure it is not used by 5437 // animation logic etc. 5438 holder.addFlags(ViewHolder.FLAG_INVALID); 5439 if (holder.isScrap()) { 5440 removeDetachedView(holder.itemView, false); 5441 holder.unScrap(); 5442 } else if (holder.wasReturnedFromScrap()) { 5443 holder.clearReturnedFromScrapFlag(); 5444 } 5445 recycleViewHolderInternal(holder); 5446 } 5447 holder = null; 5448 } else { 5449 fromScrapOrHiddenOrCache = true; 5450 } 5451 } 5452 } 5453 if (holder == null) { 5454 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 5455 if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) { 5456 throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item " 5457 + "position " + position + "(offset:" + offsetPosition + ")." 5458 + "state:" + mState.getItemCount()); 5459 } 5460 5461 final int type = mAdapter.getItemViewType(offsetPosition); 5462 // 2) Find from scrap/cache via stable ids, if exists 5463 if (mAdapter.hasStableIds()) { 5464 holder = getScrapOrCachedViewForId(mAdapter.getItemId(offsetPosition), 5465 type, dryRun); 5466 if (holder != null) { 5467 // update position 5468 holder.mPosition = offsetPosition; 5469 fromScrapOrHiddenOrCache = true; 5470 } 5471 } 5472 if (holder == null && mViewCacheExtension != null) { 5473 // We are NOT sending the offsetPosition because LayoutManager does not 5474 // know it. 5475 final View view = mViewCacheExtension 5476 .getViewForPositionAndType(this, position, type); 5477 if (view != null) { 5478 holder = getChildViewHolder(view); 5479 if (holder == null) { 5480 throw new IllegalArgumentException("getViewForPositionAndType returned" 5481 + " a view which does not have a ViewHolder"); 5482 } else if (holder.shouldIgnore()) { 5483 throw new IllegalArgumentException("getViewForPositionAndType returned" 5484 + " a view that is ignored. You must call stopIgnoring before" 5485 + " returning this view."); 5486 } 5487 } 5488 } 5489 if (holder == null) { // fallback to pool 5490 if (DEBUG) { 5491 Log.d(TAG, "tryGetViewHolderForPositionByDeadline(" 5492 + position + ") fetching from shared pool"); 5493 } 5494 holder = getRecycledViewPool().getRecycledView(type); 5495 if (holder != null) { 5496 holder.resetInternal(); 5497 if (FORCE_INVALIDATE_DISPLAY_LIST) { 5498 invalidateDisplayListInt(holder); 5499 } 5500 } 5501 } 5502 if (holder == null) { 5503 long start = getNanoTime(); 5504 if (deadlineNs != FOREVER_NS 5505 && !mRecyclerPool.willCreateInTime(type, start, deadlineNs)) { 5506 // abort - we have a deadline we can't meet 5507 return null; 5508 } 5509 holder = mAdapter.createViewHolder(RecyclerView.this, type); 5510 if (ALLOW_THREAD_GAP_WORK) { 5511 // only bother finding nested RV if prefetching 5512 RecyclerView innerView = findNestedRecyclerView(holder.itemView); 5513 if (innerView != null) { 5514 holder.mNestedRecyclerView = new WeakReference<>(innerView); 5515 } 5516 } 5517 5518 long end = getNanoTime(); 5519 mRecyclerPool.factorInCreateTime(type, end - start); 5520 if (DEBUG) { 5521 Log.d(TAG, "tryGetViewHolderForPositionByDeadline created new ViewHolder"); 5522 } 5523 } 5524 } 5525 5526 // This is very ugly but the only place we can grab this information 5527 // before the View is rebound and returned to the LayoutManager for post layout ops. 5528 // We don't need this in pre-layout since the VH is not updated by the LM. 5529 if (fromScrapOrHiddenOrCache && !mState.isPreLayout() && holder 5530 .hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST)) { 5531 holder.setFlags(0, ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST); 5532 if (mState.mRunSimpleAnimations) { 5533 int changeFlags = ItemAnimator 5534 .buildAdapterChangeFlagsForAnimations(holder); 5535 changeFlags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT; 5536 final ItemHolderInfo info = mItemAnimator.recordPreLayoutInformation(mState, 5537 holder, changeFlags, holder.getUnmodifiedPayloads()); 5538 recordAnimationInfoIfBouncedHiddenView(holder, info); 5539 } 5540 } 5541 5542 boolean bound = false; 5543 if (mState.isPreLayout() && holder.isBound()) { 5544 // do not update unless we absolutely have to. 5545 holder.mPreLayoutPosition = position; 5546 } else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) { 5547 if (DEBUG && holder.isRemoved()) { 5548 throw new IllegalStateException("Removed holder should be bound and it should" 5549 + " come here only in pre-layout. Holder: " + holder); 5550 } 5551 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 5552 bound = tryBindViewHolderByDeadline(holder, offsetPosition, position, deadlineNs); 5553 } 5554 5555 final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); 5556 final LayoutParams rvLayoutParams; 5557 if (lp == null) { 5558 rvLayoutParams = (LayoutParams) generateDefaultLayoutParams(); 5559 holder.itemView.setLayoutParams(rvLayoutParams); 5560 } else if (!checkLayoutParams(lp)) { 5561 rvLayoutParams = (LayoutParams) generateLayoutParams(lp); 5562 holder.itemView.setLayoutParams(rvLayoutParams); 5563 } else { 5564 rvLayoutParams = (LayoutParams) lp; 5565 } 5566 rvLayoutParams.mViewHolder = holder; 5567 rvLayoutParams.mPendingInvalidate = fromScrapOrHiddenOrCache && bound; 5568 return holder; 5569 } 5570 5571 private void attachAccessibilityDelegate(View itemView) { 5572 if (isAccessibilityEnabled()) { 5573 if (ViewCompat.getImportantForAccessibility(itemView) == 5574 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) { 5575 ViewCompat.setImportantForAccessibility(itemView, 5576 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES); 5577 } 5578 if (!ViewCompat.hasAccessibilityDelegate(itemView)) { 5579 ViewCompat.setAccessibilityDelegate(itemView, 5580 mAccessibilityDelegate.getItemDelegate()); 5581 } 5582 } 5583 } 5584 5585 private void invalidateDisplayListInt(ViewHolder holder) { 5586 if (holder.itemView instanceof ViewGroup) { 5587 invalidateDisplayListInt((ViewGroup) holder.itemView, false); 5588 } 5589 } 5590 5591 private void invalidateDisplayListInt(ViewGroup viewGroup, boolean invalidateThis) { 5592 for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) { 5593 final View view = viewGroup.getChildAt(i); 5594 if (view instanceof ViewGroup) { 5595 invalidateDisplayListInt((ViewGroup) view, true); 5596 } 5597 } 5598 if (!invalidateThis) { 5599 return; 5600 } 5601 // we need to force it to become invisible 5602 if (viewGroup.getVisibility() == View.INVISIBLE) { 5603 viewGroup.setVisibility(View.VISIBLE); 5604 viewGroup.setVisibility(View.INVISIBLE); 5605 } else { 5606 final int visibility = viewGroup.getVisibility(); 5607 viewGroup.setVisibility(View.INVISIBLE); 5608 viewGroup.setVisibility(visibility); 5609 } 5610 } 5611 5612 /** 5613 * Recycle a detached view. The specified view will be added to a pool of views 5614 * for later rebinding and reuse. 5615 * 5616 * <p>A view must be fully detached (removed from parent) before it may be recycled. If the 5617 * View is scrapped, it will be removed from scrap list.</p> 5618 * 5619 * @param view Removed view for recycling 5620 * @see LayoutManager#removeAndRecycleView(View, Recycler) 5621 */ 5622 public void recycleView(View view) { 5623 // This public recycle method tries to make view recycle-able since layout manager 5624 // intended to recycle this view (e.g. even if it is in scrap or change cache) 5625 ViewHolder holder = getChildViewHolderInt(view); 5626 if (holder.isTmpDetached()) { 5627 removeDetachedView(view, false); 5628 } 5629 if (holder.isScrap()) { 5630 holder.unScrap(); 5631 } else if (holder.wasReturnedFromScrap()){ 5632 holder.clearReturnedFromScrapFlag(); 5633 } 5634 recycleViewHolderInternal(holder); 5635 } 5636 5637 /** 5638 * Internally, use this method instead of {@link #recycleView(android.view.View)} to 5639 * catch potential bugs. 5640 * @param view 5641 */ 5642 void recycleViewInternal(View view) { 5643 recycleViewHolderInternal(getChildViewHolderInt(view)); 5644 } 5645 5646 void recycleAndClearCachedViews() { 5647 final int count = mCachedViews.size(); 5648 for (int i = count - 1; i >= 0; i--) { 5649 recycleCachedViewAt(i); 5650 } 5651 mCachedViews.clear(); 5652 if (ALLOW_THREAD_GAP_WORK) { 5653 mPrefetchRegistry.clearPrefetchPositions(); 5654 } 5655 } 5656 5657 /** 5658 * Recycles a cached view and removes the view from the list. Views are added to cache 5659 * if and only if they are recyclable, so this method does not check it again. 5660 * <p> 5661 * A small exception to this rule is when the view does not have an animator reference 5662 * but transient state is true (due to animations created outside ItemAnimator). In that 5663 * case, adapter may choose to recycle it. From RecyclerView's perspective, the view is 5664 * still recyclable since Adapter wants to do so. 5665 * 5666 * @param cachedViewIndex The index of the view in cached views list 5667 */ 5668 void recycleCachedViewAt(int cachedViewIndex) { 5669 if (DEBUG) { 5670 Log.d(TAG, "Recycling cached view at index " + cachedViewIndex); 5671 } 5672 ViewHolder viewHolder = mCachedViews.get(cachedViewIndex); 5673 if (DEBUG) { 5674 Log.d(TAG, "CachedViewHolder to be recycled: " + viewHolder); 5675 } 5676 addViewHolderToRecycledViewPool(viewHolder, true); 5677 mCachedViews.remove(cachedViewIndex); 5678 } 5679 5680 /** 5681 * internal implementation checks if view is scrapped or attached and throws an exception 5682 * if so. 5683 * Public version un-scraps before calling recycle. 5684 */ 5685 void recycleViewHolderInternal(ViewHolder holder) { 5686 if (holder.isScrap() || holder.itemView.getParent() != null) { 5687 throw new IllegalArgumentException( 5688 "Scrapped or attached views may not be recycled. isScrap:" 5689 + holder.isScrap() + " isAttached:" 5690 + (holder.itemView.getParent() != null)); 5691 } 5692 5693 if (holder.isTmpDetached()) { 5694 throw new IllegalArgumentException("Tmp detached view should be removed " 5695 + "from RecyclerView before it can be recycled: " + holder); 5696 } 5697 5698 if (holder.shouldIgnore()) { 5699 throw new IllegalArgumentException("Trying to recycle an ignored view holder. You" 5700 + " should first call stopIgnoringView(view) before calling recycle."); 5701 } 5702 //noinspection unchecked 5703 final boolean transientStatePreventsRecycling = holder 5704 .doesTransientStatePreventRecycling(); 5705 final boolean forceRecycle = mAdapter != null 5706 && transientStatePreventsRecycling 5707 && mAdapter.onFailedToRecycleView(holder); 5708 boolean cached = false; 5709 boolean recycled = false; 5710 if (DEBUG && mCachedViews.contains(holder)) { 5711 throw new IllegalArgumentException("cached view received recycle internal? " + 5712 holder); 5713 } 5714 if (forceRecycle || holder.isRecyclable()) { 5715 if (mViewCacheMax > 0 5716 && !holder.hasAnyOfTheFlags(ViewHolder.FLAG_INVALID 5717 | ViewHolder.FLAG_REMOVED 5718 | ViewHolder.FLAG_UPDATE 5719 | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN)) { 5720 // Retire oldest cached view 5721 int cachedViewSize = mCachedViews.size(); 5722 if (cachedViewSize >= mViewCacheMax && cachedViewSize > 0) { 5723 recycleCachedViewAt(0); 5724 cachedViewSize--; 5725 } 5726 5727 int targetCacheIndex = cachedViewSize; 5728 if (ALLOW_THREAD_GAP_WORK 5729 && cachedViewSize > 0 5730 && !mPrefetchRegistry.lastPrefetchIncludedPosition(holder.mPosition)) { 5731 // when adding the view, skip past most recently prefetched views 5732 int cacheIndex = cachedViewSize - 1; 5733 while (cacheIndex >= 0) { 5734 int cachedPos = mCachedViews.get(cacheIndex).mPosition; 5735 if (!mPrefetchRegistry.lastPrefetchIncludedPosition(cachedPos)) { 5736 break; 5737 } 5738 cacheIndex--; 5739 } 5740 targetCacheIndex = cacheIndex + 1; 5741 } 5742 mCachedViews.add(targetCacheIndex, holder); 5743 cached = true; 5744 } 5745 if (!cached) { 5746 addViewHolderToRecycledViewPool(holder, true); 5747 recycled = true; 5748 } 5749 } else { 5750 // NOTE: A view can fail to be recycled when it is scrolled off while an animation 5751 // runs. In this case, the item is eventually recycled by 5752 // ItemAnimatorRestoreListener#onAnimationFinished. 5753 5754 // TODO: consider cancelling an animation when an item is removed scrollBy, 5755 // to return it to the pool faster 5756 if (DEBUG) { 5757 Log.d(TAG, "trying to recycle a non-recycleable holder. Hopefully, it will " 5758 + "re-visit here. We are still removing it from animation lists"); 5759 } 5760 } 5761 // even if the holder is not removed, we still call this method so that it is removed 5762 // from view holder lists. 5763 mViewInfoStore.removeViewHolder(holder); 5764 if (!cached && !recycled && transientStatePreventsRecycling) { 5765 holder.mOwnerRecyclerView = null; 5766 } 5767 } 5768 5769 /** 5770 * Prepares the ViewHolder to be removed/recycled, and inserts it into the RecycledViewPool. 5771 * 5772 * Pass false to dispatchRecycled for views that have not been bound. 5773 * 5774 * @param holder Holder to be added to the pool. 5775 * @param dispatchRecycled True to dispatch View recycled callbacks. 5776 */ 5777 void addViewHolderToRecycledViewPool(ViewHolder holder, boolean dispatchRecycled) { 5778 clearNestedRecyclerViewIfNotNested(holder); 5779 ViewCompat.setAccessibilityDelegate(holder.itemView, null); 5780 if (dispatchRecycled) { 5781 dispatchViewRecycled(holder); 5782 } 5783 holder.mOwnerRecyclerView = null; 5784 getRecycledViewPool().putRecycledView(holder); 5785 } 5786 5787 /** 5788 * Used as a fast path for unscrapping and recycling a view during a bulk operation. 5789 * The caller must call {@link #clearScrap()} when it's done to update the recycler's 5790 * internal bookkeeping. 5791 */ 5792 void quickRecycleScrapView(View view) { 5793 final ViewHolder holder = getChildViewHolderInt(view); 5794 holder.mScrapContainer = null; 5795 holder.mInChangeScrap = false; 5796 holder.clearReturnedFromScrapFlag(); 5797 recycleViewHolderInternal(holder); 5798 } 5799 5800 /** 5801 * Mark an attached view as scrap. 5802 * 5803 * <p>"Scrap" views are still attached to their parent RecyclerView but are eligible 5804 * for rebinding and reuse. Requests for a view for a given position may return a 5805 * reused or rebound scrap view instance.</p> 5806 * 5807 * @param view View to scrap 5808 */ 5809 void scrapView(View view) { 5810 final ViewHolder holder = getChildViewHolderInt(view); 5811 if (holder.hasAnyOfTheFlags(ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_INVALID) 5812 || !holder.isUpdated() || canReuseUpdatedViewHolder(holder)) { 5813 if (holder.isInvalid() && !holder.isRemoved() && !mAdapter.hasStableIds()) { 5814 throw new IllegalArgumentException("Called scrap view with an invalid view." 5815 + " Invalid views cannot be reused from scrap, they should rebound from" 5816 + " recycler pool."); 5817 } 5818 holder.setScrapContainer(this, false); 5819 mAttachedScrap.add(holder); 5820 } else { 5821 if (mChangedScrap == null) { 5822 mChangedScrap = new ArrayList<ViewHolder>(); 5823 } 5824 holder.setScrapContainer(this, true); 5825 mChangedScrap.add(holder); 5826 } 5827 } 5828 5829 /** 5830 * Remove a previously scrapped view from the pool of eligible scrap. 5831 * 5832 * <p>This view will no longer be eligible for reuse until re-scrapped or 5833 * until it is explicitly removed and recycled.</p> 5834 */ 5835 void unscrapView(ViewHolder holder) { 5836 if (holder.mInChangeScrap) { 5837 mChangedScrap.remove(holder); 5838 } else { 5839 mAttachedScrap.remove(holder); 5840 } 5841 holder.mScrapContainer = null; 5842 holder.mInChangeScrap = false; 5843 holder.clearReturnedFromScrapFlag(); 5844 } 5845 5846 int getScrapCount() { 5847 return mAttachedScrap.size(); 5848 } 5849 5850 View getScrapViewAt(int index) { 5851 return mAttachedScrap.get(index).itemView; 5852 } 5853 5854 void clearScrap() { 5855 mAttachedScrap.clear(); 5856 if (mChangedScrap != null) { 5857 mChangedScrap.clear(); 5858 } 5859 } 5860 5861 ViewHolder getChangedScrapViewForPosition(int position) { 5862 // If pre-layout, check the changed scrap for an exact match. 5863 final int changedScrapSize; 5864 if (mChangedScrap == null || (changedScrapSize = mChangedScrap.size()) == 0) { 5865 return null; 5866 } 5867 // find by position 5868 for (int i = 0; i < changedScrapSize; i++) { 5869 final ViewHolder holder = mChangedScrap.get(i); 5870 if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position) { 5871 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 5872 return holder; 5873 } 5874 } 5875 // find by id 5876 if (mAdapter.hasStableIds()) { 5877 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 5878 if (offsetPosition > 0 && offsetPosition < mAdapter.getItemCount()) { 5879 final long id = mAdapter.getItemId(offsetPosition); 5880 for (int i = 0; i < changedScrapSize; i++) { 5881 final ViewHolder holder = mChangedScrap.get(i); 5882 if (!holder.wasReturnedFromScrap() && holder.getItemId() == id) { 5883 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 5884 return holder; 5885 } 5886 } 5887 } 5888 } 5889 return null; 5890 } 5891 5892 /** 5893 * Returns a view for the position either from attach scrap, hidden children, or cache. 5894 * 5895 * @param position Item position 5896 * @param dryRun Does a dry run, finds the ViewHolder but does not remove 5897 * @return a ViewHolder that can be re-used for this position. 5898 */ 5899 ViewHolder getScrapOrHiddenOrCachedHolderForPosition(int position, boolean dryRun) { 5900 final int scrapCount = mAttachedScrap.size(); 5901 5902 // Try first for an exact, non-invalid match from scrap. 5903 for (int i = 0; i < scrapCount; i++) { 5904 final ViewHolder holder = mAttachedScrap.get(i); 5905 if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position 5906 && !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) { 5907 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 5908 return holder; 5909 } 5910 } 5911 5912 if (!dryRun) { 5913 View view = mChildHelper.findHiddenNonRemovedView(position); 5914 if (view != null) { 5915 // This View is good to be used. We just need to unhide, detach and move to the 5916 // scrap list. 5917 final ViewHolder vh = getChildViewHolderInt(view); 5918 mChildHelper.unhide(view); 5919 int layoutIndex = mChildHelper.indexOfChild(view); 5920 if (layoutIndex == RecyclerView.NO_POSITION) { 5921 throw new IllegalStateException("layout index should not be -1 after " 5922 + "unhiding a view:" + vh); 5923 } 5924 mChildHelper.detachViewFromParent(layoutIndex); 5925 scrapView(view); 5926 vh.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP 5927 | ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST); 5928 return vh; 5929 } 5930 } 5931 5932 // Search in our first-level recycled view cache. 5933 final int cacheSize = mCachedViews.size(); 5934 for (int i = 0; i < cacheSize; i++) { 5935 final ViewHolder holder = mCachedViews.get(i); 5936 // invalid view holders may be in cache if adapter has stable ids as they can be 5937 // retrieved via getScrapOrCachedViewForId 5938 if (!holder.isInvalid() && holder.getLayoutPosition() == position) { 5939 if (!dryRun) { 5940 mCachedViews.remove(i); 5941 } 5942 if (DEBUG) { 5943 Log.d(TAG, "getScrapOrHiddenOrCachedHolderForPosition(" + position 5944 + ") found match in cache: " + holder); 5945 } 5946 return holder; 5947 } 5948 } 5949 return null; 5950 } 5951 5952 ViewHolder getScrapOrCachedViewForId(long id, int type, boolean dryRun) { 5953 // Look in our attached views first 5954 final int count = mAttachedScrap.size(); 5955 for (int i = count - 1; i >= 0; i--) { 5956 final ViewHolder holder = mAttachedScrap.get(i); 5957 if (holder.getItemId() == id && !holder.wasReturnedFromScrap()) { 5958 if (type == holder.getItemViewType()) { 5959 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 5960 if (holder.isRemoved()) { 5961 // this might be valid in two cases: 5962 // > item is removed but we are in pre-layout pass 5963 // >> do nothing. return as is. make sure we don't rebind 5964 // > item is removed then added to another position and we are in 5965 // post layout. 5966 // >> remove removed and invalid flags, add update flag to rebind 5967 // because item was invisible to us and we don't know what happened in 5968 // between. 5969 if (!mState.isPreLayout()) { 5970 holder.setFlags(ViewHolder.FLAG_UPDATE, ViewHolder.FLAG_UPDATE | 5971 ViewHolder.FLAG_INVALID | ViewHolder.FLAG_REMOVED); 5972 } 5973 } 5974 return holder; 5975 } else if (!dryRun) { 5976 // if we are running animations, it is actually better to keep it in scrap 5977 // but this would force layout manager to lay it out which would be bad. 5978 // Recycle this scrap. Type mismatch. 5979 mAttachedScrap.remove(i); 5980 removeDetachedView(holder.itemView, false); 5981 quickRecycleScrapView(holder.itemView); 5982 } 5983 } 5984 } 5985 5986 // Search the first-level cache 5987 final int cacheSize = mCachedViews.size(); 5988 for (int i = cacheSize - 1; i >= 0; i--) { 5989 final ViewHolder holder = mCachedViews.get(i); 5990 if (holder.getItemId() == id) { 5991 if (type == holder.getItemViewType()) { 5992 if (!dryRun) { 5993 mCachedViews.remove(i); 5994 } 5995 return holder; 5996 } else if (!dryRun) { 5997 recycleCachedViewAt(i); 5998 return null; 5999 } 6000 } 6001 } 6002 return null; 6003 } 6004 6005 void dispatchViewRecycled(ViewHolder holder) { 6006 if (mRecyclerListener != null) { 6007 mRecyclerListener.onViewRecycled(holder); 6008 } 6009 if (mAdapter != null) { 6010 mAdapter.onViewRecycled(holder); 6011 } 6012 if (mState != null) { 6013 mViewInfoStore.removeViewHolder(holder); 6014 } 6015 if (DEBUG) Log.d(TAG, "dispatchViewRecycled: " + holder); 6016 } 6017 6018 void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter, 6019 boolean compatibleWithPrevious) { 6020 clear(); 6021 getRecycledViewPool().onAdapterChanged(oldAdapter, newAdapter, compatibleWithPrevious); 6022 } 6023 6024 void offsetPositionRecordsForMove(int from, int to) { 6025 final int start, end, inBetweenOffset; 6026 if (from < to) { 6027 start = from; 6028 end = to; 6029 inBetweenOffset = -1; 6030 } else { 6031 start = to; 6032 end = from; 6033 inBetweenOffset = 1; 6034 } 6035 final int cachedCount = mCachedViews.size(); 6036 for (int i = 0; i < cachedCount; i++) { 6037 final ViewHolder holder = mCachedViews.get(i); 6038 if (holder == null || holder.mPosition < start || holder.mPosition > end) { 6039 continue; 6040 } 6041 if (holder.mPosition == from) { 6042 holder.offsetPosition(to - from, false); 6043 } else { 6044 holder.offsetPosition(inBetweenOffset, false); 6045 } 6046 if (DEBUG) { 6047 Log.d(TAG, "offsetPositionRecordsForMove cached child " + i + " holder " + 6048 holder); 6049 } 6050 } 6051 } 6052 6053 void offsetPositionRecordsForInsert(int insertedAt, int count) { 6054 final int cachedCount = mCachedViews.size(); 6055 for (int i = 0; i < cachedCount; i++) { 6056 final ViewHolder holder = mCachedViews.get(i); 6057 if (holder != null && holder.mPosition >= insertedAt) { 6058 if (DEBUG) { 6059 Log.d(TAG, "offsetPositionRecordsForInsert cached " + i + " holder " + 6060 holder + " now at position " + (holder.mPosition + count)); 6061 } 6062 holder.offsetPosition(count, true); 6063 } 6064 } 6065 } 6066 6067 /** 6068 * @param removedFrom Remove start index 6069 * @param count Remove count 6070 * @param applyToPreLayout If true, changes will affect ViewHolder's pre-layout position, if 6071 * false, they'll be applied before the second layout pass 6072 */ 6073 void offsetPositionRecordsForRemove(int removedFrom, int count, boolean applyToPreLayout) { 6074 final int removedEnd = removedFrom + count; 6075 final int cachedCount = mCachedViews.size(); 6076 for (int i = cachedCount - 1; i >= 0; i--) { 6077 final ViewHolder holder = mCachedViews.get(i); 6078 if (holder != null) { 6079 if (holder.mPosition >= removedEnd) { 6080 if (DEBUG) { 6081 Log.d(TAG, "offsetPositionRecordsForRemove cached " + i + 6082 " holder " + holder + " now at position " + 6083 (holder.mPosition - count)); 6084 } 6085 holder.offsetPosition(-count, applyToPreLayout); 6086 } else if (holder.mPosition >= removedFrom) { 6087 // Item for this view was removed. Dump it from the cache. 6088 holder.addFlags(ViewHolder.FLAG_REMOVED); 6089 recycleCachedViewAt(i); 6090 } 6091 } 6092 } 6093 } 6094 6095 void setViewCacheExtension(ViewCacheExtension extension) { 6096 mViewCacheExtension = extension; 6097 } 6098 6099 void setRecycledViewPool(RecycledViewPool pool) { 6100 if (mRecyclerPool != null) { 6101 mRecyclerPool.detach(); 6102 } 6103 mRecyclerPool = pool; 6104 if (pool != null) { 6105 mRecyclerPool.attach(getAdapter()); 6106 } 6107 } 6108 6109 RecycledViewPool getRecycledViewPool() { 6110 if (mRecyclerPool == null) { 6111 mRecyclerPool = new RecycledViewPool(); 6112 } 6113 return mRecyclerPool; 6114 } 6115 6116 void viewRangeUpdate(int positionStart, int itemCount) { 6117 final int positionEnd = positionStart + itemCount; 6118 final int cachedCount = mCachedViews.size(); 6119 for (int i = cachedCount - 1; i >= 0; i--) { 6120 final ViewHolder holder = mCachedViews.get(i); 6121 if (holder == null) { 6122 continue; 6123 } 6124 6125 final int pos = holder.getLayoutPosition(); 6126 if (pos >= positionStart && pos < positionEnd) { 6127 holder.addFlags(ViewHolder.FLAG_UPDATE); 6128 recycleCachedViewAt(i); 6129 // cached views should not be flagged as changed because this will cause them 6130 // to animate when they are returned from cache. 6131 } 6132 } 6133 } 6134 6135 void setAdapterPositionsAsUnknown() { 6136 final int cachedCount = mCachedViews.size(); 6137 for (int i = 0; i < cachedCount; i++) { 6138 final ViewHolder holder = mCachedViews.get(i); 6139 if (holder != null) { 6140 holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN); 6141 } 6142 } 6143 } 6144 6145 void markKnownViewsInvalid() { 6146 if (mAdapter != null && mAdapter.hasStableIds()) { 6147 final int cachedCount = mCachedViews.size(); 6148 for (int i = 0; i < cachedCount; i++) { 6149 final ViewHolder holder = mCachedViews.get(i); 6150 if (holder != null) { 6151 holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID); 6152 holder.addChangePayload(null); 6153 } 6154 } 6155 } else { 6156 // we cannot re-use cached views in this case. Recycle them all 6157 recycleAndClearCachedViews(); 6158 } 6159 } 6160 6161 void clearOldPositions() { 6162 final int cachedCount = mCachedViews.size(); 6163 for (int i = 0; i < cachedCount; i++) { 6164 final ViewHolder holder = mCachedViews.get(i); 6165 holder.clearOldPosition(); 6166 } 6167 final int scrapCount = mAttachedScrap.size(); 6168 for (int i = 0; i < scrapCount; i++) { 6169 mAttachedScrap.get(i).clearOldPosition(); 6170 } 6171 if (mChangedScrap != null) { 6172 final int changedScrapCount = mChangedScrap.size(); 6173 for (int i = 0; i < changedScrapCount; i++) { 6174 mChangedScrap.get(i).clearOldPosition(); 6175 } 6176 } 6177 } 6178 6179 void markItemDecorInsetsDirty() { 6180 final int cachedCount = mCachedViews.size(); 6181 for (int i = 0; i < cachedCount; i++) { 6182 final ViewHolder holder = mCachedViews.get(i); 6183 LayoutParams layoutParams = (LayoutParams) holder.itemView.getLayoutParams(); 6184 if (layoutParams != null) { 6185 layoutParams.mInsetsDirty = true; 6186 } 6187 } 6188 } 6189 } 6190 6191 /** 6192 * ViewCacheExtension is a helper class to provide an additional layer of view caching that can 6193 * be controlled by the developer. 6194 * <p> 6195 * When {@link Recycler#getViewForPosition(int)} is called, Recycler checks attached scrap and 6196 * first level cache to find a matching View. If it cannot find a suitable View, Recycler will 6197 * call the {@link #getViewForPositionAndType(Recycler, int, int)} before checking 6198 * {@link RecycledViewPool}. 6199 * <p> 6200 * Note that, Recycler never sends Views to this method to be cached. It is developers 6201 * responsibility to decide whether they want to keep their Views in this custom cache or let 6202 * the default recycling policy handle it. 6203 */ 6204 public abstract static class ViewCacheExtension { 6205 6206 /** 6207 * Returns a View that can be binded to the given Adapter position. 6208 * <p> 6209 * This method should <b>not</b> create a new View. Instead, it is expected to return 6210 * an already created View that can be re-used for the given type and position. 6211 * If the View is marked as ignored, it should first call 6212 * {@link LayoutManager#stopIgnoringView(View)} before returning the View. 6213 * <p> 6214 * RecyclerView will re-bind the returned View to the position if necessary. 6215 * 6216 * @param recycler The Recycler that can be used to bind the View 6217 * @param position The adapter position 6218 * @param type The type of the View, defined by adapter 6219 * @return A View that is bound to the given position or NULL if there is no View to re-use 6220 * @see LayoutManager#ignoreView(View) 6221 */ 6222 abstract public View getViewForPositionAndType(Recycler recycler, int position, int type); 6223 } 6224 6225 /** 6226 * Base class for an Adapter 6227 * 6228 * <p>Adapters provide a binding from an app-specific data set to views that are displayed 6229 * within a {@link RecyclerView}.</p> 6230 */ 6231 public static abstract class Adapter<VH extends ViewHolder> { 6232 private final AdapterDataObservable mObservable = new AdapterDataObservable(); 6233 private boolean mHasStableIds = false; 6234 6235 /** 6236 * Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent 6237 * an item. 6238 * <p> 6239 * This new ViewHolder should be constructed with a new View that can represent the items 6240 * of the given type. You can either create a new View manually or inflate it from an XML 6241 * layout file. 6242 * <p> 6243 * The new ViewHolder will be used to display items of the adapter using 6244 * {@link #onBindViewHolder(ViewHolder, int, List)}. Since it will be re-used to display 6245 * different items in the data set, it is a good idea to cache references to sub views of 6246 * the View to avoid unnecessary {@link View#findViewById(int)} calls. 6247 * 6248 * @param parent The ViewGroup into which the new View will be added after it is bound to 6249 * an adapter position. 6250 * @param viewType The view type of the new View. 6251 * 6252 * @return A new ViewHolder that holds a View of the given view type. 6253 * @see #getItemViewType(int) 6254 * @see #onBindViewHolder(ViewHolder, int) 6255 */ 6256 public abstract VH onCreateViewHolder(ViewGroup parent, int viewType); 6257 6258 /** 6259 * Called by RecyclerView to display the data at the specified position. This method should 6260 * update the contents of the {@link ViewHolder#itemView} to reflect the item at the given 6261 * position. 6262 * <p> 6263 * Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method 6264 * again if the position of the item changes in the data set unless the item itself is 6265 * invalidated or the new position cannot be determined. For this reason, you should only 6266 * use the <code>position</code> parameter while acquiring the related data item inside 6267 * this method and should not keep a copy of it. If you need the position of an item later 6268 * on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will 6269 * have the updated adapter position. 6270 * 6271 * Override {@link #onBindViewHolder(ViewHolder, int, List)} instead if Adapter can 6272 * handle efficient partial bind. 6273 * 6274 * @param holder The ViewHolder which should be updated to represent the contents of the 6275 * item at the given position in the data set. 6276 * @param position The position of the item within the adapter's data set. 6277 */ 6278 public abstract void onBindViewHolder(VH holder, int position); 6279 6280 /** 6281 * Called by RecyclerView to display the data at the specified position. This method 6282 * should update the contents of the {@link ViewHolder#itemView} to reflect the item at 6283 * the given position. 6284 * <p> 6285 * Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method 6286 * again if the position of the item changes in the data set unless the item itself is 6287 * invalidated or the new position cannot be determined. For this reason, you should only 6288 * use the <code>position</code> parameter while acquiring the related data item inside 6289 * this method and should not keep a copy of it. If you need the position of an item later 6290 * on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will 6291 * have the updated adapter position. 6292 * <p> 6293 * Partial bind vs full bind: 6294 * <p> 6295 * The payloads parameter is a merge list from {@link #notifyItemChanged(int, Object)} or 6296 * {@link #notifyItemRangeChanged(int, int, Object)}. If the payloads list is not empty, 6297 * the ViewHolder is currently bound to old data and Adapter may run an efficient partial 6298 * update using the payload info. If the payload is empty, Adapter must run a full bind. 6299 * Adapter should not assume that the payload passed in notify methods will be received by 6300 * onBindViewHolder(). For example when the view is not attached to the screen, the 6301 * payload in notifyItemChange() will be simply dropped. 6302 * 6303 * @param holder The ViewHolder which should be updated to represent the contents of the 6304 * item at the given position in the data set. 6305 * @param position The position of the item within the adapter's data set. 6306 * @param payloads A non-null list of merged payloads. Can be empty list if requires full 6307 * update. 6308 */ 6309 public void onBindViewHolder(VH holder, int position, List<Object> payloads) { 6310 onBindViewHolder(holder, position); 6311 } 6312 6313 /** 6314 * This method calls {@link #onCreateViewHolder(ViewGroup, int)} to create a new 6315 * {@link ViewHolder} and initializes some private fields to be used by RecyclerView. 6316 * 6317 * @see #onCreateViewHolder(ViewGroup, int) 6318 */ 6319 public final VH createViewHolder(ViewGroup parent, int viewType) { 6320 TraceCompat.beginSection(TRACE_CREATE_VIEW_TAG); 6321 final VH holder = onCreateViewHolder(parent, viewType); 6322 holder.mItemViewType = viewType; 6323 TraceCompat.endSection(); 6324 return holder; 6325 } 6326 6327 /** 6328 * This method internally calls {@link #onBindViewHolder(ViewHolder, int)} to update the 6329 * {@link ViewHolder} contents with the item at the given position and also sets up some 6330 * private fields to be used by RecyclerView. 6331 * 6332 * @see #onBindViewHolder(ViewHolder, int) 6333 */ 6334 public final void bindViewHolder(VH holder, int position) { 6335 holder.mPosition = position; 6336 if (hasStableIds()) { 6337 holder.mItemId = getItemId(position); 6338 } 6339 holder.setFlags(ViewHolder.FLAG_BOUND, 6340 ViewHolder.FLAG_BOUND | ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID 6341 | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN); 6342 TraceCompat.beginSection(TRACE_BIND_VIEW_TAG); 6343 onBindViewHolder(holder, position, holder.getUnmodifiedPayloads()); 6344 holder.clearPayload(); 6345 final ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams(); 6346 if (layoutParams instanceof RecyclerView.LayoutParams) { 6347 ((LayoutParams) layoutParams).mInsetsDirty = true; 6348 } 6349 TraceCompat.endSection(); 6350 } 6351 6352 /** 6353 * Return the view type of the item at <code>position</code> for the purposes 6354 * of view recycling. 6355 * 6356 * <p>The default implementation of this method returns 0, making the assumption of 6357 * a single view type for the adapter. Unlike ListView adapters, types need not 6358 * be contiguous. Consider using id resources to uniquely identify item view types. 6359 * 6360 * @param position position to query 6361 * @return integer value identifying the type of the view needed to represent the item at 6362 * <code>position</code>. Type codes need not be contiguous. 6363 */ 6364 public int getItemViewType(int position) { 6365 return 0; 6366 } 6367 6368 /** 6369 * Indicates whether each item in the data set can be represented with a unique identifier 6370 * of type {@link java.lang.Long}. 6371 * 6372 * @param hasStableIds Whether items in data set have unique identifiers or not. 6373 * @see #hasStableIds() 6374 * @see #getItemId(int) 6375 */ 6376 public void setHasStableIds(boolean hasStableIds) { 6377 if (hasObservers()) { 6378 throw new IllegalStateException("Cannot change whether this adapter has " + 6379 "stable IDs while the adapter has registered observers."); 6380 } 6381 mHasStableIds = hasStableIds; 6382 } 6383 6384 /** 6385 * Return the stable ID for the item at <code>position</code>. If {@link #hasStableIds()} 6386 * would return false this method should return {@link #NO_ID}. The default implementation 6387 * of this method returns {@link #NO_ID}. 6388 * 6389 * @param position Adapter position to query 6390 * @return the stable ID of the item at position 6391 */ 6392 public long getItemId(int position) { 6393 return NO_ID; 6394 } 6395 6396 /** 6397 * Returns the total number of items in the data set held by the adapter. 6398 * 6399 * @return The total number of items in this adapter. 6400 */ 6401 public abstract int getItemCount(); 6402 6403 /** 6404 * Returns true if this adapter publishes a unique <code>long</code> value that can 6405 * act as a key for the item at a given position in the data set. If that item is relocated 6406 * in the data set, the ID returned for that item should be the same. 6407 * 6408 * @return true if this adapter's items have stable IDs 6409 */ 6410 public final boolean hasStableIds() { 6411 return mHasStableIds; 6412 } 6413 6414 /** 6415 * Called when a view created by this adapter has been recycled. 6416 * 6417 * <p>A view is recycled when a {@link LayoutManager} decides that it no longer 6418 * needs to be attached to its parent {@link RecyclerView}. This can be because it has 6419 * fallen out of visibility or a set of cached views represented by views still 6420 * attached to the parent RecyclerView. If an item view has large or expensive data 6421 * bound to it such as large bitmaps, this may be a good place to release those 6422 * resources.</p> 6423 * <p> 6424 * RecyclerView calls this method right before clearing ViewHolder's internal data and 6425 * sending it to RecycledViewPool. This way, if ViewHolder was holding valid information 6426 * before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get 6427 * its adapter position. 6428 * 6429 * @param holder The ViewHolder for the view being recycled 6430 */ 6431 public void onViewRecycled(VH holder) { 6432 } 6433 6434 /** 6435 * Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled 6436 * due to its transient state. Upon receiving this callback, Adapter can clear the 6437 * animation(s) that effect the View's transient state and return <code>true</code> so that 6438 * the View can be recycled. Keep in mind that the View in question is already removed from 6439 * the RecyclerView. 6440 * <p> 6441 * In some cases, it is acceptable to recycle a View although it has transient state. Most 6442 * of the time, this is a case where the transient state will be cleared in 6443 * {@link #onBindViewHolder(ViewHolder, int)} call when View is rebound to a new position. 6444 * For this reason, RecyclerView leaves the decision to the Adapter and uses the return 6445 * value of this method to decide whether the View should be recycled or not. 6446 * <p> 6447 * Note that when all animations are created by {@link RecyclerView.ItemAnimator}, you 6448 * should never receive this callback because RecyclerView keeps those Views as children 6449 * until their animations are complete. This callback is useful when children of the item 6450 * views create animations which may not be easy to implement using an {@link ItemAnimator}. 6451 * <p> 6452 * You should <em>never</em> fix this issue by calling 6453 * <code>holder.itemView.setHasTransientState(false);</code> unless you've previously called 6454 * <code>holder.itemView.setHasTransientState(true);</code>. Each 6455 * <code>View.setHasTransientState(true)</code> call must be matched by a 6456 * <code>View.setHasTransientState(false)</code> call, otherwise, the state of the View 6457 * may become inconsistent. You should always prefer to end or cancel animations that are 6458 * triggering the transient state instead of handling it manually. 6459 * 6460 * @param holder The ViewHolder containing the View that could not be recycled due to its 6461 * transient state. 6462 * @return True if the View should be recycled, false otherwise. Note that if this method 6463 * returns <code>true</code>, RecyclerView <em>will ignore</em> the transient state of 6464 * the View and recycle it regardless. If this method returns <code>false</code>, 6465 * RecyclerView will check the View's transient state again before giving a final decision. 6466 * Default implementation returns false. 6467 */ 6468 public boolean onFailedToRecycleView(VH holder) { 6469 return false; 6470 } 6471 6472 /** 6473 * Called when a view created by this adapter has been attached to a window. 6474 * 6475 * <p>This can be used as a reasonable signal that the view is about to be seen 6476 * by the user. If the adapter previously freed any resources in 6477 * {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow} 6478 * those resources should be restored here.</p> 6479 * 6480 * @param holder Holder of the view being attached 6481 */ 6482 public void onViewAttachedToWindow(VH holder) { 6483 } 6484 6485 /** 6486 * Called when a view created by this adapter has been detached from its window. 6487 * 6488 * <p>Becoming detached from the window is not necessarily a permanent condition; 6489 * the consumer of an Adapter's views may choose to cache views offscreen while they 6490 * are not visible, attaching and detaching them as appropriate.</p> 6491 * 6492 * @param holder Holder of the view being detached 6493 */ 6494 public void onViewDetachedFromWindow(VH holder) { 6495 } 6496 6497 /** 6498 * Returns true if one or more observers are attached to this adapter. 6499 * 6500 * @return true if this adapter has observers 6501 */ 6502 public final boolean hasObservers() { 6503 return mObservable.hasObservers(); 6504 } 6505 6506 /** 6507 * Register a new observer to listen for data changes. 6508 * 6509 * <p>The adapter may publish a variety of events describing specific changes. 6510 * Not all adapters may support all change types and some may fall back to a generic 6511 * {@link android.support.v7.widget.RecyclerView.AdapterDataObserver#onChanged() 6512 * "something changed"} event if more specific data is not available.</p> 6513 * 6514 * <p>Components registering observers with an adapter are responsible for 6515 * {@link #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver) 6516 * unregistering} those observers when finished.</p> 6517 * 6518 * @param observer Observer to register 6519 * 6520 * @see #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver) 6521 */ 6522 public void registerAdapterDataObserver(AdapterDataObserver observer) { 6523 mObservable.registerObserver(observer); 6524 } 6525 6526 /** 6527 * Unregister an observer currently listening for data changes. 6528 * 6529 * <p>The unregistered observer will no longer receive events about changes 6530 * to the adapter.</p> 6531 * 6532 * @param observer Observer to unregister 6533 * 6534 * @see #registerAdapterDataObserver(RecyclerView.AdapterDataObserver) 6535 */ 6536 public void unregisterAdapterDataObserver(AdapterDataObserver observer) { 6537 mObservable.unregisterObserver(observer); 6538 } 6539 6540 /** 6541 * Called by RecyclerView when it starts observing this Adapter. 6542 * <p> 6543 * Keep in mind that same adapter may be observed by multiple RecyclerViews. 6544 * 6545 * @param recyclerView The RecyclerView instance which started observing this adapter. 6546 * @see #onDetachedFromRecyclerView(RecyclerView) 6547 */ 6548 public void onAttachedToRecyclerView(RecyclerView recyclerView) { 6549 } 6550 6551 /** 6552 * Called by RecyclerView when it stops observing this Adapter. 6553 * 6554 * @param recyclerView The RecyclerView instance which stopped observing this adapter. 6555 * @see #onAttachedToRecyclerView(RecyclerView) 6556 */ 6557 public void onDetachedFromRecyclerView(RecyclerView recyclerView) { 6558 } 6559 6560 /** 6561 * Notify any registered observers that the data set has changed. 6562 * 6563 * <p>There are two different classes of data change events, item changes and structural 6564 * changes. Item changes are when a single item has its data updated but no positional 6565 * changes have occurred. Structural changes are when items are inserted, removed or moved 6566 * within the data set.</p> 6567 * 6568 * <p>This event does not specify what about the data set has changed, forcing 6569 * any observers to assume that all existing items and structure may no longer be valid. 6570 * LayoutManagers will be forced to fully rebind and relayout all visible views.</p> 6571 * 6572 * <p><code>RecyclerView</code> will attempt to synthesize visible structural change events 6573 * for adapters that report that they have {@link #hasStableIds() stable IDs} when 6574 * this method is used. This can help for the purposes of animation and visual 6575 * object persistence but individual item views will still need to be rebound 6576 * and relaid out.</p> 6577 * 6578 * <p>If you are writing an adapter it will always be more efficient to use the more 6579 * specific change events if you can. Rely on <code>notifyDataSetChanged()</code> 6580 * as a last resort.</p> 6581 * 6582 * @see #notifyItemChanged(int) 6583 * @see #notifyItemInserted(int) 6584 * @see #notifyItemRemoved(int) 6585 * @see #notifyItemRangeChanged(int, int) 6586 * @see #notifyItemRangeInserted(int, int) 6587 * @see #notifyItemRangeRemoved(int, int) 6588 */ 6589 public final void notifyDataSetChanged() { 6590 mObservable.notifyChanged(); 6591 } 6592 6593 /** 6594 * Notify any registered observers that the item at <code>position</code> has changed. 6595 * Equivalent to calling <code>notifyItemChanged(position, null);</code>. 6596 * 6597 * <p>This is an item change event, not a structural change event. It indicates that any 6598 * reflection of the data at <code>position</code> is out of date and should be updated. 6599 * The item at <code>position</code> retains the same identity.</p> 6600 * 6601 * @param position Position of the item that has changed 6602 * 6603 * @see #notifyItemRangeChanged(int, int) 6604 */ 6605 public final void notifyItemChanged(int position) { 6606 mObservable.notifyItemRangeChanged(position, 1); 6607 } 6608 6609 /** 6610 * Notify any registered observers that the item at <code>position</code> has changed with an 6611 * optional payload object. 6612 * 6613 * <p>This is an item change event, not a structural change event. It indicates that any 6614 * reflection of the data at <code>position</code> is out of date and should be updated. 6615 * The item at <code>position</code> retains the same identity. 6616 * </p> 6617 * 6618 * <p> 6619 * Client can optionally pass a payload for partial change. These payloads will be merged 6620 * and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the 6621 * item is already represented by a ViewHolder and it will be rebound to the same 6622 * ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing 6623 * payloads on that item and prevent future payload until 6624 * {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume 6625 * that the payload will always be passed to onBindViewHolder(), e.g. when the view is not 6626 * attached, the payload will be simply dropped. 6627 * 6628 * @param position Position of the item that has changed 6629 * @param payload Optional parameter, use null to identify a "full" update 6630 * 6631 * @see #notifyItemRangeChanged(int, int) 6632 */ 6633 public final void notifyItemChanged(int position, Object payload) { 6634 mObservable.notifyItemRangeChanged(position, 1, payload); 6635 } 6636 6637 /** 6638 * Notify any registered observers that the <code>itemCount</code> items starting at 6639 * position <code>positionStart</code> have changed. 6640 * Equivalent to calling <code>notifyItemRangeChanged(position, itemCount, null);</code>. 6641 * 6642 * <p>This is an item change event, not a structural change event. It indicates that 6643 * any reflection of the data in the given position range is out of date and should 6644 * be updated. The items in the given range retain the same identity.</p> 6645 * 6646 * @param positionStart Position of the first item that has changed 6647 * @param itemCount Number of items that have changed 6648 * 6649 * @see #notifyItemChanged(int) 6650 */ 6651 public final void notifyItemRangeChanged(int positionStart, int itemCount) { 6652 mObservable.notifyItemRangeChanged(positionStart, itemCount); 6653 } 6654 6655 /** 6656 * Notify any registered observers that the <code>itemCount</code> items starting at 6657 * position <code>positionStart</code> have changed. An optional payload can be 6658 * passed to each changed item. 6659 * 6660 * <p>This is an item change event, not a structural change event. It indicates that any 6661 * reflection of the data in the given position range is out of date and should be updated. 6662 * The items in the given range retain the same identity. 6663 * </p> 6664 * 6665 * <p> 6666 * Client can optionally pass a payload for partial change. These payloads will be merged 6667 * and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the 6668 * item is already represented by a ViewHolder and it will be rebound to the same 6669 * ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing 6670 * payloads on that item and prevent future payload until 6671 * {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume 6672 * that the payload will always be passed to onBindViewHolder(), e.g. when the view is not 6673 * attached, the payload will be simply dropped. 6674 * 6675 * @param positionStart Position of the first item that has changed 6676 * @param itemCount Number of items that have changed 6677 * @param payload Optional parameter, use null to identify a "full" update 6678 * 6679 * @see #notifyItemChanged(int) 6680 */ 6681 public final void notifyItemRangeChanged(int positionStart, int itemCount, Object payload) { 6682 mObservable.notifyItemRangeChanged(positionStart, itemCount, payload); 6683 } 6684 6685 /** 6686 * Notify any registered observers that the item reflected at <code>position</code> 6687 * has been newly inserted. The item previously at <code>position</code> is now at 6688 * position <code>position + 1</code>. 6689 * 6690 * <p>This is a structural change event. Representations of other existing items in the 6691 * data set are still considered up to date and will not be rebound, though their 6692 * positions may be altered.</p> 6693 * 6694 * @param position Position of the newly inserted item in the data set 6695 * 6696 * @see #notifyItemRangeInserted(int, int) 6697 */ 6698 public final void notifyItemInserted(int position) { 6699 mObservable.notifyItemRangeInserted(position, 1); 6700 } 6701 6702 /** 6703 * Notify any registered observers that the item reflected at <code>fromPosition</code> 6704 * has been moved to <code>toPosition</code>. 6705 * 6706 * <p>This is a structural change event. Representations of other existing items in the 6707 * data set are still considered up to date and will not be rebound, though their 6708 * positions may be altered.</p> 6709 * 6710 * @param fromPosition Previous position of the item. 6711 * @param toPosition New position of the item. 6712 */ 6713 public final void notifyItemMoved(int fromPosition, int toPosition) { 6714 mObservable.notifyItemMoved(fromPosition, toPosition); 6715 } 6716 6717 /** 6718 * Notify any registered observers that the currently reflected <code>itemCount</code> 6719 * items starting at <code>positionStart</code> have been newly inserted. The items 6720 * previously located at <code>positionStart</code> and beyond can now be found starting 6721 * at position <code>positionStart + itemCount</code>. 6722 * 6723 * <p>This is a structural change event. Representations of other existing items in the 6724 * data set are still considered up to date and will not be rebound, though their positions 6725 * may be altered.</p> 6726 * 6727 * @param positionStart Position of the first item that was inserted 6728 * @param itemCount Number of items inserted 6729 * 6730 * @see #notifyItemInserted(int) 6731 */ 6732 public final void notifyItemRangeInserted(int positionStart, int itemCount) { 6733 mObservable.notifyItemRangeInserted(positionStart, itemCount); 6734 } 6735 6736 /** 6737 * Notify any registered observers that the item previously located at <code>position</code> 6738 * has been removed from the data set. The items previously located at and after 6739 * <code>position</code> may now be found at <code>oldPosition - 1</code>. 6740 * 6741 * <p>This is a structural change event. Representations of other existing items in the 6742 * data set are still considered up to date and will not be rebound, though their positions 6743 * may be altered.</p> 6744 * 6745 * @param position Position of the item that has now been removed 6746 * 6747 * @see #notifyItemRangeRemoved(int, int) 6748 */ 6749 public final void notifyItemRemoved(int position) { 6750 mObservable.notifyItemRangeRemoved(position, 1); 6751 } 6752 6753 /** 6754 * Notify any registered observers that the <code>itemCount</code> items previously 6755 * located at <code>positionStart</code> have been removed from the data set. The items 6756 * previously located at and after <code>positionStart + itemCount</code> may now be found 6757 * at <code>oldPosition - itemCount</code>. 6758 * 6759 * <p>This is a structural change event. Representations of other existing items in the data 6760 * set are still considered up to date and will not be rebound, though their positions 6761 * may be altered.</p> 6762 * 6763 * @param positionStart Previous position of the first item that was removed 6764 * @param itemCount Number of items removed from the data set 6765 */ 6766 public final void notifyItemRangeRemoved(int positionStart, int itemCount) { 6767 mObservable.notifyItemRangeRemoved(positionStart, itemCount); 6768 } 6769 } 6770 6771 void dispatchChildDetached(View child) { 6772 final ViewHolder viewHolder = getChildViewHolderInt(child); 6773 onChildDetachedFromWindow(child); 6774 if (mAdapter != null && viewHolder != null) { 6775 mAdapter.onViewDetachedFromWindow(viewHolder); 6776 } 6777 if (mOnChildAttachStateListeners != null) { 6778 final int cnt = mOnChildAttachStateListeners.size(); 6779 for (int i = cnt - 1; i >= 0; i--) { 6780 mOnChildAttachStateListeners.get(i).onChildViewDetachedFromWindow(child); 6781 } 6782 } 6783 } 6784 6785 void dispatchChildAttached(View child) { 6786 final ViewHolder viewHolder = getChildViewHolderInt(child); 6787 onChildAttachedToWindow(child); 6788 if (mAdapter != null && viewHolder != null) { 6789 mAdapter.onViewAttachedToWindow(viewHolder); 6790 } 6791 if (mOnChildAttachStateListeners != null) { 6792 final int cnt = mOnChildAttachStateListeners.size(); 6793 for (int i = cnt - 1; i >= 0; i--) { 6794 mOnChildAttachStateListeners.get(i).onChildViewAttachedToWindow(child); 6795 } 6796 } 6797 } 6798 6799 /** 6800 * A <code>LayoutManager</code> is responsible for measuring and positioning item views 6801 * within a <code>RecyclerView</code> as well as determining the policy for when to recycle 6802 * item views that are no longer visible to the user. By changing the <code>LayoutManager</code> 6803 * a <code>RecyclerView</code> can be used to implement a standard vertically scrolling list, 6804 * a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock 6805 * layout managers are provided for general use. 6806 * <p/> 6807 * If the LayoutManager specifies a default constructor or one with the signature 6808 * ({@link Context}, {@link AttributeSet}, {@code int}, {@code int}), RecyclerView will 6809 * instantiate and set the LayoutManager when being inflated. Most used properties can 6810 * be then obtained from {@link #getProperties(Context, AttributeSet, int, int)}. In case 6811 * a LayoutManager specifies both constructors, the non-default constructor will take 6812 * precedence. 6813 * 6814 */ 6815 public static abstract class LayoutManager { 6816 ChildHelper mChildHelper; 6817 RecyclerView mRecyclerView; 6818 6819 @Nullable 6820 SmoothScroller mSmoothScroller; 6821 6822 boolean mRequestedSimpleAnimations = false; 6823 6824 boolean mIsAttachedToWindow = false; 6825 6826 boolean mAutoMeasure = false; 6827 6828 /** 6829 * LayoutManager has its own more strict measurement cache to avoid re-measuring a child 6830 * if the space that will be given to it is already larger than what it has measured before. 6831 */ 6832 private boolean mMeasurementCacheEnabled = true; 6833 6834 private boolean mItemPrefetchEnabled = true; 6835 6836 /** 6837 * Written by {@link GapWorker} when prefetches occur to track largest number of view ever 6838 * requested by a {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)} or 6839 * {@link #collectAdjacentPrefetchPositions(int, int, State, LayoutPrefetchRegistry)} call. 6840 * 6841 * If expanded by a {@link #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry)}, 6842 * will be reset upon layout to prevent initial prefetches (often large, since they're 6843 * proportional to expected child count) from expanding cache permanently. 6844 */ 6845 int mPrefetchMaxCountObserved; 6846 6847 /** 6848 * If true, mPrefetchMaxCountObserved is only valid until next layout, and should be reset. 6849 */ 6850 boolean mPrefetchMaxObservedInInitialPrefetch; 6851 6852 /** 6853 * These measure specs might be the measure specs that were passed into RecyclerView's 6854 * onMeasure method OR fake measure specs created by the RecyclerView. 6855 * For example, when a layout is run, RecyclerView always sets these specs to be 6856 * EXACTLY because a LayoutManager cannot resize RecyclerView during a layout pass. 6857 * <p> 6858 * Also, to be able to use the hint in unspecified measure specs, RecyclerView checks the 6859 * API level and sets the size to 0 pre-M to avoid any issue that might be caused by 6860 * corrupt values. Older platforms have no responsibility to provide a size if they set 6861 * mode to unspecified. 6862 */ 6863 private int mWidthMode, mHeightMode; 6864 private int mWidth, mHeight; 6865 6866 6867 /** 6868 * Interface for LayoutManagers to request items to be prefetched, based on position, with 6869 * specified distance from viewport, which indicates priority. 6870 * 6871 * @see LayoutManager#collectAdjacentPrefetchPositions(int, int, State, LayoutPrefetchRegistry) 6872 * @see LayoutManager#collectInitialPrefetchPositions(int, LayoutPrefetchRegistry) 6873 */ 6874 public interface LayoutPrefetchRegistry { 6875 /** 6876 * Requests an an item to be prefetched, based on position, with a specified distance, 6877 * indicating priority. 6878 * 6879 * @param layoutPosition Position of the item to prefetch. 6880 * @param pixelDistance Distance from the current viewport to the bounds of the item, 6881 * must be non-negative. 6882 */ 6883 void addPosition(int layoutPosition, int pixelDistance); 6884 } 6885 6886 void setRecyclerView(RecyclerView recyclerView) { 6887 if (recyclerView == null) { 6888 mRecyclerView = null; 6889 mChildHelper = null; 6890 mWidth = 0; 6891 mHeight = 0; 6892 } else { 6893 mRecyclerView = recyclerView; 6894 mChildHelper = recyclerView.mChildHelper; 6895 mWidth = recyclerView.getWidth(); 6896 mHeight = recyclerView.getHeight(); 6897 } 6898 mWidthMode = MeasureSpec.EXACTLY; 6899 mHeightMode = MeasureSpec.EXACTLY; 6900 } 6901 6902 void setMeasureSpecs(int wSpec, int hSpec) { 6903 mWidth = MeasureSpec.getSize(wSpec); 6904 mWidthMode = MeasureSpec.getMode(wSpec); 6905 if (mWidthMode == MeasureSpec.UNSPECIFIED && !ALLOW_SIZE_IN_UNSPECIFIED_SPEC) { 6906 mWidth = 0; 6907 } 6908 6909 mHeight = MeasureSpec.getSize(hSpec); 6910 mHeightMode = MeasureSpec.getMode(hSpec); 6911 if (mHeightMode == MeasureSpec.UNSPECIFIED && !ALLOW_SIZE_IN_UNSPECIFIED_SPEC) { 6912 mHeight = 0; 6913 } 6914 } 6915 6916 /** 6917 * Called after a layout is calculated during a measure pass when using auto-measure. 6918 * <p> 6919 * It simply traverses all children to calculate a bounding box then calls 6920 * {@link #setMeasuredDimension(Rect, int, int)}. LayoutManagers can override that method 6921 * if they need to handle the bounding box differently. 6922 * <p> 6923 * For example, GridLayoutManager override that method to ensure that even if a column is 6924 * empty, the GridLayoutManager still measures wide enough to include it. 6925 * 6926 * @param widthSpec The widthSpec that was passing into RecyclerView's onMeasure 6927 * @param heightSpec The heightSpec that was passing into RecyclerView's onMeasure 6928 */ 6929 void setMeasuredDimensionFromChildren(int widthSpec, int heightSpec) { 6930 final int count = getChildCount(); 6931 if (count == 0) { 6932 mRecyclerView.defaultOnMeasure(widthSpec, heightSpec); 6933 return; 6934 } 6935 int minX = Integer.MAX_VALUE; 6936 int minY = Integer.MAX_VALUE; 6937 int maxX = Integer.MIN_VALUE; 6938 int maxY = Integer.MIN_VALUE; 6939 6940 for (int i = 0; i < count; i++) { 6941 View child = getChildAt(i); 6942 final Rect bounds = mRecyclerView.mTempRect; 6943 getDecoratedBoundsWithMargins(child, bounds); 6944 if (bounds.left < minX) { 6945 minX = bounds.left; 6946 } 6947 if (bounds.right > maxX) { 6948 maxX = bounds.right; 6949 } 6950 if (bounds.top < minY) { 6951 minY = bounds.top; 6952 } 6953 if (bounds.bottom > maxY) { 6954 maxY = bounds.bottom; 6955 } 6956 } 6957 mRecyclerView.mTempRect.set(minX, minY, maxX, maxY); 6958 setMeasuredDimension(mRecyclerView.mTempRect, widthSpec, heightSpec); 6959 } 6960 6961 /** 6962 * Sets the measured dimensions from the given bounding box of the children and the 6963 * measurement specs that were passed into {@link RecyclerView#onMeasure(int, int)}. It is 6964 * called after the RecyclerView calls 6965 * {@link LayoutManager#onLayoutChildren(Recycler, State)} during a measurement pass. 6966 * <p> 6967 * This method should call {@link #setMeasuredDimension(int, int)}. 6968 * <p> 6969 * The default implementation adds the RecyclerView's padding to the given bounding box 6970 * then caps the value to be within the given measurement specs. 6971 * <p> 6972 * This method is only called if the LayoutManager opted into the auto measurement API. 6973 * 6974 * @param childrenBounds The bounding box of all children 6975 * @param wSpec The widthMeasureSpec that was passed into the RecyclerView. 6976 * @param hSpec The heightMeasureSpec that was passed into the RecyclerView. 6977 * 6978 * @see #setAutoMeasureEnabled(boolean) 6979 */ 6980 public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec) { 6981 int usedWidth = childrenBounds.width() + getPaddingLeft() + getPaddingRight(); 6982 int usedHeight = childrenBounds.height() + getPaddingTop() + getPaddingBottom(); 6983 int width = chooseSize(wSpec, usedWidth, getMinimumWidth()); 6984 int height = chooseSize(hSpec, usedHeight, getMinimumHeight()); 6985 setMeasuredDimension(width, height); 6986 } 6987 6988 /** 6989 * Calls {@code RecyclerView#requestLayout} on the underlying RecyclerView 6990 */ 6991 public void requestLayout() { 6992 if(mRecyclerView != null) { 6993 mRecyclerView.requestLayout(); 6994 } 6995 } 6996 6997 /** 6998 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 6999 * {@link IllegalStateException} if it <b>is not</b>. 7000 * 7001 * @param message The message for the exception. Can be null. 7002 * @see #assertNotInLayoutOrScroll(String) 7003 */ 7004 public void assertInLayoutOrScroll(String message) { 7005 if (mRecyclerView != null) { 7006 mRecyclerView.assertInLayoutOrScroll(message); 7007 } 7008 } 7009 7010 /** 7011 * Chooses a size from the given specs and parameters that is closest to the desired size 7012 * and also complies with the spec. 7013 * 7014 * @param spec The measureSpec 7015 * @param desired The preferred measurement 7016 * @param min The minimum value 7017 * 7018 * @return A size that fits to the given specs 7019 */ 7020 public static int chooseSize(int spec, int desired, int min) { 7021 final int mode = View.MeasureSpec.getMode(spec); 7022 final int size = View.MeasureSpec.getSize(spec); 7023 switch (mode) { 7024 case View.MeasureSpec.EXACTLY: 7025 return size; 7026 case View.MeasureSpec.AT_MOST: 7027 return Math.min(size, Math.max(desired, min)); 7028 case View.MeasureSpec.UNSPECIFIED: 7029 default: 7030 return Math.max(desired, min); 7031 } 7032 } 7033 7034 /** 7035 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 7036 * {@link IllegalStateException} if it <b>is</b>. 7037 * 7038 * @param message The message for the exception. Can be null. 7039 * @see #assertInLayoutOrScroll(String) 7040 */ 7041 public void assertNotInLayoutOrScroll(String message) { 7042 if (mRecyclerView != null) { 7043 mRecyclerView.assertNotInLayoutOrScroll(message); 7044 } 7045 } 7046 7047 /** 7048 * Defines whether the layout should be measured by the RecyclerView or the LayoutManager 7049 * wants to handle the layout measurements itself. 7050 * <p> 7051 * This method is usually called by the LayoutManager with value {@code true} if it wants 7052 * to support WRAP_CONTENT. If you are using a public LayoutManager but want to customize 7053 * the measurement logic, you can call this method with {@code false} and override 7054 * {@link LayoutManager#onMeasure(int, int)} to implement your custom measurement logic. 7055 * <p> 7056 * AutoMeasure is a convenience mechanism for LayoutManagers to easily wrap their content or 7057 * handle various specs provided by the RecyclerView's parent. 7058 * It works by calling {@link LayoutManager#onLayoutChildren(Recycler, State)} during an 7059 * {@link RecyclerView#onMeasure(int, int)} call, then calculating desired dimensions based 7060 * on children's positions. It does this while supporting all existing animation 7061 * capabilities of the RecyclerView. 7062 * <p> 7063 * AutoMeasure works as follows: 7064 * <ol> 7065 * <li>LayoutManager should call {@code setAutoMeasureEnabled(true)} to enable it. All of 7066 * the framework LayoutManagers use {@code auto-measure}.</li> 7067 * <li>When {@link RecyclerView#onMeasure(int, int)} is called, if the provided specs are 7068 * exact, RecyclerView will only call LayoutManager's {@code onMeasure} and return without 7069 * doing any layout calculation.</li> 7070 * <li>If one of the layout specs is not {@code EXACT}, the RecyclerView will start the 7071 * layout process in {@code onMeasure} call. It will process all pending Adapter updates and 7072 * decide whether to run a predictive layout or not. If it decides to do so, it will first 7073 * call {@link #onLayoutChildren(Recycler, State)} with {@link State#isPreLayout()} set to 7074 * {@code true}. At this stage, {@link #getWidth()} and {@link #getHeight()} will still 7075 * return the width and height of the RecyclerView as of the last layout calculation. 7076 * <p> 7077 * After handling the predictive case, RecyclerView will call 7078 * {@link #onLayoutChildren(Recycler, State)} with {@link State#isMeasuring()} set to 7079 * {@code true} and {@link State#isPreLayout()} set to {@code false}. The LayoutManager can 7080 * access the measurement specs via {@link #getHeight()}, {@link #getHeightMode()}, 7081 * {@link #getWidth()} and {@link #getWidthMode()}.</li> 7082 * <li>After the layout calculation, RecyclerView sets the measured width & height by 7083 * calculating the bounding box for the children (+ RecyclerView's padding). The 7084 * LayoutManagers can override {@link #setMeasuredDimension(Rect, int, int)} to choose 7085 * different values. For instance, GridLayoutManager overrides this value to handle the case 7086 * where if it is vertical and has 3 columns but only 2 items, it should still measure its 7087 * width to fit 3 items, not 2.</li> 7088 * <li>Any following on measure call to the RecyclerView will run 7089 * {@link #onLayoutChildren(Recycler, State)} with {@link State#isMeasuring()} set to 7090 * {@code true} and {@link State#isPreLayout()} set to {@code false}. RecyclerView will 7091 * take care of which views are actually added / removed / moved / changed for animations so 7092 * that the LayoutManager should not worry about them and handle each 7093 * {@link #onLayoutChildren(Recycler, State)} call as if it is the last one. 7094 * </li> 7095 * <li>When measure is complete and RecyclerView's 7096 * {@link #onLayout(boolean, int, int, int, int)} method is called, RecyclerView checks 7097 * whether it already did layout calculations during the measure pass and if so, it re-uses 7098 * that information. It may still decide to call {@link #onLayoutChildren(Recycler, State)} 7099 * if the last measure spec was different from the final dimensions or adapter contents 7100 * have changed between the measure call and the layout call.</li> 7101 * <li>Finally, animations are calculated and run as usual.</li> 7102 * </ol> 7103 * 7104 * @param enabled <code>True</code> if the Layout should be measured by the 7105 * RecyclerView, <code>false</code> if the LayoutManager wants 7106 * to measure itself. 7107 * 7108 * @see #setMeasuredDimension(Rect, int, int) 7109 * @see #isAutoMeasureEnabled() 7110 */ 7111 public void setAutoMeasureEnabled(boolean enabled) { 7112 mAutoMeasure = enabled; 7113 } 7114 7115 /** 7116 * Returns whether the LayoutManager uses the automatic measurement API or not. 7117 * 7118 * @return <code>True</code> if the LayoutManager is measured by the RecyclerView or 7119 * <code>false</code> if it measures itself. 7120 * 7121 * @see #setAutoMeasureEnabled(boolean) 7122 */ 7123 public boolean isAutoMeasureEnabled() { 7124 return mAutoMeasure; 7125 } 7126 7127 /** 7128 * Returns whether this LayoutManager supports automatic item animations. 7129 * A LayoutManager wishing to support item animations should obey certain 7130 * rules as outlined in {@link #onLayoutChildren(Recycler, State)}. 7131 * The default return value is <code>false</code>, so subclasses of LayoutManager 7132 * will not get predictive item animations by default. 7133 * 7134 * <p>Whether item animations are enabled in a RecyclerView is determined both 7135 * by the return value from this method and the 7136 * {@link RecyclerView#setItemAnimator(ItemAnimator) ItemAnimator} set on the 7137 * RecyclerView itself. If the RecyclerView has a non-null ItemAnimator but this 7138 * method returns false, then simple item animations will be enabled, in which 7139 * views that are moving onto or off of the screen are simply faded in/out. If 7140 * the RecyclerView has a non-null ItemAnimator and this method returns true, 7141 * then there will be two calls to {@link #onLayoutChildren(Recycler, State)} to 7142 * setup up the information needed to more intelligently predict where appearing 7143 * and disappearing views should be animated from/to.</p> 7144 * 7145 * @return true if predictive item animations should be enabled, false otherwise 7146 */ 7147 public boolean supportsPredictiveItemAnimations() { 7148 return false; 7149 } 7150 7151 /** 7152 * Sets whether the LayoutManager should be queried for views outside of 7153 * its viewport while the UI thread is idle between frames. 7154 * 7155 * <p>If enabled, the LayoutManager will be queried for items to inflate/bind in between 7156 * view system traversals on devices running API 21 or greater. Default value is true.</p> 7157 * 7158 * <p>On platforms API level 21 and higher, the UI thread is idle between passing a frame 7159 * to RenderThread and the starting up its next frame at the next VSync pulse. By 7160 * prefetching out of window views in this time period, delays from inflation and view 7161 * binding are much less likely to cause jank and stuttering during scrolls and flings.</p> 7162 * 7163 * <p>While prefetch is enabled, it will have the side effect of expanding the effective 7164 * size of the View cache to hold prefetched views.</p> 7165 * 7166 * @param enabled <code>True</code> if items should be prefetched in between traversals. 7167 * 7168 * @see #isItemPrefetchEnabled() 7169 */ 7170 public final void setItemPrefetchEnabled(boolean enabled) { 7171 if (enabled != mItemPrefetchEnabled) { 7172 mItemPrefetchEnabled = enabled; 7173 mPrefetchMaxCountObserved = 0; 7174 if (mRecyclerView != null) { 7175 mRecyclerView.mRecycler.updateViewCacheSize(); 7176 } 7177 } 7178 } 7179 7180 /** 7181 * Sets whether the LayoutManager should be queried for views outside of 7182 * its viewport while the UI thread is idle between frames. 7183 * 7184 * @see #setItemPrefetchEnabled(boolean) 7185 * 7186 * @return true if item prefetch is enabled, false otherwise 7187 */ 7188 public final boolean isItemPrefetchEnabled() { 7189 return mItemPrefetchEnabled; 7190 } 7191 7192 /** 7193 * Gather all positions from the LayoutManager to be prefetched, given specified momentum. 7194 * 7195 * <p>If item prefetch is enabled, this method is called in between traversals to gather 7196 * which positions the LayoutManager will soon need, given upcoming movement in subsequent 7197 * traversals.</p> 7198 * 7199 * <p>The LayoutManager should call {@link LayoutPrefetchRegistry#addPosition(int, int)} for each 7200 * item to be prepared, and these positions will have their ViewHolders created and bound, 7201 * if there is sufficient time available, in advance of being needed by a 7202 * scroll or layout.</p> 7203 * 7204 * @param dx X movement component. 7205 * @param dy Y movement component. 7206 * @param state State of RecyclerView 7207 * @param layoutPrefetchRegistry PrefetchRegistry to add prefetch entries into. 7208 * 7209 * @see #isItemPrefetchEnabled() 7210 * @see #collectInitialPrefetchPositions(int, LayoutPrefetchRegistry) 7211 */ 7212 public void collectAdjacentPrefetchPositions(int dx, int dy, State state, 7213 LayoutPrefetchRegistry layoutPrefetchRegistry) {} 7214 7215 /** 7216 * Gather all positions from the LayoutManager to be prefetched in preperation for its 7217 * RecyclerView to come on screen, due to the movement of another, containing RecyclerView. 7218 * 7219 * <p>This method is only called when a RecyclerView is nested in another RecyclerView.</p> 7220 * 7221 * <p>If item prefetch is enabled for this LayoutManager, as well in another containing 7222 * LayoutManager, this method is called in between draw traversals to gather 7223 * which positions this LayoutManager will first need, once it appears on the screen.</p> 7224 * 7225 * <p>For example, if this LayoutManager represents a horizontally scrolling list within a 7226 * vertically scrolling LayoutManager, this method would be called when the horizontal list 7227 * is about to come onscreen.</p> 7228 * 7229 * <p>The LayoutManager should call {@link LayoutPrefetchRegistry#addPosition(int, int)} for each 7230 * item to be prepared, and these positions will have their ViewHolders created and bound, 7231 * if there is sufficient time available, in advance of being needed by a 7232 * scroll or layout.</p> 7233 * 7234 * @param adapterItemCount number of items in the associated adapter. 7235 * @param layoutPrefetchRegistry PrefetchRegistry to add prefetch entries into. 7236 * 7237 * @see #isItemPrefetchEnabled() 7238 * @see #collectAdjacentPrefetchPositions(int, int, State, LayoutPrefetchRegistry) 7239 */ 7240 public void collectInitialPrefetchPositions(int adapterItemCount, 7241 LayoutPrefetchRegistry layoutPrefetchRegistry) {} 7242 7243 void dispatchAttachedToWindow(RecyclerView view) { 7244 mIsAttachedToWindow = true; 7245 onAttachedToWindow(view); 7246 } 7247 7248 void dispatchDetachedFromWindow(RecyclerView view, Recycler recycler) { 7249 mIsAttachedToWindow = false; 7250 onDetachedFromWindow(view, recycler); 7251 } 7252 7253 /** 7254 * Returns whether LayoutManager is currently attached to a RecyclerView which is attached 7255 * to a window. 7256 * 7257 * @return True if this LayoutManager is controlling a RecyclerView and the RecyclerView 7258 * is attached to window. 7259 */ 7260 public boolean isAttachedToWindow() { 7261 return mIsAttachedToWindow; 7262 } 7263 7264 /** 7265 * Causes the Runnable to execute on the next animation time step. 7266 * The runnable will be run on the user interface thread. 7267 * <p> 7268 * Calling this method when LayoutManager is not attached to a RecyclerView has no effect. 7269 * 7270 * @param action The Runnable that will be executed. 7271 * 7272 * @see #removeCallbacks 7273 */ 7274 public void postOnAnimation(Runnable action) { 7275 if (mRecyclerView != null) { 7276 ViewCompat.postOnAnimation(mRecyclerView, action); 7277 } 7278 } 7279 7280 /** 7281 * Removes the specified Runnable from the message queue. 7282 * <p> 7283 * Calling this method when LayoutManager is not attached to a RecyclerView has no effect. 7284 * 7285 * @param action The Runnable to remove from the message handling queue 7286 * 7287 * @return true if RecyclerView could ask the Handler to remove the Runnable, 7288 * false otherwise. When the returned value is true, the Runnable 7289 * may or may not have been actually removed from the message queue 7290 * (for instance, if the Runnable was not in the queue already.) 7291 * 7292 * @see #postOnAnimation 7293 */ 7294 public boolean removeCallbacks(Runnable action) { 7295 if (mRecyclerView != null) { 7296 return mRecyclerView.removeCallbacks(action); 7297 } 7298 return false; 7299 } 7300 /** 7301 * Called when this LayoutManager is both attached to a RecyclerView and that RecyclerView 7302 * is attached to a window. 7303 * <p> 7304 * If the RecyclerView is re-attached with the same LayoutManager and Adapter, it may not 7305 * call {@link #onLayoutChildren(Recycler, State)} if nothing has changed and a layout was 7306 * not requested on the RecyclerView while it was detached. 7307 * <p> 7308 * Subclass implementations should always call through to the superclass implementation. 7309 * 7310 * @param view The RecyclerView this LayoutManager is bound to 7311 * 7312 * @see #onDetachedFromWindow(RecyclerView, Recycler) 7313 */ 7314 @CallSuper 7315 public void onAttachedToWindow(RecyclerView view) { 7316 } 7317 7318 /** 7319 * @deprecated 7320 * override {@link #onDetachedFromWindow(RecyclerView, Recycler)} 7321 */ 7322 @Deprecated 7323 public void onDetachedFromWindow(RecyclerView view) { 7324 7325 } 7326 7327 /** 7328 * Called when this LayoutManager is detached from its parent RecyclerView or when 7329 * its parent RecyclerView is detached from its window. 7330 * <p> 7331 * LayoutManager should clear all of its View references as another LayoutManager might be 7332 * assigned to the RecyclerView. 7333 * <p> 7334 * If the RecyclerView is re-attached with the same LayoutManager and Adapter, it may not 7335 * call {@link #onLayoutChildren(Recycler, State)} if nothing has changed and a layout was 7336 * not requested on the RecyclerView while it was detached. 7337 * <p> 7338 * If your LayoutManager has View references that it cleans in on-detach, it should also 7339 * call {@link RecyclerView#requestLayout()} to ensure that it is re-laid out when 7340 * RecyclerView is re-attached. 7341 * <p> 7342 * Subclass implementations should always call through to the superclass implementation. 7343 * 7344 * @param view The RecyclerView this LayoutManager is bound to 7345 * @param recycler The recycler to use if you prefer to recycle your children instead of 7346 * keeping them around. 7347 * 7348 * @see #onAttachedToWindow(RecyclerView) 7349 */ 7350 @CallSuper 7351 public void onDetachedFromWindow(RecyclerView view, Recycler recycler) { 7352 onDetachedFromWindow(view); 7353 } 7354 7355 /** 7356 * Check if the RecyclerView is configured to clip child views to its padding. 7357 * 7358 * @return true if this RecyclerView clips children to its padding, false otherwise 7359 */ 7360 public boolean getClipToPadding() { 7361 return mRecyclerView != null && mRecyclerView.mClipToPadding; 7362 } 7363 7364 /** 7365 * Lay out all relevant child views from the given adapter. 7366 * 7367 * The LayoutManager is in charge of the behavior of item animations. By default, 7368 * RecyclerView has a non-null {@link #getItemAnimator() ItemAnimator}, and simple 7369 * item animations are enabled. This means that add/remove operations on the 7370 * adapter will result in animations to add new or appearing items, removed or 7371 * disappearing items, and moved items. If a LayoutManager returns false from 7372 * {@link #supportsPredictiveItemAnimations()}, which is the default, and runs a 7373 * normal layout operation during {@link #onLayoutChildren(Recycler, State)}, the 7374 * RecyclerView will have enough information to run those animations in a simple 7375 * way. For example, the default ItemAnimator, {@link DefaultItemAnimator}, will 7376 * simply fade views in and out, whether they are actually added/removed or whether 7377 * they are moved on or off the screen due to other add/remove operations. 7378 * 7379 * <p>A LayoutManager wanting a better item animation experience, where items can be 7380 * animated onto and off of the screen according to where the items exist when they 7381 * are not on screen, then the LayoutManager should return true from 7382 * {@link #supportsPredictiveItemAnimations()} and add additional logic to 7383 * {@link #onLayoutChildren(Recycler, State)}. Supporting predictive animations 7384 * means that {@link #onLayoutChildren(Recycler, State)} will be called twice; 7385 * once as a "pre" layout step to determine where items would have been prior to 7386 * a real layout, and again to do the "real" layout. In the pre-layout phase, 7387 * items will remember their pre-layout positions to allow them to be laid out 7388 * appropriately. Also, {@link LayoutParams#isItemRemoved() removed} items will 7389 * be returned from the scrap to help determine correct placement of other items. 7390 * These removed items should not be added to the child list, but should be used 7391 * to help calculate correct positioning of other views, including views that 7392 * were not previously onscreen (referred to as APPEARING views), but whose 7393 * pre-layout offscreen position can be determined given the extra 7394 * information about the pre-layout removed views.</p> 7395 * 7396 * <p>The second layout pass is the real layout in which only non-removed views 7397 * will be used. The only additional requirement during this pass is, if 7398 * {@link #supportsPredictiveItemAnimations()} returns true, to note which 7399 * views exist in the child list prior to layout and which are not there after 7400 * layout (referred to as DISAPPEARING views), and to position/layout those views 7401 * appropriately, without regard to the actual bounds of the RecyclerView. This allows 7402 * the animation system to know the location to which to animate these disappearing 7403 * views.</p> 7404 * 7405 * <p>The default LayoutManager implementations for RecyclerView handle all of these 7406 * requirements for animations already. Clients of RecyclerView can either use one 7407 * of these layout managers directly or look at their implementations of 7408 * onLayoutChildren() to see how they account for the APPEARING and 7409 * DISAPPEARING views.</p> 7410 * 7411 * @param recycler Recycler to use for fetching potentially cached views for a 7412 * position 7413 * @param state Transient state of RecyclerView 7414 */ 7415 public void onLayoutChildren(Recycler recycler, State state) { 7416 Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) "); 7417 } 7418 7419 /** 7420 * Called after a full layout calculation is finished. The layout calculation may include 7421 * multiple {@link #onLayoutChildren(Recycler, State)} calls due to animations or 7422 * layout measurement but it will include only one {@link #onLayoutCompleted(State)} call. 7423 * This method will be called at the end of {@link View#layout(int, int, int, int)} call. 7424 * <p> 7425 * This is a good place for the LayoutManager to do some cleanup like pending scroll 7426 * position, saved state etc. 7427 * 7428 * @param state Transient state of RecyclerView 7429 */ 7430 public void onLayoutCompleted(State state) { 7431 } 7432 7433 /** 7434 * Create a default <code>LayoutParams</code> object for a child of the RecyclerView. 7435 * 7436 * <p>LayoutManagers will often want to use a custom <code>LayoutParams</code> type 7437 * to store extra information specific to the layout. Client code should subclass 7438 * {@link RecyclerView.LayoutParams} for this purpose.</p> 7439 * 7440 * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type 7441 * you must also override 7442 * {@link #checkLayoutParams(LayoutParams)}, 7443 * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and 7444 * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p> 7445 * 7446 * @return A new LayoutParams for a child view 7447 */ 7448 public abstract LayoutParams generateDefaultLayoutParams(); 7449 7450 /** 7451 * Determines the validity of the supplied LayoutParams object. 7452 * 7453 * <p>This should check to make sure that the object is of the correct type 7454 * and all values are within acceptable ranges. The default implementation 7455 * returns <code>true</code> for non-null params.</p> 7456 * 7457 * @param lp LayoutParams object to check 7458 * @return true if this LayoutParams object is valid, false otherwise 7459 */ 7460 public boolean checkLayoutParams(LayoutParams lp) { 7461 return lp != null; 7462 } 7463 7464 /** 7465 * Create a LayoutParams object suitable for this LayoutManager, copying relevant 7466 * values from the supplied LayoutParams object if possible. 7467 * 7468 * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type 7469 * you must also override 7470 * {@link #checkLayoutParams(LayoutParams)}, 7471 * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and 7472 * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p> 7473 * 7474 * @param lp Source LayoutParams object to copy values from 7475 * @return a new LayoutParams object 7476 */ 7477 public LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { 7478 if (lp instanceof LayoutParams) { 7479 return new LayoutParams((LayoutParams) lp); 7480 } else if (lp instanceof MarginLayoutParams) { 7481 return new LayoutParams((MarginLayoutParams) lp); 7482 } else { 7483 return new LayoutParams(lp); 7484 } 7485 } 7486 7487 /** 7488 * Create a LayoutParams object suitable for this LayoutManager from 7489 * an inflated layout resource. 7490 * 7491 * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type 7492 * you must also override 7493 * {@link #checkLayoutParams(LayoutParams)}, 7494 * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and 7495 * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p> 7496 * 7497 * @param c Context for obtaining styled attributes 7498 * @param attrs AttributeSet describing the supplied arguments 7499 * @return a new LayoutParams object 7500 */ 7501 public LayoutParams generateLayoutParams(Context c, AttributeSet attrs) { 7502 return new LayoutParams(c, attrs); 7503 } 7504 7505 /** 7506 * Scroll horizontally by dx pixels in screen coordinates and return the distance traveled. 7507 * The default implementation does nothing and returns 0. 7508 * 7509 * @param dx distance to scroll by in pixels. X increases as scroll position 7510 * approaches the right. 7511 * @param recycler Recycler to use for fetching potentially cached views for a 7512 * position 7513 * @param state Transient state of RecyclerView 7514 * @return The actual distance scrolled. The return value will be negative if dx was 7515 * negative and scrolling proceeeded in that direction. 7516 * <code>Math.abs(result)</code> may be less than dx if a boundary was reached. 7517 */ 7518 public int scrollHorizontallyBy(int dx, Recycler recycler, State state) { 7519 return 0; 7520 } 7521 7522 /** 7523 * Scroll vertically by dy pixels in screen coordinates and return the distance traveled. 7524 * The default implementation does nothing and returns 0. 7525 * 7526 * @param dy distance to scroll in pixels. Y increases as scroll position 7527 * approaches the bottom. 7528 * @param recycler Recycler to use for fetching potentially cached views for a 7529 * position 7530 * @param state Transient state of RecyclerView 7531 * @return The actual distance scrolled. The return value will be negative if dy was 7532 * negative and scrolling proceeeded in that direction. 7533 * <code>Math.abs(result)</code> may be less than dy if a boundary was reached. 7534 */ 7535 public int scrollVerticallyBy(int dy, Recycler recycler, State state) { 7536 return 0; 7537 } 7538 7539 /** 7540 * Query if horizontal scrolling is currently supported. The default implementation 7541 * returns false. 7542 * 7543 * @return True if this LayoutManager can scroll the current contents horizontally 7544 */ 7545 public boolean canScrollHorizontally() { 7546 return false; 7547 } 7548 7549 /** 7550 * Query if vertical scrolling is currently supported. The default implementation 7551 * returns false. 7552 * 7553 * @return True if this LayoutManager can scroll the current contents vertically 7554 */ 7555 public boolean canScrollVertically() { 7556 return false; 7557 } 7558 7559 /** 7560 * Scroll to the specified adapter position. 7561 * 7562 * Actual position of the item on the screen depends on the LayoutManager implementation. 7563 * @param position Scroll to this adapter position. 7564 */ 7565 public void scrollToPosition(int position) { 7566 if (DEBUG) { 7567 Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract"); 7568 } 7569 } 7570 7571 /** 7572 * <p>Smooth scroll to the specified adapter position.</p> 7573 * <p>To support smooth scrolling, override this method, create your {@link SmoothScroller} 7574 * instance and call {@link #startSmoothScroll(SmoothScroller)}. 7575 * </p> 7576 * @param recyclerView The RecyclerView to which this layout manager is attached 7577 * @param state Current State of RecyclerView 7578 * @param position Scroll to this adapter position. 7579 */ 7580 public void smoothScrollToPosition(RecyclerView recyclerView, State state, 7581 int position) { 7582 Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling"); 7583 } 7584 7585 /** 7586 * <p>Starts a smooth scroll using the provided SmoothScroller.</p> 7587 * <p>Calling this method will cancel any previous smooth scroll request.</p> 7588 * @param smoothScroller Instance which defines how smooth scroll should be animated 7589 */ 7590 public void startSmoothScroll(SmoothScroller smoothScroller) { 7591 if (mSmoothScroller != null && smoothScroller != mSmoothScroller 7592 && mSmoothScroller.isRunning()) { 7593 mSmoothScroller.stop(); 7594 } 7595 mSmoothScroller = smoothScroller; 7596 mSmoothScroller.start(mRecyclerView, this); 7597 } 7598 7599 /** 7600 * @return true if RecycylerView is currently in the state of smooth scrolling. 7601 */ 7602 public boolean isSmoothScrolling() { 7603 return mSmoothScroller != null && mSmoothScroller.isRunning(); 7604 } 7605 7606 7607 /** 7608 * Returns the resolved layout direction for this RecyclerView. 7609 * 7610 * @return {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL} if the layout 7611 * direction is RTL or returns 7612 * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} if the layout direction 7613 * is not RTL. 7614 */ 7615 public int getLayoutDirection() { 7616 return ViewCompat.getLayoutDirection(mRecyclerView); 7617 } 7618 7619 /** 7620 * Ends all animations on the view created by the {@link ItemAnimator}. 7621 * 7622 * @param view The View for which the animations should be ended. 7623 * @see RecyclerView.ItemAnimator#endAnimations() 7624 */ 7625 public void endAnimation(View view) { 7626 if (mRecyclerView.mItemAnimator != null) { 7627 mRecyclerView.mItemAnimator.endAnimation(getChildViewHolderInt(view)); 7628 } 7629 } 7630 7631 /** 7632 * To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view 7633 * to the layout that is known to be going away, either because it has been 7634 * {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the 7635 * visible portion of the container but is being laid out in order to inform RecyclerView 7636 * in how to animate the item out of view. 7637 * <p> 7638 * Views added via this method are going to be invisible to LayoutManager after the 7639 * dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)} 7640 * or won't be included in {@link #getChildCount()} method. 7641 * 7642 * @param child View to add and then remove with animation. 7643 */ 7644 public void addDisappearingView(View child) { 7645 addDisappearingView(child, -1); 7646 } 7647 7648 /** 7649 * To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view 7650 * to the layout that is known to be going away, either because it has been 7651 * {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the 7652 * visible portion of the container but is being laid out in order to inform RecyclerView 7653 * in how to animate the item out of view. 7654 * <p> 7655 * Views added via this method are going to be invisible to LayoutManager after the 7656 * dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)} 7657 * or won't be included in {@link #getChildCount()} method. 7658 * 7659 * @param child View to add and then remove with animation. 7660 * @param index Index of the view. 7661 */ 7662 public void addDisappearingView(View child, int index) { 7663 addViewInt(child, index, true); 7664 } 7665 7666 /** 7667 * Add a view to the currently attached RecyclerView if needed. LayoutManagers should 7668 * use this method to add views obtained from a {@link Recycler} using 7669 * {@link Recycler#getViewForPosition(int)}. 7670 * 7671 * @param child View to add 7672 */ 7673 public void addView(View child) { 7674 addView(child, -1); 7675 } 7676 7677 /** 7678 * Add a view to the currently attached RecyclerView if needed. LayoutManagers should 7679 * use this method to add views obtained from a {@link Recycler} using 7680 * {@link Recycler#getViewForPosition(int)}. 7681 * 7682 * @param child View to add 7683 * @param index Index to add child at 7684 */ 7685 public void addView(View child, int index) { 7686 addViewInt(child, index, false); 7687 } 7688 7689 private void addViewInt(View child, int index, boolean disappearing) { 7690 final ViewHolder holder = getChildViewHolderInt(child); 7691 if (disappearing || holder.isRemoved()) { 7692 // these views will be hidden at the end of the layout pass. 7693 mRecyclerView.mViewInfoStore.addToDisappearedInLayout(holder); 7694 } else { 7695 // This may look like unnecessary but may happen if layout manager supports 7696 // predictive layouts and adapter removed then re-added the same item. 7697 // In this case, added version will be visible in the post layout (because add is 7698 // deferred) but RV will still bind it to the same View. 7699 // So if a View re-appears in post layout pass, remove it from disappearing list. 7700 mRecyclerView.mViewInfoStore.removeFromDisappearedInLayout(holder); 7701 } 7702 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 7703 if (holder.wasReturnedFromScrap() || holder.isScrap()) { 7704 if (holder.isScrap()) { 7705 holder.unScrap(); 7706 } else { 7707 holder.clearReturnedFromScrapFlag(); 7708 } 7709 mChildHelper.attachViewToParent(child, index, child.getLayoutParams(), false); 7710 if (DISPATCH_TEMP_DETACH) { 7711 ViewCompat.dispatchFinishTemporaryDetach(child); 7712 } 7713 } else if (child.getParent() == mRecyclerView) { // it was not a scrap but a valid child 7714 // ensure in correct position 7715 int currentIndex = mChildHelper.indexOfChild(child); 7716 if (index == -1) { 7717 index = mChildHelper.getChildCount(); 7718 } 7719 if (currentIndex == -1) { 7720 throw new IllegalStateException("Added View has RecyclerView as parent but" 7721 + " view is not a real child. Unfiltered index:" 7722 + mRecyclerView.indexOfChild(child)); 7723 } 7724 if (currentIndex != index) { 7725 mRecyclerView.mLayout.moveView(currentIndex, index); 7726 } 7727 } else { 7728 mChildHelper.addView(child, index, false); 7729 lp.mInsetsDirty = true; 7730 if (mSmoothScroller != null && mSmoothScroller.isRunning()) { 7731 mSmoothScroller.onChildAttachedToWindow(child); 7732 } 7733 } 7734 if (lp.mPendingInvalidate) { 7735 if (DEBUG) { 7736 Log.d(TAG, "consuming pending invalidate on child " + lp.mViewHolder); 7737 } 7738 holder.itemView.invalidate(); 7739 lp.mPendingInvalidate = false; 7740 } 7741 } 7742 7743 /** 7744 * Remove a view from the currently attached RecyclerView if needed. LayoutManagers should 7745 * use this method to completely remove a child view that is no longer needed. 7746 * LayoutManagers should strongly consider recycling removed views using 7747 * {@link Recycler#recycleView(android.view.View)}. 7748 * 7749 * @param child View to remove 7750 */ 7751 public void removeView(View child) { 7752 mChildHelper.removeView(child); 7753 } 7754 7755 /** 7756 * Remove a view from the currently attached RecyclerView if needed. LayoutManagers should 7757 * use this method to completely remove a child view that is no longer needed. 7758 * LayoutManagers should strongly consider recycling removed views using 7759 * {@link Recycler#recycleView(android.view.View)}. 7760 * 7761 * @param index Index of the child view to remove 7762 */ 7763 public void removeViewAt(int index) { 7764 final View child = getChildAt(index); 7765 if (child != null) { 7766 mChildHelper.removeViewAt(index); 7767 } 7768 } 7769 7770 /** 7771 * Remove all views from the currently attached RecyclerView. This will not recycle 7772 * any of the affected views; the LayoutManager is responsible for doing so if desired. 7773 */ 7774 public void removeAllViews() { 7775 // Only remove non-animating views 7776 final int childCount = getChildCount(); 7777 for (int i = childCount - 1; i >= 0; i--) { 7778 mChildHelper.removeViewAt(i); 7779 } 7780 } 7781 7782 /** 7783 * Returns offset of the RecyclerView's text baseline from the its top boundary. 7784 * 7785 * @return The offset of the RecyclerView's text baseline from the its top boundary; -1 if 7786 * there is no baseline. 7787 */ 7788 public int getBaseline() { 7789 return -1; 7790 } 7791 7792 /** 7793 * Returns the adapter position of the item represented by the given View. This does not 7794 * contain any adapter changes that might have happened after the last layout. 7795 * 7796 * @param view The view to query 7797 * @return The adapter position of the item which is rendered by this View. 7798 */ 7799 public int getPosition(View view) { 7800 return ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); 7801 } 7802 7803 /** 7804 * Returns the View type defined by the adapter. 7805 * 7806 * @param view The view to query 7807 * @return The type of the view assigned by the adapter. 7808 */ 7809 public int getItemViewType(View view) { 7810 return getChildViewHolderInt(view).getItemViewType(); 7811 } 7812 7813 /** 7814 * Traverses the ancestors of the given view and returns the item view that contains it 7815 * and also a direct child of the LayoutManager. 7816 * <p> 7817 * Note that this method may return null if the view is a child of the RecyclerView but 7818 * not a child of the LayoutManager (e.g. running a disappear animation). 7819 * 7820 * @param view The view that is a descendant of the LayoutManager. 7821 * 7822 * @return The direct child of the LayoutManager which contains the given view or null if 7823 * the provided view is not a descendant of this LayoutManager. 7824 * 7825 * @see RecyclerView#getChildViewHolder(View) 7826 * @see RecyclerView#findContainingViewHolder(View) 7827 */ 7828 @Nullable 7829 public View findContainingItemView(View view) { 7830 if (mRecyclerView == null) { 7831 return null; 7832 } 7833 View found = mRecyclerView.findContainingItemView(view); 7834 if (found == null) { 7835 return null; 7836 } 7837 if (mChildHelper.isHidden(found)) { 7838 return null; 7839 } 7840 return found; 7841 } 7842 7843 /** 7844 * Finds the view which represents the given adapter position. 7845 * <p> 7846 * This method traverses each child since it has no information about child order. 7847 * Override this method to improve performance if your LayoutManager keeps data about 7848 * child views. 7849 * <p> 7850 * If a view is ignored via {@link #ignoreView(View)}, it is also ignored by this method. 7851 * 7852 * @param position Position of the item in adapter 7853 * @return The child view that represents the given position or null if the position is not 7854 * laid out 7855 */ 7856 public View findViewByPosition(int position) { 7857 final int childCount = getChildCount(); 7858 for (int i = 0; i < childCount; i++) { 7859 View child = getChildAt(i); 7860 ViewHolder vh = getChildViewHolderInt(child); 7861 if (vh == null) { 7862 continue; 7863 } 7864 if (vh.getLayoutPosition() == position && !vh.shouldIgnore() && 7865 (mRecyclerView.mState.isPreLayout() || !vh.isRemoved())) { 7866 return child; 7867 } 7868 } 7869 return null; 7870 } 7871 7872 /** 7873 * Temporarily detach a child view. 7874 * 7875 * <p>LayoutManagers may want to perform a lightweight detach operation to rearrange 7876 * views currently attached to the RecyclerView. Generally LayoutManager implementations 7877 * will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} 7878 * so that the detached view may be rebound and reused.</p> 7879 * 7880 * <p>If a LayoutManager uses this method to detach a view, it <em>must</em> 7881 * {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach} 7882 * or {@link #removeDetachedView(android.view.View) fully remove} the detached view 7883 * before the LayoutManager entry point method called by RecyclerView returns.</p> 7884 * 7885 * @param child Child to detach 7886 */ 7887 public void detachView(View child) { 7888 final int ind = mChildHelper.indexOfChild(child); 7889 if (ind >= 0) { 7890 detachViewInternal(ind, child); 7891 } 7892 } 7893 7894 /** 7895 * Temporarily detach a child view. 7896 * 7897 * <p>LayoutManagers may want to perform a lightweight detach operation to rearrange 7898 * views currently attached to the RecyclerView. Generally LayoutManager implementations 7899 * will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} 7900 * so that the detached view may be rebound and reused.</p> 7901 * 7902 * <p>If a LayoutManager uses this method to detach a view, it <em>must</em> 7903 * {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach} 7904 * or {@link #removeDetachedView(android.view.View) fully remove} the detached view 7905 * before the LayoutManager entry point method called by RecyclerView returns.</p> 7906 * 7907 * @param index Index of the child to detach 7908 */ 7909 public void detachViewAt(int index) { 7910 detachViewInternal(index, getChildAt(index)); 7911 } 7912 7913 private void detachViewInternal(int index, View view) { 7914 if (DISPATCH_TEMP_DETACH) { 7915 ViewCompat.dispatchStartTemporaryDetach(view); 7916 } 7917 mChildHelper.detachViewFromParent(index); 7918 } 7919 7920 /** 7921 * Reattach a previously {@link #detachView(android.view.View) detached} view. 7922 * This method should not be used to reattach views that were previously 7923 * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}. 7924 * 7925 * @param child Child to reattach 7926 * @param index Intended child index for child 7927 * @param lp LayoutParams for child 7928 */ 7929 public void attachView(View child, int index, LayoutParams lp) { 7930 ViewHolder vh = getChildViewHolderInt(child); 7931 if (vh.isRemoved()) { 7932 mRecyclerView.mViewInfoStore.addToDisappearedInLayout(vh); 7933 } else { 7934 mRecyclerView.mViewInfoStore.removeFromDisappearedInLayout(vh); 7935 } 7936 mChildHelper.attachViewToParent(child, index, lp, vh.isRemoved()); 7937 if (DISPATCH_TEMP_DETACH) { 7938 ViewCompat.dispatchFinishTemporaryDetach(child); 7939 } 7940 } 7941 7942 /** 7943 * Reattach a previously {@link #detachView(android.view.View) detached} view. 7944 * This method should not be used to reattach views that were previously 7945 * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}. 7946 * 7947 * @param child Child to reattach 7948 * @param index Intended child index for child 7949 */ 7950 public void attachView(View child, int index) { 7951 attachView(child, index, (LayoutParams) child.getLayoutParams()); 7952 } 7953 7954 /** 7955 * Reattach a previously {@link #detachView(android.view.View) detached} view. 7956 * This method should not be used to reattach views that were previously 7957 * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}. 7958 * 7959 * @param child Child to reattach 7960 */ 7961 public void attachView(View child) { 7962 attachView(child, -1); 7963 } 7964 7965 /** 7966 * Finish removing a view that was previously temporarily 7967 * {@link #detachView(android.view.View) detached}. 7968 * 7969 * @param child Detached child to remove 7970 */ 7971 public void removeDetachedView(View child) { 7972 mRecyclerView.removeDetachedView(child, false); 7973 } 7974 7975 /** 7976 * Moves a View from one position to another. 7977 * 7978 * @param fromIndex The View's initial index 7979 * @param toIndex The View's target index 7980 */ 7981 public void moveView(int fromIndex, int toIndex) { 7982 View view = getChildAt(fromIndex); 7983 if (view == null) { 7984 throw new IllegalArgumentException("Cannot move a child from non-existing index:" 7985 + fromIndex); 7986 } 7987 detachViewAt(fromIndex); 7988 attachView(view, toIndex); 7989 } 7990 7991 /** 7992 * Detach a child view and add it to a {@link Recycler Recycler's} scrap heap. 7993 * 7994 * <p>Scrapping a view allows it to be rebound and reused to show updated or 7995 * different data.</p> 7996 * 7997 * @param child Child to detach and scrap 7998 * @param recycler Recycler to deposit the new scrap view into 7999 */ 8000 public void detachAndScrapView(View child, Recycler recycler) { 8001 int index = mChildHelper.indexOfChild(child); 8002 scrapOrRecycleView(recycler, index, child); 8003 } 8004 8005 /** 8006 * Detach a child view and add it to a {@link Recycler Recycler's} scrap heap. 8007 * 8008 * <p>Scrapping a view allows it to be rebound and reused to show updated or 8009 * different data.</p> 8010 * 8011 * @param index Index of child to detach and scrap 8012 * @param recycler Recycler to deposit the new scrap view into 8013 */ 8014 public void detachAndScrapViewAt(int index, Recycler recycler) { 8015 final View child = getChildAt(index); 8016 scrapOrRecycleView(recycler, index, child); 8017 } 8018 8019 /** 8020 * Remove a child view and recycle it using the given Recycler. 8021 * 8022 * @param child Child to remove and recycle 8023 * @param recycler Recycler to use to recycle child 8024 */ 8025 public void removeAndRecycleView(View child, Recycler recycler) { 8026 removeView(child); 8027 recycler.recycleView(child); 8028 } 8029 8030 /** 8031 * Remove a child view and recycle it using the given Recycler. 8032 * 8033 * @param index Index of child to remove and recycle 8034 * @param recycler Recycler to use to recycle child 8035 */ 8036 public void removeAndRecycleViewAt(int index, Recycler recycler) { 8037 final View view = getChildAt(index); 8038 removeViewAt(index); 8039 recycler.recycleView(view); 8040 } 8041 8042 /** 8043 * Return the current number of child views attached to the parent RecyclerView. 8044 * This does not include child views that were temporarily detached and/or scrapped. 8045 * 8046 * @return Number of attached children 8047 */ 8048 public int getChildCount() { 8049 return mChildHelper != null ? mChildHelper.getChildCount() : 0; 8050 } 8051 8052 /** 8053 * Return the child view at the given index 8054 * @param index Index of child to return 8055 * @return Child view at index 8056 */ 8057 public View getChildAt(int index) { 8058 return mChildHelper != null ? mChildHelper.getChildAt(index) : null; 8059 } 8060 8061 /** 8062 * Return the width measurement spec mode of the RecyclerView. 8063 * <p> 8064 * This value is set only if the LayoutManager opts into the auto measure api via 8065 * {@link #setAutoMeasureEnabled(boolean)}. 8066 * <p> 8067 * When RecyclerView is running a layout, this value is always set to 8068 * {@link View.MeasureSpec#EXACTLY} even if it was measured with a different spec mode. 8069 * 8070 * @return Width measure spec mode. 8071 * 8072 * @see View.MeasureSpec#getMode(int) 8073 * @see View#onMeasure(int, int) 8074 */ 8075 public int getWidthMode() { 8076 return mWidthMode; 8077 } 8078 8079 /** 8080 * Return the height measurement spec mode of the RecyclerView. 8081 * <p> 8082 * This value is set only if the LayoutManager opts into the auto measure api via 8083 * {@link #setAutoMeasureEnabled(boolean)}. 8084 * <p> 8085 * When RecyclerView is running a layout, this value is always set to 8086 * {@link View.MeasureSpec#EXACTLY} even if it was measured with a different spec mode. 8087 * 8088 * @return Height measure spec mode. 8089 * 8090 * @see View.MeasureSpec#getMode(int) 8091 * @see View#onMeasure(int, int) 8092 */ 8093 public int getHeightMode() { 8094 return mHeightMode; 8095 } 8096 8097 /** 8098 * Return the width of the parent RecyclerView 8099 * 8100 * @return Width in pixels 8101 */ 8102 public int getWidth() { 8103 return mWidth; 8104 } 8105 8106 /** 8107 * Return the height of the parent RecyclerView 8108 * 8109 * @return Height in pixels 8110 */ 8111 public int getHeight() { 8112 return mHeight; 8113 } 8114 8115 /** 8116 * Return the left padding of the parent RecyclerView 8117 * 8118 * @return Padding in pixels 8119 */ 8120 public int getPaddingLeft() { 8121 return mRecyclerView != null ? mRecyclerView.getPaddingLeft() : 0; 8122 } 8123 8124 /** 8125 * Return the top padding of the parent RecyclerView 8126 * 8127 * @return Padding in pixels 8128 */ 8129 public int getPaddingTop() { 8130 return mRecyclerView != null ? mRecyclerView.getPaddingTop() : 0; 8131 } 8132 8133 /** 8134 * Return the right padding of the parent RecyclerView 8135 * 8136 * @return Padding in pixels 8137 */ 8138 public int getPaddingRight() { 8139 return mRecyclerView != null ? mRecyclerView.getPaddingRight() : 0; 8140 } 8141 8142 /** 8143 * Return the bottom padding of the parent RecyclerView 8144 * 8145 * @return Padding in pixels 8146 */ 8147 public int getPaddingBottom() { 8148 return mRecyclerView != null ? mRecyclerView.getPaddingBottom() : 0; 8149 } 8150 8151 /** 8152 * Return the start padding of the parent RecyclerView 8153 * 8154 * @return Padding in pixels 8155 */ 8156 public int getPaddingStart() { 8157 return mRecyclerView != null ? ViewCompat.getPaddingStart(mRecyclerView) : 0; 8158 } 8159 8160 /** 8161 * Return the end padding of the parent RecyclerView 8162 * 8163 * @return Padding in pixels 8164 */ 8165 public int getPaddingEnd() { 8166 return mRecyclerView != null ? ViewCompat.getPaddingEnd(mRecyclerView) : 0; 8167 } 8168 8169 /** 8170 * Returns true if the RecyclerView this LayoutManager is bound to has focus. 8171 * 8172 * @return True if the RecyclerView has focus, false otherwise. 8173 * @see View#isFocused() 8174 */ 8175 public boolean isFocused() { 8176 return mRecyclerView != null && mRecyclerView.isFocused(); 8177 } 8178 8179 /** 8180 * Returns true if the RecyclerView this LayoutManager is bound to has or contains focus. 8181 * 8182 * @return true if the RecyclerView has or contains focus 8183 * @see View#hasFocus() 8184 */ 8185 public boolean hasFocus() { 8186 return mRecyclerView != null && mRecyclerView.hasFocus(); 8187 } 8188 8189 /** 8190 * Returns the item View which has or contains focus. 8191 * 8192 * @return A direct child of RecyclerView which has focus or contains the focused child. 8193 */ 8194 public View getFocusedChild() { 8195 if (mRecyclerView == null) { 8196 return null; 8197 } 8198 final View focused = mRecyclerView.getFocusedChild(); 8199 if (focused == null || mChildHelper.isHidden(focused)) { 8200 return null; 8201 } 8202 return focused; 8203 } 8204 8205 /** 8206 * Returns the number of items in the adapter bound to the parent RecyclerView. 8207 * <p> 8208 * Note that this number is not necessarily equal to {@link State#getItemCount()}. In 8209 * methods where State is available, you should use {@link State#getItemCount()} instead. 8210 * For more details, check the documentation for {@link State#getItemCount()}. 8211 * 8212 * @return The number of items in the bound adapter 8213 * @see State#getItemCount() 8214 */ 8215 public int getItemCount() { 8216 final Adapter a = mRecyclerView != null ? mRecyclerView.getAdapter() : null; 8217 return a != null ? a.getItemCount() : 0; 8218 } 8219 8220 /** 8221 * Offset all child views attached to the parent RecyclerView by dx pixels along 8222 * the horizontal axis. 8223 * 8224 * @param dx Pixels to offset by 8225 */ 8226 public void offsetChildrenHorizontal(int dx) { 8227 if (mRecyclerView != null) { 8228 mRecyclerView.offsetChildrenHorizontal(dx); 8229 } 8230 } 8231 8232 /** 8233 * Offset all child views attached to the parent RecyclerView by dy pixels along 8234 * the vertical axis. 8235 * 8236 * @param dy Pixels to offset by 8237 */ 8238 public void offsetChildrenVertical(int dy) { 8239 if (mRecyclerView != null) { 8240 mRecyclerView.offsetChildrenVertical(dy); 8241 } 8242 } 8243 8244 /** 8245 * Flags a view so that it will not be scrapped or recycled. 8246 * <p> 8247 * Scope of ignoring a child is strictly restricted to position tracking, scrapping and 8248 * recyling. Methods like {@link #removeAndRecycleAllViews(Recycler)} will ignore the child 8249 * whereas {@link #removeAllViews()} or {@link #offsetChildrenHorizontal(int)} will not 8250 * ignore the child. 8251 * <p> 8252 * Before this child can be recycled again, you have to call 8253 * {@link #stopIgnoringView(View)}. 8254 * <p> 8255 * You can call this method only if your LayoutManger is in onLayout or onScroll callback. 8256 * 8257 * @param view View to ignore. 8258 * @see #stopIgnoringView(View) 8259 */ 8260 public void ignoreView(View view) { 8261 if (view.getParent() != mRecyclerView || mRecyclerView.indexOfChild(view) == -1) { 8262 // checking this because calling this method on a recycled or detached view may 8263 // cause loss of state. 8264 throw new IllegalArgumentException("View should be fully attached to be ignored"); 8265 } 8266 final ViewHolder vh = getChildViewHolderInt(view); 8267 vh.addFlags(ViewHolder.FLAG_IGNORE); 8268 mRecyclerView.mViewInfoStore.removeViewHolder(vh); 8269 } 8270 8271 /** 8272 * View can be scrapped and recycled again. 8273 * <p> 8274 * Note that calling this method removes all information in the view holder. 8275 * <p> 8276 * You can call this method only if your LayoutManger is in onLayout or onScroll callback. 8277 * 8278 * @param view View to ignore. 8279 */ 8280 public void stopIgnoringView(View view) { 8281 final ViewHolder vh = getChildViewHolderInt(view); 8282 vh.stopIgnoring(); 8283 vh.resetInternal(); 8284 vh.addFlags(ViewHolder.FLAG_INVALID); 8285 } 8286 8287 /** 8288 * Temporarily detach and scrap all currently attached child views. Views will be scrapped 8289 * into the given Recycler. The Recycler may prefer to reuse scrap views before 8290 * other views that were previously recycled. 8291 * 8292 * @param recycler Recycler to scrap views into 8293 */ 8294 public void detachAndScrapAttachedViews(Recycler recycler) { 8295 final int childCount = getChildCount(); 8296 for (int i = childCount - 1; i >= 0; i--) { 8297 final View v = getChildAt(i); 8298 scrapOrRecycleView(recycler, i, v); 8299 } 8300 } 8301 8302 private void scrapOrRecycleView(Recycler recycler, int index, View view) { 8303 final ViewHolder viewHolder = getChildViewHolderInt(view); 8304 if (viewHolder.shouldIgnore()) { 8305 if (DEBUG) { 8306 Log.d(TAG, "ignoring view " + viewHolder); 8307 } 8308 return; 8309 } 8310 if (viewHolder.isInvalid() && !viewHolder.isRemoved() && 8311 !mRecyclerView.mAdapter.hasStableIds()) { 8312 removeViewAt(index); 8313 recycler.recycleViewHolderInternal(viewHolder); 8314 } else { 8315 detachViewAt(index); 8316 recycler.scrapView(view); 8317 mRecyclerView.mViewInfoStore.onViewDetached(viewHolder); 8318 } 8319 } 8320 8321 /** 8322 * Recycles the scrapped views. 8323 * <p> 8324 * When a view is detached and removed, it does not trigger a ViewGroup invalidate. This is 8325 * the expected behavior if scrapped views are used for animations. Otherwise, we need to 8326 * call remove and invalidate RecyclerView to ensure UI update. 8327 * 8328 * @param recycler Recycler 8329 */ 8330 void removeAndRecycleScrapInt(Recycler recycler) { 8331 final int scrapCount = recycler.getScrapCount(); 8332 // Loop backward, recycler might be changed by removeDetachedView() 8333 for (int i = scrapCount - 1; i >= 0; i--) { 8334 final View scrap = recycler.getScrapViewAt(i); 8335 final ViewHolder vh = getChildViewHolderInt(scrap); 8336 if (vh.shouldIgnore()) { 8337 continue; 8338 } 8339 // If the scrap view is animating, we need to cancel them first. If we cancel it 8340 // here, ItemAnimator callback may recycle it which will cause double recycling. 8341 // To avoid this, we mark it as not recycleable before calling the item animator. 8342 // Since removeDetachedView calls a user API, a common mistake (ending animations on 8343 // the view) may recycle it too, so we guard it before we call user APIs. 8344 vh.setIsRecyclable(false); 8345 if (vh.isTmpDetached()) { 8346 mRecyclerView.removeDetachedView(scrap, false); 8347 } 8348 if (mRecyclerView.mItemAnimator != null) { 8349 mRecyclerView.mItemAnimator.endAnimation(vh); 8350 } 8351 vh.setIsRecyclable(true); 8352 recycler.quickRecycleScrapView(scrap); 8353 } 8354 recycler.clearScrap(); 8355 if (scrapCount > 0) { 8356 mRecyclerView.invalidate(); 8357 } 8358 } 8359 8360 8361 /** 8362 * Measure a child view using standard measurement policy, taking the padding 8363 * of the parent RecyclerView and any added item decorations into account. 8364 * 8365 * <p>If the RecyclerView can be scrolled in either dimension the caller may 8366 * pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p> 8367 * 8368 * @param child Child view to measure 8369 * @param widthUsed Width in pixels currently consumed by other views, if relevant 8370 * @param heightUsed Height in pixels currently consumed by other views, if relevant 8371 */ 8372 public void measureChild(View child, int widthUsed, int heightUsed) { 8373 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 8374 8375 final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child); 8376 widthUsed += insets.left + insets.right; 8377 heightUsed += insets.top + insets.bottom; 8378 final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(), 8379 getPaddingLeft() + getPaddingRight() + widthUsed, lp.width, 8380 canScrollHorizontally()); 8381 final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(), 8382 getPaddingTop() + getPaddingBottom() + heightUsed, lp.height, 8383 canScrollVertically()); 8384 if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) { 8385 child.measure(widthSpec, heightSpec); 8386 } 8387 } 8388 8389 /** 8390 * RecyclerView internally does its own View measurement caching which should help with 8391 * WRAP_CONTENT. 8392 * <p> 8393 * Use this method if the View is already measured once in this layout pass. 8394 */ 8395 boolean shouldReMeasureChild(View child, int widthSpec, int heightSpec, LayoutParams lp) { 8396 return !mMeasurementCacheEnabled 8397 || !isMeasurementUpToDate(child.getMeasuredWidth(), widthSpec, lp.width) 8398 || !isMeasurementUpToDate(child.getMeasuredHeight(), heightSpec, lp.height); 8399 } 8400 8401 // we may consider making this public 8402 /** 8403 * RecyclerView internally does its own View measurement caching which should help with 8404 * WRAP_CONTENT. 8405 * <p> 8406 * Use this method if the View is not yet measured and you need to decide whether to 8407 * measure this View or not. 8408 */ 8409 boolean shouldMeasureChild(View child, int widthSpec, int heightSpec, LayoutParams lp) { 8410 return child.isLayoutRequested() 8411 || !mMeasurementCacheEnabled 8412 || !isMeasurementUpToDate(child.getWidth(), widthSpec, lp.width) 8413 || !isMeasurementUpToDate(child.getHeight(), heightSpec, lp.height); 8414 } 8415 8416 /** 8417 * In addition to the View Framework's measurement cache, RecyclerView uses its own 8418 * additional measurement cache for its children to avoid re-measuring them when not 8419 * necessary. It is on by default but it can be turned off via 8420 * {@link #setMeasurementCacheEnabled(boolean)}. 8421 * 8422 * @return True if measurement cache is enabled, false otherwise. 8423 * 8424 * @see #setMeasurementCacheEnabled(boolean) 8425 */ 8426 public boolean isMeasurementCacheEnabled() { 8427 return mMeasurementCacheEnabled; 8428 } 8429 8430 /** 8431 * Sets whether RecyclerView should use its own measurement cache for the children. This is 8432 * a more aggressive cache than the framework uses. 8433 * 8434 * @param measurementCacheEnabled True to enable the measurement cache, false otherwise. 8435 * 8436 * @see #isMeasurementCacheEnabled() 8437 */ 8438 public void setMeasurementCacheEnabled(boolean measurementCacheEnabled) { 8439 mMeasurementCacheEnabled = measurementCacheEnabled; 8440 } 8441 8442 private static boolean isMeasurementUpToDate(int childSize, int spec, int dimension) { 8443 final int specMode = MeasureSpec.getMode(spec); 8444 final int specSize = MeasureSpec.getSize(spec); 8445 if (dimension > 0 && childSize != dimension) { 8446 return false; 8447 } 8448 switch (specMode) { 8449 case MeasureSpec.UNSPECIFIED: 8450 return true; 8451 case MeasureSpec.AT_MOST: 8452 return specSize >= childSize; 8453 case MeasureSpec.EXACTLY: 8454 return specSize == childSize; 8455 } 8456 return false; 8457 } 8458 8459 /** 8460 * Measure a child view using standard measurement policy, taking the padding 8461 * of the parent RecyclerView, any added item decorations and the child margins 8462 * into account. 8463 * 8464 * <p>If the RecyclerView can be scrolled in either dimension the caller may 8465 * pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p> 8466 * 8467 * @param child Child view to measure 8468 * @param widthUsed Width in pixels currently consumed by other views, if relevant 8469 * @param heightUsed Height in pixels currently consumed by other views, if relevant 8470 */ 8471 public void measureChildWithMargins(View child, int widthUsed, int heightUsed) { 8472 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 8473 8474 final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child); 8475 widthUsed += insets.left + insets.right; 8476 heightUsed += insets.top + insets.bottom; 8477 8478 final int widthSpec = getChildMeasureSpec(getWidth(), getWidthMode(), 8479 getPaddingLeft() + getPaddingRight() + 8480 lp.leftMargin + lp.rightMargin + widthUsed, lp.width, 8481 canScrollHorizontally()); 8482 final int heightSpec = getChildMeasureSpec(getHeight(), getHeightMode(), 8483 getPaddingTop() + getPaddingBottom() + 8484 lp.topMargin + lp.bottomMargin + heightUsed, lp.height, 8485 canScrollVertically()); 8486 if (shouldMeasureChild(child, widthSpec, heightSpec, lp)) { 8487 child.measure(widthSpec, heightSpec); 8488 } 8489 } 8490 8491 /** 8492 * Calculate a MeasureSpec value for measuring a child view in one dimension. 8493 * 8494 * @param parentSize Size of the parent view where the child will be placed 8495 * @param padding Total space currently consumed by other elements of the parent 8496 * @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT. 8497 * Generally obtained from the child view's LayoutParams 8498 * @param canScroll true if the parent RecyclerView can scroll in this dimension 8499 * 8500 * @return a MeasureSpec value for the child view 8501 * @deprecated use {@link #getChildMeasureSpec(int, int, int, int, boolean)} 8502 */ 8503 @Deprecated 8504 public static int getChildMeasureSpec(int parentSize, int padding, int childDimension, 8505 boolean canScroll) { 8506 int size = Math.max(0, parentSize - padding); 8507 int resultSize = 0; 8508 int resultMode = 0; 8509 if (canScroll) { 8510 if (childDimension >= 0) { 8511 resultSize = childDimension; 8512 resultMode = MeasureSpec.EXACTLY; 8513 } else { 8514 // MATCH_PARENT can't be applied since we can scroll in this dimension, wrap 8515 // instead using UNSPECIFIED. 8516 resultSize = 0; 8517 resultMode = MeasureSpec.UNSPECIFIED; 8518 } 8519 } else { 8520 if (childDimension >= 0) { 8521 resultSize = childDimension; 8522 resultMode = MeasureSpec.EXACTLY; 8523 } else if (childDimension == LayoutParams.MATCH_PARENT) { 8524 resultSize = size; 8525 // TODO this should be my spec. 8526 resultMode = MeasureSpec.EXACTLY; 8527 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 8528 resultSize = size; 8529 resultMode = MeasureSpec.AT_MOST; 8530 } 8531 } 8532 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 8533 } 8534 8535 /** 8536 * Calculate a MeasureSpec value for measuring a child view in one dimension. 8537 * 8538 * @param parentSize Size of the parent view where the child will be placed 8539 * @param parentMode The measurement spec mode of the parent 8540 * @param padding Total space currently consumed by other elements of parent 8541 * @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT. 8542 * Generally obtained from the child view's LayoutParams 8543 * @param canScroll true if the parent RecyclerView can scroll in this dimension 8544 * 8545 * @return a MeasureSpec value for the child view 8546 */ 8547 public static int getChildMeasureSpec(int parentSize, int parentMode, int padding, 8548 int childDimension, boolean canScroll) { 8549 int size = Math.max(0, parentSize - padding); 8550 int resultSize = 0; 8551 int resultMode = 0; 8552 if (canScroll) { 8553 if (childDimension >= 0) { 8554 resultSize = childDimension; 8555 resultMode = MeasureSpec.EXACTLY; 8556 } else if (childDimension == LayoutParams.MATCH_PARENT) { 8557 switch (parentMode) { 8558 case MeasureSpec.AT_MOST: 8559 case MeasureSpec.EXACTLY: 8560 resultSize = size; 8561 resultMode = parentMode; 8562 break; 8563 case MeasureSpec.UNSPECIFIED: 8564 resultSize = 0; 8565 resultMode = MeasureSpec.UNSPECIFIED; 8566 break; 8567 } 8568 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 8569 resultSize = 0; 8570 resultMode = MeasureSpec.UNSPECIFIED; 8571 } 8572 } else { 8573 if (childDimension >= 0) { 8574 resultSize = childDimension; 8575 resultMode = MeasureSpec.EXACTLY; 8576 } else if (childDimension == LayoutParams.MATCH_PARENT) { 8577 resultSize = size; 8578 resultMode = parentMode; 8579 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 8580 resultSize = size; 8581 if (parentMode == MeasureSpec.AT_MOST || parentMode == MeasureSpec.EXACTLY) { 8582 resultMode = MeasureSpec.AT_MOST; 8583 } else { 8584 resultMode = MeasureSpec.UNSPECIFIED; 8585 } 8586 8587 } 8588 } 8589 //noinspection WrongConstant 8590 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 8591 } 8592 8593 /** 8594 * Returns the measured width of the given child, plus the additional size of 8595 * any insets applied by {@link ItemDecoration ItemDecorations}. 8596 * 8597 * @param child Child view to query 8598 * @return child's measured width plus <code>ItemDecoration</code> insets 8599 * 8600 * @see View#getMeasuredWidth() 8601 */ 8602 public int getDecoratedMeasuredWidth(View child) { 8603 final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets; 8604 return child.getMeasuredWidth() + insets.left + insets.right; 8605 } 8606 8607 /** 8608 * Returns the measured height of the given child, plus the additional size of 8609 * any insets applied by {@link ItemDecoration ItemDecorations}. 8610 * 8611 * @param child Child view to query 8612 * @return child's measured height plus <code>ItemDecoration</code> insets 8613 * 8614 * @see View#getMeasuredHeight() 8615 */ 8616 public int getDecoratedMeasuredHeight(View child) { 8617 final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets; 8618 return child.getMeasuredHeight() + insets.top + insets.bottom; 8619 } 8620 8621 /** 8622 * Lay out the given child view within the RecyclerView using coordinates that 8623 * include any current {@link ItemDecoration ItemDecorations}. 8624 * 8625 * <p>LayoutManagers should prefer working in sizes and coordinates that include 8626 * item decoration insets whenever possible. This allows the LayoutManager to effectively 8627 * ignore decoration insets within measurement and layout code. See the following 8628 * methods:</p> 8629 * <ul> 8630 * <li>{@link #layoutDecoratedWithMargins(View, int, int, int, int)}</li> 8631 * <li>{@link #getDecoratedBoundsWithMargins(View, Rect)}</li> 8632 * <li>{@link #measureChild(View, int, int)}</li> 8633 * <li>{@link #measureChildWithMargins(View, int, int)}</li> 8634 * <li>{@link #getDecoratedLeft(View)}</li> 8635 * <li>{@link #getDecoratedTop(View)}</li> 8636 * <li>{@link #getDecoratedRight(View)}</li> 8637 * <li>{@link #getDecoratedBottom(View)}</li> 8638 * <li>{@link #getDecoratedMeasuredWidth(View)}</li> 8639 * <li>{@link #getDecoratedMeasuredHeight(View)}</li> 8640 * </ul> 8641 * 8642 * @param child Child to lay out 8643 * @param left Left edge, with item decoration insets included 8644 * @param top Top edge, with item decoration insets included 8645 * @param right Right edge, with item decoration insets included 8646 * @param bottom Bottom edge, with item decoration insets included 8647 * 8648 * @see View#layout(int, int, int, int) 8649 * @see #layoutDecoratedWithMargins(View, int, int, int, int) 8650 */ 8651 public void layoutDecorated(View child, int left, int top, int right, int bottom) { 8652 final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets; 8653 child.layout(left + insets.left, top + insets.top, right - insets.right, 8654 bottom - insets.bottom); 8655 } 8656 8657 /** 8658 * Lay out the given child view within the RecyclerView using coordinates that 8659 * include any current {@link ItemDecoration ItemDecorations} and margins. 8660 * 8661 * <p>LayoutManagers should prefer working in sizes and coordinates that include 8662 * item decoration insets whenever possible. This allows the LayoutManager to effectively 8663 * ignore decoration insets within measurement and layout code. See the following 8664 * methods:</p> 8665 * <ul> 8666 * <li>{@link #layoutDecorated(View, int, int, int, int)}</li> 8667 * <li>{@link #measureChild(View, int, int)}</li> 8668 * <li>{@link #measureChildWithMargins(View, int, int)}</li> 8669 * <li>{@link #getDecoratedLeft(View)}</li> 8670 * <li>{@link #getDecoratedTop(View)}</li> 8671 * <li>{@link #getDecoratedRight(View)}</li> 8672 * <li>{@link #getDecoratedBottom(View)}</li> 8673 * <li>{@link #getDecoratedMeasuredWidth(View)}</li> 8674 * <li>{@link #getDecoratedMeasuredHeight(View)}</li> 8675 * </ul> 8676 * 8677 * @param child Child to lay out 8678 * @param left Left edge, with item decoration insets and left margin included 8679 * @param top Top edge, with item decoration insets and top margin included 8680 * @param right Right edge, with item decoration insets and right margin included 8681 * @param bottom Bottom edge, with item decoration insets and bottom margin included 8682 * 8683 * @see View#layout(int, int, int, int) 8684 * @see #layoutDecorated(View, int, int, int, int) 8685 */ 8686 public void layoutDecoratedWithMargins(View child, int left, int top, int right, 8687 int bottom) { 8688 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 8689 final Rect insets = lp.mDecorInsets; 8690 child.layout(left + insets.left + lp.leftMargin, top + insets.top + lp.topMargin, 8691 right - insets.right - lp.rightMargin, 8692 bottom - insets.bottom - lp.bottomMargin); 8693 } 8694 8695 /** 8696 * Calculates the bounding box of the View while taking into account its matrix changes 8697 * (translation, scale etc) with respect to the RecyclerView. 8698 * <p> 8699 * If {@code includeDecorInsets} is {@code true}, they are applied first before applying 8700 * the View's matrix so that the decor offsets also go through the same transformation. 8701 * 8702 * @param child The ItemView whose bounding box should be calculated. 8703 * @param includeDecorInsets True if the decor insets should be included in the bounding box 8704 * @param out The rectangle into which the output will be written. 8705 */ 8706 public void getTransformedBoundingBox(View child, boolean includeDecorInsets, Rect out) { 8707 if (includeDecorInsets) { 8708 Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets; 8709 out.set(-insets.left, -insets.top, 8710 child.getWidth() + insets.right, child.getHeight() + insets.bottom); 8711 } else { 8712 out.set(0, 0, child.getWidth(), child.getHeight()); 8713 } 8714 8715 if (mRecyclerView != null) { 8716 final Matrix childMatrix = ViewCompat.getMatrix(child); 8717 if (childMatrix != null && !childMatrix.isIdentity()) { 8718 final RectF tempRectF = mRecyclerView.mTempRectF; 8719 tempRectF.set(out); 8720 childMatrix.mapRect(tempRectF); 8721 out.set( 8722 (int) Math.floor(tempRectF.left), 8723 (int) Math.floor(tempRectF.top), 8724 (int) Math.ceil(tempRectF.right), 8725 (int) Math.ceil(tempRectF.bottom) 8726 ); 8727 } 8728 } 8729 out.offset(child.getLeft(), child.getTop()); 8730 } 8731 8732 /** 8733 * Returns the bounds of the view including its decoration and margins. 8734 * 8735 * @param view The view element to check 8736 * @param outBounds A rect that will receive the bounds of the element including its 8737 * decoration and margins. 8738 */ 8739 public void getDecoratedBoundsWithMargins(View view, Rect outBounds) { 8740 RecyclerView.getDecoratedBoundsWithMarginsInt(view, outBounds); 8741 } 8742 8743 /** 8744 * Returns the left edge of the given child view within its parent, offset by any applied 8745 * {@link ItemDecoration ItemDecorations}. 8746 * 8747 * @param child Child to query 8748 * @return Child left edge with offsets applied 8749 * @see #getLeftDecorationWidth(View) 8750 */ 8751 public int getDecoratedLeft(View child) { 8752 return child.getLeft() - getLeftDecorationWidth(child); 8753 } 8754 8755 /** 8756 * Returns the top edge of the given child view within its parent, offset by any applied 8757 * {@link ItemDecoration ItemDecorations}. 8758 * 8759 * @param child Child to query 8760 * @return Child top edge with offsets applied 8761 * @see #getTopDecorationHeight(View) 8762 */ 8763 public int getDecoratedTop(View child) { 8764 return child.getTop() - getTopDecorationHeight(child); 8765 } 8766 8767 /** 8768 * Returns the right edge of the given child view within its parent, offset by any applied 8769 * {@link ItemDecoration ItemDecorations}. 8770 * 8771 * @param child Child to query 8772 * @return Child right edge with offsets applied 8773 * @see #getRightDecorationWidth(View) 8774 */ 8775 public int getDecoratedRight(View child) { 8776 return child.getRight() + getRightDecorationWidth(child); 8777 } 8778 8779 /** 8780 * Returns the bottom edge of the given child view within its parent, offset by any applied 8781 * {@link ItemDecoration ItemDecorations}. 8782 * 8783 * @param child Child to query 8784 * @return Child bottom edge with offsets applied 8785 * @see #getBottomDecorationHeight(View) 8786 */ 8787 public int getDecoratedBottom(View child) { 8788 return child.getBottom() + getBottomDecorationHeight(child); 8789 } 8790 8791 /** 8792 * Calculates the item decor insets applied to the given child and updates the provided 8793 * Rect instance with the inset values. 8794 * <ul> 8795 * <li>The Rect's left is set to the total width of left decorations.</li> 8796 * <li>The Rect's top is set to the total height of top decorations.</li> 8797 * <li>The Rect's right is set to the total width of right decorations.</li> 8798 * <li>The Rect's bottom is set to total height of bottom decorations.</li> 8799 * </ul> 8800 * <p> 8801 * Note that item decorations are automatically calculated when one of the LayoutManager's 8802 * measure child methods is called. If you need to measure the child with custom specs via 8803 * {@link View#measure(int, int)}, you can use this method to get decorations. 8804 * 8805 * @param child The child view whose decorations should be calculated 8806 * @param outRect The Rect to hold result values 8807 */ 8808 public void calculateItemDecorationsForChild(View child, Rect outRect) { 8809 if (mRecyclerView == null) { 8810 outRect.set(0, 0, 0, 0); 8811 return; 8812 } 8813 Rect insets = mRecyclerView.getItemDecorInsetsForChild(child); 8814 outRect.set(insets); 8815 } 8816 8817 /** 8818 * Returns the total height of item decorations applied to child's top. 8819 * <p> 8820 * Note that this value is not updated until the View is measured or 8821 * {@link #calculateItemDecorationsForChild(View, Rect)} is called. 8822 * 8823 * @param child Child to query 8824 * @return The total height of item decorations applied to the child's top. 8825 * @see #getDecoratedTop(View) 8826 * @see #calculateItemDecorationsForChild(View, Rect) 8827 */ 8828 public int getTopDecorationHeight(View child) { 8829 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.top; 8830 } 8831 8832 /** 8833 * Returns the total height of item decorations applied to child's bottom. 8834 * <p> 8835 * Note that this value is not updated until the View is measured or 8836 * {@link #calculateItemDecorationsForChild(View, Rect)} is called. 8837 * 8838 * @param child Child to query 8839 * @return The total height of item decorations applied to the child's bottom. 8840 * @see #getDecoratedBottom(View) 8841 * @see #calculateItemDecorationsForChild(View, Rect) 8842 */ 8843 public int getBottomDecorationHeight(View child) { 8844 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.bottom; 8845 } 8846 8847 /** 8848 * Returns the total width of item decorations applied to child's left. 8849 * <p> 8850 * Note that this value is not updated until the View is measured or 8851 * {@link #calculateItemDecorationsForChild(View, Rect)} is called. 8852 * 8853 * @param child Child to query 8854 * @return The total width of item decorations applied to the child's left. 8855 * @see #getDecoratedLeft(View) 8856 * @see #calculateItemDecorationsForChild(View, Rect) 8857 */ 8858 public int getLeftDecorationWidth(View child) { 8859 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.left; 8860 } 8861 8862 /** 8863 * Returns the total width of item decorations applied to child's right. 8864 * <p> 8865 * Note that this value is not updated until the View is measured or 8866 * {@link #calculateItemDecorationsForChild(View, Rect)} is called. 8867 * 8868 * @param child Child to query 8869 * @return The total width of item decorations applied to the child's right. 8870 * @see #getDecoratedRight(View) 8871 * @see #calculateItemDecorationsForChild(View, Rect) 8872 */ 8873 public int getRightDecorationWidth(View child) { 8874 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.right; 8875 } 8876 8877 /** 8878 * Called when searching for a focusable view in the given direction has failed 8879 * for the current content of the RecyclerView. 8880 * 8881 * <p>This is the LayoutManager's opportunity to populate views in the given direction 8882 * to fulfill the request if it can. The LayoutManager should attach and return 8883 * the view to be focused. The default implementation returns null.</p> 8884 * 8885 * @param focused The currently focused view 8886 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 8887 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, 8888 * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} 8889 * or 0 for not applicable 8890 * @param recycler The recycler to use for obtaining views for currently offscreen items 8891 * @param state Transient state of RecyclerView 8892 * @return The chosen view to be focused 8893 */ 8894 @Nullable 8895 public View onFocusSearchFailed(View focused, int direction, Recycler recycler, 8896 State state) { 8897 return null; 8898 } 8899 8900 /** 8901 * This method gives a LayoutManager an opportunity to intercept the initial focus search 8902 * before the default behavior of {@link FocusFinder} is used. If this method returns 8903 * null FocusFinder will attempt to find a focusable child view. If it fails 8904 * then {@link #onFocusSearchFailed(View, int, RecyclerView.Recycler, RecyclerView.State)} 8905 * will be called to give the LayoutManager an opportunity to add new views for items 8906 * that did not have attached views representing them. The LayoutManager should not add 8907 * or remove views from this method. 8908 * 8909 * @param focused The currently focused view 8910 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 8911 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, 8912 * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} 8913 * @return A descendant view to focus or null to fall back to default behavior. 8914 * The default implementation returns null. 8915 */ 8916 public View onInterceptFocusSearch(View focused, int direction) { 8917 return null; 8918 } 8919 8920 /** 8921 * Called when a child of the RecyclerView wants a particular rectangle to be positioned 8922 * onto the screen. See {@link ViewParent#requestChildRectangleOnScreen(android.view.View, 8923 * android.graphics.Rect, boolean)} for more details. 8924 * 8925 * <p>The base implementation will attempt to perform a standard programmatic scroll 8926 * to bring the given rect into view, within the padded area of the RecyclerView.</p> 8927 * 8928 * @param child The direct child making the request. 8929 * @param rect The rectangle in the child's coordinates the child 8930 * wishes to be on the screen. 8931 * @param immediate True to forbid animated or delayed scrolling, 8932 * false otherwise 8933 * @return Whether the group scrolled to handle the operation 8934 */ 8935 public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect, 8936 boolean immediate) { 8937 final int parentLeft = getPaddingLeft(); 8938 final int parentTop = getPaddingTop(); 8939 final int parentRight = getWidth() - getPaddingRight(); 8940 final int parentBottom = getHeight() - getPaddingBottom(); 8941 final int childLeft = child.getLeft() + rect.left - child.getScrollX(); 8942 final int childTop = child.getTop() + rect.top - child.getScrollY(); 8943 final int childRight = childLeft + rect.width(); 8944 final int childBottom = childTop + rect.height(); 8945 8946 final int offScreenLeft = Math.min(0, childLeft - parentLeft); 8947 final int offScreenTop = Math.min(0, childTop - parentTop); 8948 final int offScreenRight = Math.max(0, childRight - parentRight); 8949 final int offScreenBottom = Math.max(0, childBottom - parentBottom); 8950 8951 // Favor the "start" layout direction over the end when bringing one side or the other 8952 // of a large rect into view. If we decide to bring in end because start is already 8953 // visible, limit the scroll such that start won't go out of bounds. 8954 final int dx; 8955 if (getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL) { 8956 dx = offScreenRight != 0 ? offScreenRight 8957 : Math.max(offScreenLeft, childRight - parentRight); 8958 } else { 8959 dx = offScreenLeft != 0 ? offScreenLeft 8960 : Math.min(childLeft - parentLeft, offScreenRight); 8961 } 8962 8963 // Favor bringing the top into view over the bottom. If top is already visible and 8964 // we should scroll to make bottom visible, make sure top does not go out of bounds. 8965 final int dy = offScreenTop != 0 ? offScreenTop 8966 : Math.min(childTop - parentTop, offScreenBottom); 8967 8968 if (dx != 0 || dy != 0) { 8969 if (immediate) { 8970 parent.scrollBy(dx, dy); 8971 } else { 8972 parent.smoothScrollBy(dx, dy); 8973 } 8974 return true; 8975 } 8976 return false; 8977 } 8978 8979 /** 8980 * @deprecated Use {@link #onRequestChildFocus(RecyclerView, State, View, View)} 8981 */ 8982 @Deprecated 8983 public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) { 8984 // eat the request if we are in the middle of a scroll or layout 8985 return isSmoothScrolling() || parent.isComputingLayout(); 8986 } 8987 8988 /** 8989 * Called when a descendant view of the RecyclerView requests focus. 8990 * 8991 * <p>A LayoutManager wishing to keep focused views aligned in a specific 8992 * portion of the view may implement that behavior in an override of this method.</p> 8993 * 8994 * <p>If the LayoutManager executes different behavior that should override the default 8995 * behavior of scrolling the focused child on screen instead of running alongside it, 8996 * this method should return true.</p> 8997 * 8998 * @param parent The RecyclerView hosting this LayoutManager 8999 * @param state Current state of RecyclerView 9000 * @param child Direct child of the RecyclerView containing the newly focused view 9001 * @param focused The newly focused view. This may be the same view as child or it may be 9002 * null 9003 * @return true if the default scroll behavior should be suppressed 9004 */ 9005 public boolean onRequestChildFocus(RecyclerView parent, State state, View child, 9006 View focused) { 9007 return onRequestChildFocus(parent, child, focused); 9008 } 9009 9010 /** 9011 * Called if the RecyclerView this LayoutManager is bound to has a different adapter set. 9012 * The LayoutManager may use this opportunity to clear caches and configure state such 9013 * that it can relayout appropriately with the new data and potentially new view types. 9014 * 9015 * <p>The default implementation removes all currently attached views.</p> 9016 * 9017 * @param oldAdapter The previous adapter instance. Will be null if there was previously no 9018 * adapter. 9019 * @param newAdapter The new adapter instance. Might be null if 9020 * {@link #setAdapter(RecyclerView.Adapter)} is called with {@code null}. 9021 */ 9022 public void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) { 9023 } 9024 9025 /** 9026 * Called to populate focusable views within the RecyclerView. 9027 * 9028 * <p>The LayoutManager implementation should return <code>true</code> if the default 9029 * behavior of {@link ViewGroup#addFocusables(java.util.ArrayList, int)} should be 9030 * suppressed.</p> 9031 * 9032 * <p>The default implementation returns <code>false</code> to trigger RecyclerView 9033 * to fall back to the default ViewGroup behavior.</p> 9034 * 9035 * @param recyclerView The RecyclerView hosting this LayoutManager 9036 * @param views List of output views. This method should add valid focusable views 9037 * to this list. 9038 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 9039 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, 9040 * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} 9041 * @param focusableMode The type of focusables to be added. 9042 * 9043 * @return true to suppress the default behavior, false to add default focusables after 9044 * this method returns. 9045 * 9046 * @see #FOCUSABLES_ALL 9047 * @see #FOCUSABLES_TOUCH_MODE 9048 */ 9049 public boolean onAddFocusables(RecyclerView recyclerView, ArrayList<View> views, 9050 int direction, int focusableMode) { 9051 return false; 9052 } 9053 9054 /** 9055 * Called when {@link Adapter#notifyDataSetChanged()} is triggered instead of giving 9056 * detailed information on what has actually changed. 9057 * 9058 * @param recyclerView 9059 */ 9060 public void onItemsChanged(RecyclerView recyclerView) { 9061 } 9062 9063 /** 9064 * Called when items have been added to the adapter. The LayoutManager may choose to 9065 * requestLayout if the inserted items would require refreshing the currently visible set 9066 * of child views. (e.g. currently empty space would be filled by appended items, etc.) 9067 * 9068 * @param recyclerView 9069 * @param positionStart 9070 * @param itemCount 9071 */ 9072 public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { 9073 } 9074 9075 /** 9076 * Called when items have been removed from the adapter. 9077 * 9078 * @param recyclerView 9079 * @param positionStart 9080 * @param itemCount 9081 */ 9082 public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) { 9083 } 9084 9085 /** 9086 * Called when items have been changed in the adapter. 9087 * To receive payload, override {@link #onItemsUpdated(RecyclerView, int, int, Object)} 9088 * instead, then this callback will not be invoked. 9089 * 9090 * @param recyclerView 9091 * @param positionStart 9092 * @param itemCount 9093 */ 9094 public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) { 9095 } 9096 9097 /** 9098 * Called when items have been changed in the adapter and with optional payload. 9099 * Default implementation calls {@link #onItemsUpdated(RecyclerView, int, int)}. 9100 * 9101 * @param recyclerView 9102 * @param positionStart 9103 * @param itemCount 9104 * @param payload 9105 */ 9106 public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount, 9107 Object payload) { 9108 onItemsUpdated(recyclerView, positionStart, itemCount); 9109 } 9110 9111 /** 9112 * Called when an item is moved withing the adapter. 9113 * <p> 9114 * Note that, an item may also change position in response to another ADD/REMOVE/MOVE 9115 * operation. This callback is only called if and only if {@link Adapter#notifyItemMoved} 9116 * is called. 9117 * 9118 * @param recyclerView 9119 * @param from 9120 * @param to 9121 * @param itemCount 9122 */ 9123 public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) { 9124 9125 } 9126 9127 9128 /** 9129 * <p>Override this method if you want to support scroll bars.</p> 9130 * 9131 * <p>Read {@link RecyclerView#computeHorizontalScrollExtent()} for details.</p> 9132 * 9133 * <p>Default implementation returns 0.</p> 9134 * 9135 * @param state Current state of RecyclerView 9136 * @return The horizontal extent of the scrollbar's thumb 9137 * @see RecyclerView#computeHorizontalScrollExtent() 9138 */ 9139 public int computeHorizontalScrollExtent(State state) { 9140 return 0; 9141 } 9142 9143 /** 9144 * <p>Override this method if you want to support scroll bars.</p> 9145 * 9146 * <p>Read {@link RecyclerView#computeHorizontalScrollOffset()} for details.</p> 9147 * 9148 * <p>Default implementation returns 0.</p> 9149 * 9150 * @param state Current State of RecyclerView where you can find total item count 9151 * @return The horizontal offset of the scrollbar's thumb 9152 * @see RecyclerView#computeHorizontalScrollOffset() 9153 */ 9154 public int computeHorizontalScrollOffset(State state) { 9155 return 0; 9156 } 9157 9158 /** 9159 * <p>Override this method if you want to support scroll bars.</p> 9160 * 9161 * <p>Read {@link RecyclerView#computeHorizontalScrollRange()} for details.</p> 9162 * 9163 * <p>Default implementation returns 0.</p> 9164 * 9165 * @param state Current State of RecyclerView where you can find total item count 9166 * @return The total horizontal range represented by the vertical scrollbar 9167 * @see RecyclerView#computeHorizontalScrollRange() 9168 */ 9169 public int computeHorizontalScrollRange(State state) { 9170 return 0; 9171 } 9172 9173 /** 9174 * <p>Override this method if you want to support scroll bars.</p> 9175 * 9176 * <p>Read {@link RecyclerView#computeVerticalScrollExtent()} for details.</p> 9177 * 9178 * <p>Default implementation returns 0.</p> 9179 * 9180 * @param state Current state of RecyclerView 9181 * @return The vertical extent of the scrollbar's thumb 9182 * @see RecyclerView#computeVerticalScrollExtent() 9183 */ 9184 public int computeVerticalScrollExtent(State state) { 9185 return 0; 9186 } 9187 9188 /** 9189 * <p>Override this method if you want to support scroll bars.</p> 9190 * 9191 * <p>Read {@link RecyclerView#computeVerticalScrollOffset()} for details.</p> 9192 * 9193 * <p>Default implementation returns 0.</p> 9194 * 9195 * @param state Current State of RecyclerView where you can find total item count 9196 * @return The vertical offset of the scrollbar's thumb 9197 * @see RecyclerView#computeVerticalScrollOffset() 9198 */ 9199 public int computeVerticalScrollOffset(State state) { 9200 return 0; 9201 } 9202 9203 /** 9204 * <p>Override this method if you want to support scroll bars.</p> 9205 * 9206 * <p>Read {@link RecyclerView#computeVerticalScrollRange()} for details.</p> 9207 * 9208 * <p>Default implementation returns 0.</p> 9209 * 9210 * @param state Current State of RecyclerView where you can find total item count 9211 * @return The total vertical range represented by the vertical scrollbar 9212 * @see RecyclerView#computeVerticalScrollRange() 9213 */ 9214 public int computeVerticalScrollRange(State state) { 9215 return 0; 9216 } 9217 9218 /** 9219 * Measure the attached RecyclerView. Implementations must call 9220 * {@link #setMeasuredDimension(int, int)} before returning. 9221 * 9222 * <p>The default implementation will handle EXACTLY measurements and respect 9223 * the minimum width and height properties of the host RecyclerView if measured 9224 * as UNSPECIFIED. AT_MOST measurements will be treated as EXACTLY and the RecyclerView 9225 * will consume all available space.</p> 9226 * 9227 * @param recycler Recycler 9228 * @param state Transient state of RecyclerView 9229 * @param widthSpec Width {@link android.view.View.MeasureSpec} 9230 * @param heightSpec Height {@link android.view.View.MeasureSpec} 9231 */ 9232 public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) { 9233 mRecyclerView.defaultOnMeasure(widthSpec, heightSpec); 9234 } 9235 9236 /** 9237 * {@link View#setMeasuredDimension(int, int) Set the measured dimensions} of the 9238 * host RecyclerView. 9239 * 9240 * @param widthSize Measured width 9241 * @param heightSize Measured height 9242 */ 9243 public void setMeasuredDimension(int widthSize, int heightSize) { 9244 mRecyclerView.setMeasuredDimension(widthSize, heightSize); 9245 } 9246 9247 /** 9248 * @return The host RecyclerView's {@link View#getMinimumWidth()} 9249 */ 9250 public int getMinimumWidth() { 9251 return ViewCompat.getMinimumWidth(mRecyclerView); 9252 } 9253 9254 /** 9255 * @return The host RecyclerView's {@link View#getMinimumHeight()} 9256 */ 9257 public int getMinimumHeight() { 9258 return ViewCompat.getMinimumHeight(mRecyclerView); 9259 } 9260 /** 9261 * <p>Called when the LayoutManager should save its state. This is a good time to save your 9262 * scroll position, configuration and anything else that may be required to restore the same 9263 * layout state if the LayoutManager is recreated.</p> 9264 * <p>RecyclerView does NOT verify if the LayoutManager has changed between state save and 9265 * restore. This will let you share information between your LayoutManagers but it is also 9266 * your responsibility to make sure they use the same parcelable class.</p> 9267 * 9268 * @return Necessary information for LayoutManager to be able to restore its state 9269 */ 9270 public Parcelable onSaveInstanceState() { 9271 return null; 9272 } 9273 9274 9275 public void onRestoreInstanceState(Parcelable state) { 9276 9277 } 9278 9279 void stopSmoothScroller() { 9280 if (mSmoothScroller != null) { 9281 mSmoothScroller.stop(); 9282 } 9283 } 9284 9285 private void onSmoothScrollerStopped(SmoothScroller smoothScroller) { 9286 if (mSmoothScroller == smoothScroller) { 9287 mSmoothScroller = null; 9288 } 9289 } 9290 9291 /** 9292 * RecyclerView calls this method to notify LayoutManager that scroll state has changed. 9293 * 9294 * @param state The new scroll state for RecyclerView 9295 */ 9296 public void onScrollStateChanged(int state) { 9297 } 9298 9299 /** 9300 * Removes all views and recycles them using the given recycler. 9301 * <p> 9302 * If you want to clean cached views as well, you should call {@link Recycler#clear()} too. 9303 * <p> 9304 * If a View is marked as "ignored", it is not removed nor recycled. 9305 * 9306 * @param recycler Recycler to use to recycle children 9307 * @see #removeAndRecycleView(View, Recycler) 9308 * @see #removeAndRecycleViewAt(int, Recycler) 9309 * @see #ignoreView(View) 9310 */ 9311 public void removeAndRecycleAllViews(Recycler recycler) { 9312 for (int i = getChildCount() - 1; i >= 0; i--) { 9313 final View view = getChildAt(i); 9314 if (!getChildViewHolderInt(view).shouldIgnore()) { 9315 removeAndRecycleViewAt(i, recycler); 9316 } 9317 } 9318 } 9319 9320 // called by accessibility delegate 9321 void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfoCompat info) { 9322 onInitializeAccessibilityNodeInfo(mRecyclerView.mRecycler, mRecyclerView.mState, info); 9323 } 9324 9325 /** 9326 * Called by the AccessibilityDelegate when the information about the current layout should 9327 * be populated. 9328 * <p> 9329 * Default implementation adds a {@link 9330 * android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat}. 9331 * <p> 9332 * You should override 9333 * {@link #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)}, 9334 * {@link #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)}, 9335 * {@link #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)} and 9336 * {@link #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)} for 9337 * more accurate accessibility information. 9338 * 9339 * @param recycler The Recycler that can be used to convert view positions into adapter 9340 * positions 9341 * @param state The current state of RecyclerView 9342 * @param info The info that should be filled by the LayoutManager 9343 * @see View#onInitializeAccessibilityNodeInfo( 9344 *android.view.accessibility.AccessibilityNodeInfo) 9345 * @see #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State) 9346 * @see #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State) 9347 * @see #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State) 9348 * @see #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State) 9349 */ 9350 public void onInitializeAccessibilityNodeInfo(Recycler recycler, State state, 9351 AccessibilityNodeInfoCompat info) { 9352 if (ViewCompat.canScrollVertically(mRecyclerView, -1) || 9353 ViewCompat.canScrollHorizontally(mRecyclerView, -1)) { 9354 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD); 9355 info.setScrollable(true); 9356 } 9357 if (ViewCompat.canScrollVertically(mRecyclerView, 1) || 9358 ViewCompat.canScrollHorizontally(mRecyclerView, 1)) { 9359 info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD); 9360 info.setScrollable(true); 9361 } 9362 final AccessibilityNodeInfoCompat.CollectionInfoCompat collectionInfo 9363 = AccessibilityNodeInfoCompat.CollectionInfoCompat 9364 .obtain(getRowCountForAccessibility(recycler, state), 9365 getColumnCountForAccessibility(recycler, state), 9366 isLayoutHierarchical(recycler, state), 9367 getSelectionModeForAccessibility(recycler, state)); 9368 info.setCollectionInfo(collectionInfo); 9369 } 9370 9371 // called by accessibility delegate 9372 public void onInitializeAccessibilityEvent(AccessibilityEvent event) { 9373 onInitializeAccessibilityEvent(mRecyclerView.mRecycler, mRecyclerView.mState, event); 9374 } 9375 9376 /** 9377 * Called by the accessibility delegate to initialize an accessibility event. 9378 * <p> 9379 * Default implementation adds item count and scroll information to the event. 9380 * 9381 * @param recycler The Recycler that can be used to convert view positions into adapter 9382 * positions 9383 * @param state The current state of RecyclerView 9384 * @param event The event instance to initialize 9385 * @see View#onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent) 9386 */ 9387 public void onInitializeAccessibilityEvent(Recycler recycler, State state, 9388 AccessibilityEvent event) { 9389 final AccessibilityRecordCompat record = AccessibilityEventCompat 9390 .asRecord(event); 9391 if (mRecyclerView == null || record == null) { 9392 return; 9393 } 9394 record.setScrollable(ViewCompat.canScrollVertically(mRecyclerView, 1) 9395 || ViewCompat.canScrollVertically(mRecyclerView, -1) 9396 || ViewCompat.canScrollHorizontally(mRecyclerView, -1) 9397 || ViewCompat.canScrollHorizontally(mRecyclerView, 1)); 9398 9399 if (mRecyclerView.mAdapter != null) { 9400 record.setItemCount(mRecyclerView.mAdapter.getItemCount()); 9401 } 9402 } 9403 9404 // called by accessibility delegate 9405 void onInitializeAccessibilityNodeInfoForItem(View host, AccessibilityNodeInfoCompat info) { 9406 final ViewHolder vh = getChildViewHolderInt(host); 9407 // avoid trying to create accessibility node info for removed children 9408 if (vh != null && !vh.isRemoved() && !mChildHelper.isHidden(vh.itemView)) { 9409 onInitializeAccessibilityNodeInfoForItem(mRecyclerView.mRecycler, 9410 mRecyclerView.mState, host, info); 9411 } 9412 } 9413 9414 /** 9415 * Called by the AccessibilityDelegate when the accessibility information for a specific 9416 * item should be populated. 9417 * <p> 9418 * Default implementation adds basic positioning information about the item. 9419 * 9420 * @param recycler The Recycler that can be used to convert view positions into adapter 9421 * positions 9422 * @param state The current state of RecyclerView 9423 * @param host The child for which accessibility node info should be populated 9424 * @param info The info to fill out about the item 9425 * @see android.widget.AbsListView#onInitializeAccessibilityNodeInfoForItem(View, int, 9426 * android.view.accessibility.AccessibilityNodeInfo) 9427 */ 9428 public void onInitializeAccessibilityNodeInfoForItem(Recycler recycler, State state, 9429 View host, AccessibilityNodeInfoCompat info) { 9430 int rowIndexGuess = canScrollVertically() ? getPosition(host) : 0; 9431 int columnIndexGuess = canScrollHorizontally() ? getPosition(host) : 0; 9432 final AccessibilityNodeInfoCompat.CollectionItemInfoCompat itemInfo 9433 = AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(rowIndexGuess, 1, 9434 columnIndexGuess, 1, false, false); 9435 info.setCollectionItemInfo(itemInfo); 9436 } 9437 9438 /** 9439 * A LayoutManager can call this method to force RecyclerView to run simple animations in 9440 * the next layout pass, even if there is not any trigger to do so. (e.g. adapter data 9441 * change). 9442 * <p> 9443 * Note that, calling this method will not guarantee that RecyclerView will run animations 9444 * at all. For example, if there is not any {@link ItemAnimator} set, RecyclerView will 9445 * not run any animations but will still clear this flag after the layout is complete. 9446 * 9447 */ 9448 public void requestSimpleAnimationsInNextLayout() { 9449 mRequestedSimpleAnimations = true; 9450 } 9451 9452 /** 9453 * Returns the selection mode for accessibility. Should be 9454 * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}, 9455 * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_SINGLE} or 9456 * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_MULTIPLE}. 9457 * <p> 9458 * Default implementation returns 9459 * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}. 9460 * 9461 * @param recycler The Recycler that can be used to convert view positions into adapter 9462 * positions 9463 * @param state The current state of RecyclerView 9464 * @return Selection mode for accessibility. Default implementation returns 9465 * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}. 9466 */ 9467 public int getSelectionModeForAccessibility(Recycler recycler, State state) { 9468 return AccessibilityNodeInfoCompat.CollectionInfoCompat.SELECTION_MODE_NONE; 9469 } 9470 9471 /** 9472 * Returns the number of rows for accessibility. 9473 * <p> 9474 * Default implementation returns the number of items in the adapter if LayoutManager 9475 * supports vertical scrolling or 1 if LayoutManager does not support vertical 9476 * scrolling. 9477 * 9478 * @param recycler The Recycler that can be used to convert view positions into adapter 9479 * positions 9480 * @param state The current state of RecyclerView 9481 * @return The number of rows in LayoutManager for accessibility. 9482 */ 9483 public int getRowCountForAccessibility(Recycler recycler, State state) { 9484 if (mRecyclerView == null || mRecyclerView.mAdapter == null) { 9485 return 1; 9486 } 9487 return canScrollVertically() ? mRecyclerView.mAdapter.getItemCount() : 1; 9488 } 9489 9490 /** 9491 * Returns the number of columns for accessibility. 9492 * <p> 9493 * Default implementation returns the number of items in the adapter if LayoutManager 9494 * supports horizontal scrolling or 1 if LayoutManager does not support horizontal 9495 * scrolling. 9496 * 9497 * @param recycler The Recycler that can be used to convert view positions into adapter 9498 * positions 9499 * @param state The current state of RecyclerView 9500 * @return The number of rows in LayoutManager for accessibility. 9501 */ 9502 public int getColumnCountForAccessibility(Recycler recycler, State state) { 9503 if (mRecyclerView == null || mRecyclerView.mAdapter == null) { 9504 return 1; 9505 } 9506 return canScrollHorizontally() ? mRecyclerView.mAdapter.getItemCount() : 1; 9507 } 9508 9509 /** 9510 * Returns whether layout is hierarchical or not to be used for accessibility. 9511 * <p> 9512 * Default implementation returns false. 9513 * 9514 * @param recycler The Recycler that can be used to convert view positions into adapter 9515 * positions 9516 * @param state The current state of RecyclerView 9517 * @return True if layout is hierarchical. 9518 */ 9519 public boolean isLayoutHierarchical(Recycler recycler, State state) { 9520 return false; 9521 } 9522 9523 // called by accessibility delegate 9524 boolean performAccessibilityAction(int action, Bundle args) { 9525 return performAccessibilityAction(mRecyclerView.mRecycler, mRecyclerView.mState, 9526 action, args); 9527 } 9528 9529 /** 9530 * Called by AccessibilityDelegate when an action is requested from the RecyclerView. 9531 * 9532 * @param recycler The Recycler that can be used to convert view positions into adapter 9533 * positions 9534 * @param state The current state of RecyclerView 9535 * @param action The action to perform 9536 * @param args Optional action arguments 9537 * @see View#performAccessibilityAction(int, android.os.Bundle) 9538 */ 9539 public boolean performAccessibilityAction(Recycler recycler, State state, int action, 9540 Bundle args) { 9541 if (mRecyclerView == null) { 9542 return false; 9543 } 9544 int vScroll = 0, hScroll = 0; 9545 switch (action) { 9546 case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD: 9547 if (ViewCompat.canScrollVertically(mRecyclerView, -1)) { 9548 vScroll = -(getHeight() - getPaddingTop() - getPaddingBottom()); 9549 } 9550 if (ViewCompat.canScrollHorizontally(mRecyclerView, -1)) { 9551 hScroll = -(getWidth() - getPaddingLeft() - getPaddingRight()); 9552 } 9553 break; 9554 case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD: 9555 if (ViewCompat.canScrollVertically(mRecyclerView, 1)) { 9556 vScroll = getHeight() - getPaddingTop() - getPaddingBottom(); 9557 } 9558 if (ViewCompat.canScrollHorizontally(mRecyclerView, 1)) { 9559 hScroll = getWidth() - getPaddingLeft() - getPaddingRight(); 9560 } 9561 break; 9562 } 9563 if (vScroll == 0 && hScroll == 0) { 9564 return false; 9565 } 9566 mRecyclerView.scrollBy(hScroll, vScroll); 9567 return true; 9568 } 9569 9570 // called by accessibility delegate 9571 boolean performAccessibilityActionForItem(View view, int action, Bundle args) { 9572 return performAccessibilityActionForItem(mRecyclerView.mRecycler, mRecyclerView.mState, 9573 view, action, args); 9574 } 9575 9576 /** 9577 * Called by AccessibilityDelegate when an accessibility action is requested on one of the 9578 * children of LayoutManager. 9579 * <p> 9580 * Default implementation does not do anything. 9581 * 9582 * @param recycler The Recycler that can be used to convert view positions into adapter 9583 * positions 9584 * @param state The current state of RecyclerView 9585 * @param view The child view on which the action is performed 9586 * @param action The action to perform 9587 * @param args Optional action arguments 9588 * @return true if action is handled 9589 * @see View#performAccessibilityAction(int, android.os.Bundle) 9590 */ 9591 public boolean performAccessibilityActionForItem(Recycler recycler, State state, View view, 9592 int action, Bundle args) { 9593 return false; 9594 } 9595 9596 /** 9597 * Parse the xml attributes to get the most common properties used by layout managers. 9598 * 9599 * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_android_orientation 9600 * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_spanCount 9601 * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_reverseLayout 9602 * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_stackFromEnd 9603 * 9604 * @return an object containing the properties as specified in the attrs. 9605 */ 9606 public static Properties getProperties(Context context, AttributeSet attrs, 9607 int defStyleAttr, int defStyleRes) { 9608 Properties properties = new Properties(); 9609 TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView, 9610 defStyleAttr, defStyleRes); 9611 properties.orientation = a.getInt(R.styleable.RecyclerView_android_orientation, VERTICAL); 9612 properties.spanCount = a.getInt(R.styleable.RecyclerView_spanCount, 1); 9613 properties.reverseLayout = a.getBoolean(R.styleable.RecyclerView_reverseLayout, false); 9614 properties.stackFromEnd = a.getBoolean(R.styleable.RecyclerView_stackFromEnd, false); 9615 a.recycle(); 9616 return properties; 9617 } 9618 9619 void setExactMeasureSpecsFrom(RecyclerView recyclerView) { 9620 setMeasureSpecs( 9621 MeasureSpec.makeMeasureSpec(recyclerView.getWidth(), MeasureSpec.EXACTLY), 9622 MeasureSpec.makeMeasureSpec(recyclerView.getHeight(), MeasureSpec.EXACTLY) 9623 ); 9624 } 9625 9626 /** 9627 * Internal API to allow LayoutManagers to be measured twice. 9628 * <p> 9629 * This is not public because LayoutManagers should be able to handle their layouts in one 9630 * pass but it is very convenient to make existing LayoutManagers support wrapping content 9631 * when both orientations are undefined. 9632 * <p> 9633 * This API will be removed after default LayoutManagers properly implement wrap content in 9634 * non-scroll orientation. 9635 */ 9636 boolean shouldMeasureTwice() { 9637 return false; 9638 } 9639 9640 boolean hasFlexibleChildInBothOrientations() { 9641 final int childCount = getChildCount(); 9642 for (int i = 0; i < childCount; i++) { 9643 final View child = getChildAt(i); 9644 final ViewGroup.LayoutParams lp = child.getLayoutParams(); 9645 if (lp.width < 0 && lp.height < 0) { 9646 return true; 9647 } 9648 } 9649 return false; 9650 } 9651 9652 /** 9653 * Some general properties that a LayoutManager may want to use. 9654 */ 9655 public static class Properties { 9656 /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_android_orientation */ 9657 public int orientation; 9658 /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_spanCount */ 9659 public int spanCount; 9660 /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_reverseLayout */ 9661 public boolean reverseLayout; 9662 /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_stackFromEnd */ 9663 public boolean stackFromEnd; 9664 } 9665 } 9666 9667 /** 9668 * An ItemDecoration allows the application to add a special drawing and layout offset 9669 * to specific item views from the adapter's data set. This can be useful for drawing dividers 9670 * between items, highlights, visual grouping boundaries and more. 9671 * 9672 * <p>All ItemDecorations are drawn in the order they were added, before the item 9673 * views (in {@link ItemDecoration#onDraw(Canvas, RecyclerView, RecyclerView.State) onDraw()} 9674 * and after the items (in {@link ItemDecoration#onDrawOver(Canvas, RecyclerView, 9675 * RecyclerView.State)}.</p> 9676 */ 9677 public static abstract class ItemDecoration { 9678 /** 9679 * Draw any appropriate decorations into the Canvas supplied to the RecyclerView. 9680 * Any content drawn by this method will be drawn before the item views are drawn, 9681 * and will thus appear underneath the views. 9682 * 9683 * @param c Canvas to draw into 9684 * @param parent RecyclerView this ItemDecoration is drawing into 9685 * @param state The current state of RecyclerView 9686 */ 9687 public void onDraw(Canvas c, RecyclerView parent, State state) { 9688 onDraw(c, parent); 9689 } 9690 9691 /** 9692 * @deprecated 9693 * Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)} 9694 */ 9695 @Deprecated 9696 public void onDraw(Canvas c, RecyclerView parent) { 9697 } 9698 9699 /** 9700 * Draw any appropriate decorations into the Canvas supplied to the RecyclerView. 9701 * Any content drawn by this method will be drawn after the item views are drawn 9702 * and will thus appear over the views. 9703 * 9704 * @param c Canvas to draw into 9705 * @param parent RecyclerView this ItemDecoration is drawing into 9706 * @param state The current state of RecyclerView. 9707 */ 9708 public void onDrawOver(Canvas c, RecyclerView parent, State state) { 9709 onDrawOver(c, parent); 9710 } 9711 9712 /** 9713 * @deprecated 9714 * Override {@link #onDrawOver(Canvas, RecyclerView, RecyclerView.State)} 9715 */ 9716 @Deprecated 9717 public void onDrawOver(Canvas c, RecyclerView parent) { 9718 } 9719 9720 9721 /** 9722 * @deprecated 9723 * Use {@link #getItemOffsets(Rect, View, RecyclerView, State)} 9724 */ 9725 @Deprecated 9726 public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { 9727 outRect.set(0, 0, 0, 0); 9728 } 9729 9730 /** 9731 * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies 9732 * the number of pixels that the item view should be inset by, similar to padding or margin. 9733 * The default implementation sets the bounds of outRect to 0 and returns. 9734 * 9735 * <p> 9736 * If this ItemDecoration does not affect the positioning of item views, it should set 9737 * all four fields of <code>outRect</code> (left, top, right, bottom) to zero 9738 * before returning. 9739 * 9740 * <p> 9741 * If you need to access Adapter for additional data, you can call 9742 * {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the 9743 * View. 9744 * 9745 * @param outRect Rect to receive the output. 9746 * @param view The child view to decorate 9747 * @param parent RecyclerView this ItemDecoration is decorating 9748 * @param state The current state of RecyclerView. 9749 */ 9750 public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) { 9751 getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(), 9752 parent); 9753 } 9754 } 9755 9756 /** 9757 * An OnItemTouchListener allows the application to intercept touch events in progress at the 9758 * view hierarchy level of the RecyclerView before those touch events are considered for 9759 * RecyclerView's own scrolling behavior. 9760 * 9761 * <p>This can be useful for applications that wish to implement various forms of gestural 9762 * manipulation of item views within the RecyclerView. OnItemTouchListeners may intercept 9763 * a touch interaction already in progress even if the RecyclerView is already handling that 9764 * gesture stream itself for the purposes of scrolling.</p> 9765 * 9766 * @see SimpleOnItemTouchListener 9767 */ 9768 public static interface OnItemTouchListener { 9769 /** 9770 * Silently observe and/or take over touch events sent to the RecyclerView 9771 * before they are handled by either the RecyclerView itself or its child views. 9772 * 9773 * <p>The onInterceptTouchEvent methods of each attached OnItemTouchListener will be run 9774 * in the order in which each listener was added, before any other touch processing 9775 * by the RecyclerView itself or child views occurs.</p> 9776 * 9777 * @param e MotionEvent describing the touch event. All coordinates are in 9778 * the RecyclerView's coordinate system. 9779 * @return true if this OnItemTouchListener wishes to begin intercepting touch events, false 9780 * to continue with the current behavior and continue observing future events in 9781 * the gesture. 9782 */ 9783 public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e); 9784 9785 /** 9786 * Process a touch event as part of a gesture that was claimed by returning true from 9787 * a previous call to {@link #onInterceptTouchEvent}. 9788 * 9789 * @param e MotionEvent describing the touch event. All coordinates are in 9790 * the RecyclerView's coordinate system. 9791 */ 9792 public void onTouchEvent(RecyclerView rv, MotionEvent e); 9793 9794 /** 9795 * Called when a child of RecyclerView does not want RecyclerView and its ancestors to 9796 * intercept touch events with 9797 * {@link ViewGroup#onInterceptTouchEvent(MotionEvent)}. 9798 * 9799 * @param disallowIntercept True if the child does not want the parent to 9800 * intercept touch events. 9801 * @see ViewParent#requestDisallowInterceptTouchEvent(boolean) 9802 */ 9803 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept); 9804 } 9805 9806 /** 9807 * An implementation of {@link RecyclerView.OnItemTouchListener} that has empty method bodies and 9808 * default return values. 9809 * <p> 9810 * You may prefer to extend this class if you don't need to override all methods. Another 9811 * benefit of using this class is future compatibility. As the interface may change, we'll 9812 * always provide a default implementation on this class so that your code won't break when 9813 * you update to a new version of the support library. 9814 */ 9815 public static class SimpleOnItemTouchListener implements RecyclerView.OnItemTouchListener { 9816 @Override 9817 public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) { 9818 return false; 9819 } 9820 9821 @Override 9822 public void onTouchEvent(RecyclerView rv, MotionEvent e) { 9823 } 9824 9825 @Override 9826 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { 9827 } 9828 } 9829 9830 9831 /** 9832 * An OnScrollListener can be added to a RecyclerView to receive messages when a scrolling event 9833 * has occurred on that RecyclerView. 9834 * <p> 9835 * @see RecyclerView#addOnScrollListener(OnScrollListener) 9836 * @see RecyclerView#clearOnChildAttachStateChangeListeners() 9837 * 9838 */ 9839 public abstract static class OnScrollListener { 9840 /** 9841 * Callback method to be invoked when RecyclerView's scroll state changes. 9842 * 9843 * @param recyclerView The RecyclerView whose scroll state has changed. 9844 * @param newState The updated scroll state. One of {@link #SCROLL_STATE_IDLE}, 9845 * {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}. 9846 */ 9847 public void onScrollStateChanged(RecyclerView recyclerView, int newState){} 9848 9849 /** 9850 * Callback method to be invoked when the RecyclerView has been scrolled. This will be 9851 * called after the scroll has completed. 9852 * <p> 9853 * This callback will also be called if visible item range changes after a layout 9854 * calculation. In that case, dx and dy will be 0. 9855 * 9856 * @param recyclerView The RecyclerView which scrolled. 9857 * @param dx The amount of horizontal scroll. 9858 * @param dy The amount of vertical scroll. 9859 */ 9860 public void onScrolled(RecyclerView recyclerView, int dx, int dy){} 9861 } 9862 9863 /** 9864 * A RecyclerListener can be set on a RecyclerView to receive messages whenever 9865 * a view is recycled. 9866 * 9867 * @see RecyclerView#setRecyclerListener(RecyclerListener) 9868 */ 9869 public interface RecyclerListener { 9870 9871 /** 9872 * This method is called whenever the view in the ViewHolder is recycled. 9873 * 9874 * RecyclerView calls this method right before clearing ViewHolder's internal data and 9875 * sending it to RecycledViewPool. This way, if ViewHolder was holding valid information 9876 * before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get 9877 * its adapter position. 9878 * 9879 * @param holder The ViewHolder containing the view that was recycled 9880 */ 9881 public void onViewRecycled(ViewHolder holder); 9882 } 9883 9884 /** 9885 * A Listener interface that can be attached to a RecylcerView to get notified 9886 * whenever a ViewHolder is attached to or detached from RecyclerView. 9887 */ 9888 public interface OnChildAttachStateChangeListener { 9889 9890 /** 9891 * Called when a view is attached to the RecyclerView. 9892 * 9893 * @param view The View which is attached to the RecyclerView 9894 */ 9895 public void onChildViewAttachedToWindow(View view); 9896 9897 /** 9898 * Called when a view is detached from RecyclerView. 9899 * 9900 * @param view The View which is being detached from the RecyclerView 9901 */ 9902 public void onChildViewDetachedFromWindow(View view); 9903 } 9904 9905 /** 9906 * A ViewHolder describes an item view and metadata about its place within the RecyclerView. 9907 * 9908 * <p>{@link Adapter} implementations should subclass ViewHolder and add fields for caching 9909 * potentially expensive {@link View#findViewById(int)} results.</p> 9910 * 9911 * <p>While {@link LayoutParams} belong to the {@link LayoutManager}, 9912 * {@link ViewHolder ViewHolders} belong to the adapter. Adapters should feel free to use 9913 * their own custom ViewHolder implementations to store data that makes binding view contents 9914 * easier. Implementations should assume that individual item views will hold strong references 9915 * to <code>ViewHolder</code> objects and that <code>RecyclerView</code> instances may hold 9916 * strong references to extra off-screen item views for caching purposes</p> 9917 */ 9918 public static abstract class ViewHolder { 9919 public final View itemView; 9920 WeakReference<RecyclerView> mNestedRecyclerView; 9921 int mPosition = NO_POSITION; 9922 int mOldPosition = NO_POSITION; 9923 long mItemId = NO_ID; 9924 int mItemViewType = INVALID_TYPE; 9925 int mPreLayoutPosition = NO_POSITION; 9926 9927 // The item that this holder is shadowing during an item change event/animation 9928 ViewHolder mShadowedHolder = null; 9929 // The item that is shadowing this holder during an item change event/animation 9930 ViewHolder mShadowingHolder = null; 9931 9932 /** 9933 * This ViewHolder has been bound to a position; mPosition, mItemId and mItemViewType 9934 * are all valid. 9935 */ 9936 static final int FLAG_BOUND = 1 << 0; 9937 9938 /** 9939 * The data this ViewHolder's view reflects is stale and needs to be rebound 9940 * by the adapter. mPosition and mItemId are consistent. 9941 */ 9942 static final int FLAG_UPDATE = 1 << 1; 9943 9944 /** 9945 * This ViewHolder's data is invalid. The identity implied by mPosition and mItemId 9946 * are not to be trusted and may no longer match the item view type. 9947 * This ViewHolder must be fully rebound to different data. 9948 */ 9949 static final int FLAG_INVALID = 1 << 2; 9950 9951 /** 9952 * This ViewHolder points at data that represents an item previously removed from the 9953 * data set. Its view may still be used for things like outgoing animations. 9954 */ 9955 static final int FLAG_REMOVED = 1 << 3; 9956 9957 /** 9958 * This ViewHolder should not be recycled. This flag is set via setIsRecyclable() 9959 * and is intended to keep views around during animations. 9960 */ 9961 static final int FLAG_NOT_RECYCLABLE = 1 << 4; 9962 9963 /** 9964 * This ViewHolder is returned from scrap which means we are expecting an addView call 9965 * for this itemView. When returned from scrap, ViewHolder stays in the scrap list until 9966 * the end of the layout pass and then recycled by RecyclerView if it is not added back to 9967 * the RecyclerView. 9968 */ 9969 static final int FLAG_RETURNED_FROM_SCRAP = 1 << 5; 9970 9971 /** 9972 * This ViewHolder is fully managed by the LayoutManager. We do not scrap, recycle or remove 9973 * it unless LayoutManager is replaced. 9974 * It is still fully visible to the LayoutManager. 9975 */ 9976 static final int FLAG_IGNORE = 1 << 7; 9977 9978 /** 9979 * When the View is detached form the parent, we set this flag so that we can take correct 9980 * action when we need to remove it or add it back. 9981 */ 9982 static final int FLAG_TMP_DETACHED = 1 << 8; 9983 9984 /** 9985 * Set when we can no longer determine the adapter position of this ViewHolder until it is 9986 * rebound to a new position. It is different than FLAG_INVALID because FLAG_INVALID is 9987 * set even when the type does not match. Also, FLAG_ADAPTER_POSITION_UNKNOWN is set as soon 9988 * as adapter notification arrives vs FLAG_INVALID is set lazily before layout is 9989 * re-calculated. 9990 */ 9991 static final int FLAG_ADAPTER_POSITION_UNKNOWN = 1 << 9; 9992 9993 /** 9994 * Set when a addChangePayload(null) is called 9995 */ 9996 static final int FLAG_ADAPTER_FULLUPDATE = 1 << 10; 9997 9998 /** 9999 * Used by ItemAnimator when a ViewHolder's position changes 10000 */ 10001 static final int FLAG_MOVED = 1 << 11; 10002 10003 /** 10004 * Used by ItemAnimator when a ViewHolder appears in pre-layout 10005 */ 10006 static final int FLAG_APPEARED_IN_PRE_LAYOUT = 1 << 12; 10007 10008 static final int PENDING_ACCESSIBILITY_STATE_NOT_SET = -1; 10009 10010 /** 10011 * Used when a ViewHolder starts the layout pass as a hidden ViewHolder but is re-used from 10012 * hidden list (as if it was scrap) without being recycled in between. 10013 * 10014 * When a ViewHolder is hidden, there are 2 paths it can be re-used: 10015 * a) Animation ends, view is recycled and used from the recycle pool. 10016 * b) LayoutManager asks for the View for that position while the ViewHolder is hidden. 10017 * 10018 * This flag is used to represent "case b" where the ViewHolder is reused without being 10019 * recycled (thus "bounced" from the hidden list). This state requires special handling 10020 * because the ViewHolder must be added to pre layout maps for animations as if it was 10021 * already there. 10022 */ 10023 static final int FLAG_BOUNCED_FROM_HIDDEN_LIST = 1 << 13; 10024 10025 private int mFlags; 10026 10027 private static final List<Object> FULLUPDATE_PAYLOADS = Collections.EMPTY_LIST; 10028 10029 List<Object> mPayloads = null; 10030 List<Object> mUnmodifiedPayloads = null; 10031 10032 private int mIsRecyclableCount = 0; 10033 10034 // If non-null, view is currently considered scrap and may be reused for other data by the 10035 // scrap container. 10036 private Recycler mScrapContainer = null; 10037 // Keeps whether this ViewHolder lives in Change scrap or Attached scrap 10038 private boolean mInChangeScrap = false; 10039 10040 // Saves isImportantForAccessibility value for the view item while it's in hidden state and 10041 // marked as unimportant for accessibility. 10042 private int mWasImportantForAccessibilityBeforeHidden = 10043 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; 10044 // set if we defer the accessibility state change of the view holder 10045 @VisibleForTesting 10046 int mPendingAccessibilityState = PENDING_ACCESSIBILITY_STATE_NOT_SET; 10047 10048 /** 10049 * Is set when VH is bound from the adapter and cleaned right before it is sent to 10050 * {@link RecycledViewPool}. 10051 */ 10052 RecyclerView mOwnerRecyclerView; 10053 10054 public ViewHolder(View itemView) { 10055 if (itemView == null) { 10056 throw new IllegalArgumentException("itemView may not be null"); 10057 } 10058 this.itemView = itemView; 10059 } 10060 10061 void flagRemovedAndOffsetPosition(int mNewPosition, int offset, boolean applyToPreLayout) { 10062 addFlags(ViewHolder.FLAG_REMOVED); 10063 offsetPosition(offset, applyToPreLayout); 10064 mPosition = mNewPosition; 10065 } 10066 10067 void offsetPosition(int offset, boolean applyToPreLayout) { 10068 if (mOldPosition == NO_POSITION) { 10069 mOldPosition = mPosition; 10070 } 10071 if (mPreLayoutPosition == NO_POSITION) { 10072 mPreLayoutPosition = mPosition; 10073 } 10074 if (applyToPreLayout) { 10075 mPreLayoutPosition += offset; 10076 } 10077 mPosition += offset; 10078 if (itemView.getLayoutParams() != null) { 10079 ((LayoutParams) itemView.getLayoutParams()).mInsetsDirty = true; 10080 } 10081 } 10082 10083 void clearOldPosition() { 10084 mOldPosition = NO_POSITION; 10085 mPreLayoutPosition = NO_POSITION; 10086 } 10087 10088 void saveOldPosition() { 10089 if (mOldPosition == NO_POSITION) { 10090 mOldPosition = mPosition; 10091 } 10092 } 10093 10094 boolean shouldIgnore() { 10095 return (mFlags & FLAG_IGNORE) != 0; 10096 } 10097 10098 /** 10099 * @deprecated This method is deprecated because its meaning is ambiguous due to the async 10100 * handling of adapter updates. Please use {@link #getLayoutPosition()} or 10101 * {@link #getAdapterPosition()} depending on your use case. 10102 * 10103 * @see #getLayoutPosition() 10104 * @see #getAdapterPosition() 10105 */ 10106 @Deprecated 10107 public final int getPosition() { 10108 return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition; 10109 } 10110 10111 /** 10112 * Returns the position of the ViewHolder in terms of the latest layout pass. 10113 * <p> 10114 * This position is mostly used by RecyclerView components to be consistent while 10115 * RecyclerView lazily processes adapter updates. 10116 * <p> 10117 * For performance and animation reasons, RecyclerView batches all adapter updates until the 10118 * next layout pass. This may cause mismatches between the Adapter position of the item and 10119 * the position it had in the latest layout calculations. 10120 * <p> 10121 * LayoutManagers should always call this method while doing calculations based on item 10122 * positions. All methods in {@link RecyclerView.LayoutManager}, {@link RecyclerView.State}, 10123 * {@link RecyclerView.Recycler} that receive a position expect it to be the layout position 10124 * of the item. 10125 * <p> 10126 * If LayoutManager needs to call an external method that requires the adapter position of 10127 * the item, it can use {@link #getAdapterPosition()} or 10128 * {@link RecyclerView.Recycler#convertPreLayoutPositionToPostLayout(int)}. 10129 * 10130 * @return Returns the adapter position of the ViewHolder in the latest layout pass. 10131 * @see #getAdapterPosition() 10132 */ 10133 public final int getLayoutPosition() { 10134 return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition; 10135 } 10136 10137 /** 10138 * Returns the Adapter position of the item represented by this ViewHolder. 10139 * <p> 10140 * Note that this might be different than the {@link #getLayoutPosition()} if there are 10141 * pending adapter updates but a new layout pass has not happened yet. 10142 * <p> 10143 * RecyclerView does not handle any adapter updates until the next layout traversal. This 10144 * may create temporary inconsistencies between what user sees on the screen and what 10145 * adapter contents have. This inconsistency is not important since it will be less than 10146 * 16ms but it might be a problem if you want to use ViewHolder position to access the 10147 * adapter. Sometimes, you may need to get the exact adapter position to do 10148 * some actions in response to user events. In that case, you should use this method which 10149 * will calculate the Adapter position of the ViewHolder. 10150 * <p> 10151 * Note that if you've called {@link RecyclerView.Adapter#notifyDataSetChanged()}, until the 10152 * next layout pass, the return value of this method will be {@link #NO_POSITION}. 10153 * 10154 * @return The adapter position of the item if it still exists in the adapter. 10155 * {@link RecyclerView#NO_POSITION} if item has been removed from the adapter, 10156 * {@link RecyclerView.Adapter#notifyDataSetChanged()} has been called after the last 10157 * layout pass or the ViewHolder has already been recycled. 10158 */ 10159 public final int getAdapterPosition() { 10160 if (mOwnerRecyclerView == null) { 10161 return NO_POSITION; 10162 } 10163 return mOwnerRecyclerView.getAdapterPositionFor(this); 10164 } 10165 10166 /** 10167 * When LayoutManager supports animations, RecyclerView tracks 3 positions for ViewHolders 10168 * to perform animations. 10169 * <p> 10170 * If a ViewHolder was laid out in the previous onLayout call, old position will keep its 10171 * adapter index in the previous layout. 10172 * 10173 * @return The previous adapter index of the Item represented by this ViewHolder or 10174 * {@link #NO_POSITION} if old position does not exists or cleared (pre-layout is 10175 * complete). 10176 */ 10177 public final int getOldPosition() { 10178 return mOldPosition; 10179 } 10180 10181 /** 10182 * Returns The itemId represented by this ViewHolder. 10183 * 10184 * @return The item's id if adapter has stable ids, {@link RecyclerView#NO_ID} 10185 * otherwise 10186 */ 10187 public final long getItemId() { 10188 return mItemId; 10189 } 10190 10191 /** 10192 * @return The view type of this ViewHolder. 10193 */ 10194 public final int getItemViewType() { 10195 return mItemViewType; 10196 } 10197 10198 boolean isScrap() { 10199 return mScrapContainer != null; 10200 } 10201 10202 void unScrap() { 10203 mScrapContainer.unscrapView(this); 10204 } 10205 10206 boolean wasReturnedFromScrap() { 10207 return (mFlags & FLAG_RETURNED_FROM_SCRAP) != 0; 10208 } 10209 10210 void clearReturnedFromScrapFlag() { 10211 mFlags = mFlags & ~FLAG_RETURNED_FROM_SCRAP; 10212 } 10213 10214 void clearTmpDetachFlag() { 10215 mFlags = mFlags & ~FLAG_TMP_DETACHED; 10216 } 10217 10218 void stopIgnoring() { 10219 mFlags = mFlags & ~FLAG_IGNORE; 10220 } 10221 10222 void setScrapContainer(Recycler recycler, boolean isChangeScrap) { 10223 mScrapContainer = recycler; 10224 mInChangeScrap = isChangeScrap; 10225 } 10226 10227 boolean isInvalid() { 10228 return (mFlags & FLAG_INVALID) != 0; 10229 } 10230 10231 boolean needsUpdate() { 10232 return (mFlags & FLAG_UPDATE) != 0; 10233 } 10234 10235 boolean isBound() { 10236 return (mFlags & FLAG_BOUND) != 0; 10237 } 10238 10239 boolean isRemoved() { 10240 return (mFlags & FLAG_REMOVED) != 0; 10241 } 10242 10243 boolean hasAnyOfTheFlags(int flags) { 10244 return (mFlags & flags) != 0; 10245 } 10246 10247 boolean isTmpDetached() { 10248 return (mFlags & FLAG_TMP_DETACHED) != 0; 10249 } 10250 10251 boolean isAdapterPositionUnknown() { 10252 return (mFlags & FLAG_ADAPTER_POSITION_UNKNOWN) != 0 || isInvalid(); 10253 } 10254 10255 void setFlags(int flags, int mask) { 10256 mFlags = (mFlags & ~mask) | (flags & mask); 10257 } 10258 10259 void addFlags(int flags) { 10260 mFlags |= flags; 10261 } 10262 10263 void addChangePayload(Object payload) { 10264 if (payload == null) { 10265 addFlags(FLAG_ADAPTER_FULLUPDATE); 10266 } else if ((mFlags & FLAG_ADAPTER_FULLUPDATE) == 0) { 10267 createPayloadsIfNeeded(); 10268 mPayloads.add(payload); 10269 } 10270 } 10271 10272 private void createPayloadsIfNeeded() { 10273 if (mPayloads == null) { 10274 mPayloads = new ArrayList<Object>(); 10275 mUnmodifiedPayloads = Collections.unmodifiableList(mPayloads); 10276 } 10277 } 10278 10279 void clearPayload() { 10280 if (mPayloads != null) { 10281 mPayloads.clear(); 10282 } 10283 mFlags = mFlags & ~FLAG_ADAPTER_FULLUPDATE; 10284 } 10285 10286 List<Object> getUnmodifiedPayloads() { 10287 if ((mFlags & FLAG_ADAPTER_FULLUPDATE) == 0) { 10288 if (mPayloads == null || mPayloads.size() == 0) { 10289 // Initial state, no update being called. 10290 return FULLUPDATE_PAYLOADS; 10291 } 10292 // there are none-null payloads 10293 return mUnmodifiedPayloads; 10294 } else { 10295 // a full update has been called. 10296 return FULLUPDATE_PAYLOADS; 10297 } 10298 } 10299 10300 void resetInternal() { 10301 mFlags = 0; 10302 mPosition = NO_POSITION; 10303 mOldPosition = NO_POSITION; 10304 mItemId = NO_ID; 10305 mPreLayoutPosition = NO_POSITION; 10306 mIsRecyclableCount = 0; 10307 mShadowedHolder = null; 10308 mShadowingHolder = null; 10309 clearPayload(); 10310 mWasImportantForAccessibilityBeforeHidden = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; 10311 mPendingAccessibilityState = PENDING_ACCESSIBILITY_STATE_NOT_SET; 10312 clearNestedRecyclerViewIfNotNested(this); 10313 } 10314 10315 /** 10316 * Called when the child view enters the hidden state 10317 */ 10318 private void onEnteredHiddenState(RecyclerView parent) { 10319 // While the view item is in hidden state, make it invisible for the accessibility. 10320 mWasImportantForAccessibilityBeforeHidden = 10321 ViewCompat.getImportantForAccessibility(itemView); 10322 parent.setChildImportantForAccessibilityInternal(this, 10323 ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS); 10324 } 10325 10326 /** 10327 * Called when the child view leaves the hidden state 10328 */ 10329 private void onLeftHiddenState(RecyclerView parent) { 10330 parent.setChildImportantForAccessibilityInternal(this, 10331 mWasImportantForAccessibilityBeforeHidden); 10332 mWasImportantForAccessibilityBeforeHidden = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO; 10333 } 10334 10335 @Override 10336 public String toString() { 10337 final StringBuilder sb = new StringBuilder("ViewHolder{" + 10338 Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId + 10339 ", oldPos=" + mOldPosition + ", pLpos:" + mPreLayoutPosition); 10340 if (isScrap()) { 10341 sb.append(" scrap ") 10342 .append(mInChangeScrap ? "[changeScrap]" : "[attachedScrap]"); 10343 } 10344 if (isInvalid()) sb.append(" invalid"); 10345 if (!isBound()) sb.append(" unbound"); 10346 if (needsUpdate()) sb.append(" update"); 10347 if (isRemoved()) sb.append(" removed"); 10348 if (shouldIgnore()) sb.append(" ignored"); 10349 if (isTmpDetached()) sb.append(" tmpDetached"); 10350 if (!isRecyclable()) sb.append(" not recyclable(" + mIsRecyclableCount + ")"); 10351 if (isAdapterPositionUnknown()) sb.append(" undefined adapter position"); 10352 10353 if (itemView.getParent() == null) sb.append(" no parent"); 10354 sb.append("}"); 10355 return sb.toString(); 10356 } 10357 10358 /** 10359 * Informs the recycler whether this item can be recycled. Views which are not 10360 * recyclable will not be reused for other items until setIsRecyclable() is 10361 * later set to true. Calls to setIsRecyclable() should always be paired (one 10362 * call to setIsRecyclabe(false) should always be matched with a later call to 10363 * setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally 10364 * reference-counted. 10365 * 10366 * @param recyclable Whether this item is available to be recycled. Default value 10367 * is true. 10368 * 10369 * @see #isRecyclable() 10370 */ 10371 public final void setIsRecyclable(boolean recyclable) { 10372 mIsRecyclableCount = recyclable ? mIsRecyclableCount - 1 : mIsRecyclableCount + 1; 10373 if (mIsRecyclableCount < 0) { 10374 mIsRecyclableCount = 0; 10375 if (DEBUG) { 10376 throw new RuntimeException("isRecyclable decremented below 0: " + 10377 "unmatched pair of setIsRecyable() calls for " + this); 10378 } 10379 Log.e(VIEW_LOG_TAG, "isRecyclable decremented below 0: " + 10380 "unmatched pair of setIsRecyable() calls for " + this); 10381 } else if (!recyclable && mIsRecyclableCount == 1) { 10382 mFlags |= FLAG_NOT_RECYCLABLE; 10383 } else if (recyclable && mIsRecyclableCount == 0) { 10384 mFlags &= ~FLAG_NOT_RECYCLABLE; 10385 } 10386 if (DEBUG) { 10387 Log.d(TAG, "setIsRecyclable val:" + recyclable + ":" + this); 10388 } 10389 } 10390 10391 /** 10392 * @return true if this item is available to be recycled, false otherwise. 10393 * 10394 * @see #setIsRecyclable(boolean) 10395 */ 10396 public final boolean isRecyclable() { 10397 return (mFlags & FLAG_NOT_RECYCLABLE) == 0 && 10398 !ViewCompat.hasTransientState(itemView); 10399 } 10400 10401 /** 10402 * Returns whether we have animations referring to this view holder or not. 10403 * This is similar to isRecyclable flag but does not check transient state. 10404 */ 10405 private boolean shouldBeKeptAsChild() { 10406 return (mFlags & FLAG_NOT_RECYCLABLE) != 0; 10407 } 10408 10409 /** 10410 * @return True if ViewHolder is not referenced by RecyclerView animations but has 10411 * transient state which will prevent it from being recycled. 10412 */ 10413 private boolean doesTransientStatePreventRecycling() { 10414 return (mFlags & FLAG_NOT_RECYCLABLE) == 0 && ViewCompat.hasTransientState(itemView); 10415 } 10416 10417 boolean isUpdated() { 10418 return (mFlags & FLAG_UPDATE) != 0; 10419 } 10420 } 10421 10422 /** 10423 * This method is here so that we can control the important for a11y changes and test it. 10424 */ 10425 @VisibleForTesting 10426 boolean setChildImportantForAccessibilityInternal(ViewHolder viewHolder, 10427 int importantForAccessibility) { 10428 if (isComputingLayout()) { 10429 viewHolder.mPendingAccessibilityState = importantForAccessibility; 10430 mPendingAccessibilityImportanceChange.add(viewHolder); 10431 return false; 10432 } 10433 ViewCompat.setImportantForAccessibility(viewHolder.itemView, importantForAccessibility); 10434 return true; 10435 } 10436 10437 void dispatchPendingImportantForAccessibilityChanges() { 10438 for (int i = mPendingAccessibilityImportanceChange.size() - 1; i >= 0; i --) { 10439 ViewHolder viewHolder = mPendingAccessibilityImportanceChange.get(i); 10440 if (viewHolder.itemView.getParent() != this || viewHolder.shouldIgnore()) { 10441 continue; 10442 } 10443 int state = viewHolder.mPendingAccessibilityState; 10444 if (state != ViewHolder.PENDING_ACCESSIBILITY_STATE_NOT_SET) { 10445 //noinspection WrongConstant 10446 ViewCompat.setImportantForAccessibility(viewHolder.itemView, state); 10447 viewHolder.mPendingAccessibilityState = 10448 ViewHolder.PENDING_ACCESSIBILITY_STATE_NOT_SET; 10449 } 10450 } 10451 mPendingAccessibilityImportanceChange.clear(); 10452 } 10453 10454 int getAdapterPositionFor(ViewHolder viewHolder) { 10455 if (viewHolder.hasAnyOfTheFlags( ViewHolder.FLAG_INVALID | 10456 ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN) 10457 || !viewHolder.isBound()) { 10458 return RecyclerView.NO_POSITION; 10459 } 10460 return mAdapterHelper.applyPendingUpdatesToPosition(viewHolder.mPosition); 10461 } 10462 10463 // NestedScrollingChild 10464 10465 @Override 10466 public void setNestedScrollingEnabled(boolean enabled) { 10467 getScrollingChildHelper().setNestedScrollingEnabled(enabled); 10468 } 10469 10470 @Override 10471 public boolean isNestedScrollingEnabled() { 10472 return getScrollingChildHelper().isNestedScrollingEnabled(); 10473 } 10474 10475 @Override 10476 public boolean startNestedScroll(int axes) { 10477 return getScrollingChildHelper().startNestedScroll(axes); 10478 } 10479 10480 @Override 10481 public void stopNestedScroll() { 10482 getScrollingChildHelper().stopNestedScroll(); 10483 } 10484 10485 @Override 10486 public boolean hasNestedScrollingParent() { 10487 return getScrollingChildHelper().hasNestedScrollingParent(); 10488 } 10489 10490 @Override 10491 public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, 10492 int dyUnconsumed, int[] offsetInWindow) { 10493 return getScrollingChildHelper().dispatchNestedScroll(dxConsumed, dyConsumed, 10494 dxUnconsumed, dyUnconsumed, offsetInWindow); 10495 } 10496 10497 @Override 10498 public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) { 10499 return getScrollingChildHelper().dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow); 10500 } 10501 10502 @Override 10503 public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) { 10504 return getScrollingChildHelper().dispatchNestedFling(velocityX, velocityY, consumed); 10505 } 10506 10507 @Override 10508 public boolean dispatchNestedPreFling(float velocityX, float velocityY) { 10509 return getScrollingChildHelper().dispatchNestedPreFling(velocityX, velocityY); 10510 } 10511 10512 /** 10513 * {@link android.view.ViewGroup.MarginLayoutParams LayoutParams} subclass for children of 10514 * {@link RecyclerView}. Custom {@link LayoutManager layout managers} are encouraged 10515 * to create their own subclass of this <code>LayoutParams</code> class 10516 * to store any additional required per-child view metadata about the layout. 10517 */ 10518 public static class LayoutParams extends android.view.ViewGroup.MarginLayoutParams { 10519 ViewHolder mViewHolder; 10520 final Rect mDecorInsets = new Rect(); 10521 boolean mInsetsDirty = true; 10522 // Flag is set to true if the view is bound while it is detached from RV. 10523 // In this case, we need to manually call invalidate after view is added to guarantee that 10524 // invalidation is populated through the View hierarchy 10525 boolean mPendingInvalidate = false; 10526 10527 public LayoutParams(Context c, AttributeSet attrs) { 10528 super(c, attrs); 10529 } 10530 10531 public LayoutParams(int width, int height) { 10532 super(width, height); 10533 } 10534 10535 public LayoutParams(MarginLayoutParams source) { 10536 super(source); 10537 } 10538 10539 public LayoutParams(ViewGroup.LayoutParams source) { 10540 super(source); 10541 } 10542 10543 public LayoutParams(LayoutParams source) { 10544 super((ViewGroup.LayoutParams) source); 10545 } 10546 10547 /** 10548 * Returns true if the view this LayoutParams is attached to needs to have its content 10549 * updated from the corresponding adapter. 10550 * 10551 * @return true if the view should have its content updated 10552 */ 10553 public boolean viewNeedsUpdate() { 10554 return mViewHolder.needsUpdate(); 10555 } 10556 10557 /** 10558 * Returns true if the view this LayoutParams is attached to is now representing 10559 * potentially invalid data. A LayoutManager should scrap/recycle it. 10560 * 10561 * @return true if the view is invalid 10562 */ 10563 public boolean isViewInvalid() { 10564 return mViewHolder.isInvalid(); 10565 } 10566 10567 /** 10568 * Returns true if the adapter data item corresponding to the view this LayoutParams 10569 * is attached to has been removed from the data set. A LayoutManager may choose to 10570 * treat it differently in order to animate its outgoing or disappearing state. 10571 * 10572 * @return true if the item the view corresponds to was removed from the data set 10573 */ 10574 public boolean isItemRemoved() { 10575 return mViewHolder.isRemoved(); 10576 } 10577 10578 /** 10579 * Returns true if the adapter data item corresponding to the view this LayoutParams 10580 * is attached to has been changed in the data set. A LayoutManager may choose to 10581 * treat it differently in order to animate its changing state. 10582 * 10583 * @return true if the item the view corresponds to was changed in the data set 10584 */ 10585 public boolean isItemChanged() { 10586 return mViewHolder.isUpdated(); 10587 } 10588 10589 /** 10590 * @deprecated use {@link #getViewLayoutPosition()} or {@link #getViewAdapterPosition()} 10591 */ 10592 @Deprecated 10593 public int getViewPosition() { 10594 return mViewHolder.getPosition(); 10595 } 10596 10597 /** 10598 * Returns the adapter position that the view this LayoutParams is attached to corresponds 10599 * to as of latest layout calculation. 10600 * 10601 * @return the adapter position this view as of latest layout pass 10602 */ 10603 public int getViewLayoutPosition() { 10604 return mViewHolder.getLayoutPosition(); 10605 } 10606 10607 /** 10608 * Returns the up-to-date adapter position that the view this LayoutParams is attached to 10609 * corresponds to. 10610 * 10611 * @return the up-to-date adapter position this view. It may return 10612 * {@link RecyclerView#NO_POSITION} if item represented by this View has been removed or 10613 * its up-to-date position cannot be calculated. 10614 */ 10615 public int getViewAdapterPosition() { 10616 return mViewHolder.getAdapterPosition(); 10617 } 10618 } 10619 10620 /** 10621 * Observer base class for watching changes to an {@link Adapter}. 10622 * See {@link Adapter#registerAdapterDataObserver(AdapterDataObserver)}. 10623 */ 10624 public static abstract class AdapterDataObserver { 10625 public void onChanged() { 10626 // Do nothing 10627 } 10628 10629 public void onItemRangeChanged(int positionStart, int itemCount) { 10630 // do nothing 10631 } 10632 10633 public void onItemRangeChanged(int positionStart, int itemCount, Object payload) { 10634 // fallback to onItemRangeChanged(positionStart, itemCount) if app 10635 // does not override this method. 10636 onItemRangeChanged(positionStart, itemCount); 10637 } 10638 10639 public void onItemRangeInserted(int positionStart, int itemCount) { 10640 // do nothing 10641 } 10642 10643 public void onItemRangeRemoved(int positionStart, int itemCount) { 10644 // do nothing 10645 } 10646 10647 public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { 10648 // do nothing 10649 } 10650 } 10651 10652 /** 10653 * <p>Base class for smooth scrolling. Handles basic tracking of the target view position and 10654 * provides methods to trigger a programmatic scroll.</p> 10655 * 10656 * @see LinearSmoothScroller 10657 */ 10658 public static abstract class SmoothScroller { 10659 10660 private int mTargetPosition = RecyclerView.NO_POSITION; 10661 10662 private RecyclerView mRecyclerView; 10663 10664 private LayoutManager mLayoutManager; 10665 10666 private boolean mPendingInitialRun; 10667 10668 private boolean mRunning; 10669 10670 private View mTargetView; 10671 10672 private final Action mRecyclingAction; 10673 10674 public SmoothScroller() { 10675 mRecyclingAction = new Action(0, 0); 10676 } 10677 10678 /** 10679 * Starts a smooth scroll for the given target position. 10680 * <p>In each animation step, {@link RecyclerView} will check 10681 * for the target view and call either 10682 * {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or 10683 * {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)} until 10684 * SmoothScroller is stopped.</p> 10685 * 10686 * <p>Note that if RecyclerView finds the target view, it will automatically stop the 10687 * SmoothScroller. This <b>does not</b> mean that scroll will stop, it only means it will 10688 * stop calling SmoothScroller in each animation step.</p> 10689 */ 10690 void start(RecyclerView recyclerView, LayoutManager layoutManager) { 10691 mRecyclerView = recyclerView; 10692 mLayoutManager = layoutManager; 10693 if (mTargetPosition == RecyclerView.NO_POSITION) { 10694 throw new IllegalArgumentException("Invalid target position"); 10695 } 10696 mRecyclerView.mState.mTargetPosition = mTargetPosition; 10697 mRunning = true; 10698 mPendingInitialRun = true; 10699 mTargetView = findViewByPosition(getTargetPosition()); 10700 onStart(); 10701 mRecyclerView.mViewFlinger.postOnAnimation(); 10702 } 10703 10704 public void setTargetPosition(int targetPosition) { 10705 mTargetPosition = targetPosition; 10706 } 10707 10708 /** 10709 * @return The LayoutManager to which this SmoothScroller is attached. Will return 10710 * <code>null</code> after the SmoothScroller is stopped. 10711 */ 10712 @Nullable 10713 public LayoutManager getLayoutManager() { 10714 return mLayoutManager; 10715 } 10716 10717 /** 10718 * Stops running the SmoothScroller in each animation callback. Note that this does not 10719 * cancel any existing {@link Action} updated by 10720 * {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or 10721 * {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)}. 10722 */ 10723 final protected void stop() { 10724 if (!mRunning) { 10725 return; 10726 } 10727 onStop(); 10728 mRecyclerView.mState.mTargetPosition = RecyclerView.NO_POSITION; 10729 mTargetView = null; 10730 mTargetPosition = RecyclerView.NO_POSITION; 10731 mPendingInitialRun = false; 10732 mRunning = false; 10733 // trigger a cleanup 10734 mLayoutManager.onSmoothScrollerStopped(this); 10735 // clear references to avoid any potential leak by a custom smooth scroller 10736 mLayoutManager = null; 10737 mRecyclerView = null; 10738 } 10739 10740 /** 10741 * Returns true if SmoothScroller has been started but has not received the first 10742 * animation 10743 * callback yet. 10744 * 10745 * @return True if this SmoothScroller is waiting to start 10746 */ 10747 public boolean isPendingInitialRun() { 10748 return mPendingInitialRun; 10749 } 10750 10751 10752 /** 10753 * @return True if SmoothScroller is currently active 10754 */ 10755 public boolean isRunning() { 10756 return mRunning; 10757 } 10758 10759 /** 10760 * Returns the adapter position of the target item 10761 * 10762 * @return Adapter position of the target item or 10763 * {@link RecyclerView#NO_POSITION} if no target view is set. 10764 */ 10765 public int getTargetPosition() { 10766 return mTargetPosition; 10767 } 10768 10769 private void onAnimation(int dx, int dy) { 10770 final RecyclerView recyclerView = mRecyclerView; 10771 if (!mRunning || mTargetPosition == RecyclerView.NO_POSITION || recyclerView == null) { 10772 stop(); 10773 } 10774 mPendingInitialRun = false; 10775 if (mTargetView != null) { 10776 // verify target position 10777 if (getChildPosition(mTargetView) == mTargetPosition) { 10778 onTargetFound(mTargetView, recyclerView.mState, mRecyclingAction); 10779 mRecyclingAction.runIfNecessary(recyclerView); 10780 stop(); 10781 } else { 10782 Log.e(TAG, "Passed over target position while smooth scrolling."); 10783 mTargetView = null; 10784 } 10785 } 10786 if (mRunning) { 10787 onSeekTargetStep(dx, dy, recyclerView.mState, mRecyclingAction); 10788 boolean hadJumpTarget = mRecyclingAction.hasJumpTarget(); 10789 mRecyclingAction.runIfNecessary(recyclerView); 10790 if (hadJumpTarget) { 10791 // It is not stopped so needs to be restarted 10792 if (mRunning) { 10793 mPendingInitialRun = true; 10794 recyclerView.mViewFlinger.postOnAnimation(); 10795 } else { 10796 stop(); // done 10797 } 10798 } 10799 } 10800 } 10801 10802 /** 10803 * @see RecyclerView#getChildLayoutPosition(android.view.View) 10804 */ 10805 public int getChildPosition(View view) { 10806 return mRecyclerView.getChildLayoutPosition(view); 10807 } 10808 10809 /** 10810 * @see RecyclerView.LayoutManager#getChildCount() 10811 */ 10812 public int getChildCount() { 10813 return mRecyclerView.mLayout.getChildCount(); 10814 } 10815 10816 /** 10817 * @see RecyclerView.LayoutManager#findViewByPosition(int) 10818 */ 10819 public View findViewByPosition(int position) { 10820 return mRecyclerView.mLayout.findViewByPosition(position); 10821 } 10822 10823 /** 10824 * @see RecyclerView#scrollToPosition(int) 10825 * @deprecated Use {@link Action#jumpTo(int)}. 10826 */ 10827 @Deprecated 10828 public void instantScrollToPosition(int position) { 10829 mRecyclerView.scrollToPosition(position); 10830 } 10831 10832 protected void onChildAttachedToWindow(View child) { 10833 if (getChildPosition(child) == getTargetPosition()) { 10834 mTargetView = child; 10835 if (DEBUG) { 10836 Log.d(TAG, "smooth scroll target view has been attached"); 10837 } 10838 } 10839 } 10840 10841 /** 10842 * Normalizes the vector. 10843 * @param scrollVector The vector that points to the target scroll position 10844 */ 10845 protected void normalize(PointF scrollVector) { 10846 final double magnitude = Math.sqrt(scrollVector.x * scrollVector.x + scrollVector.y 10847 * scrollVector.y); 10848 scrollVector.x /= magnitude; 10849 scrollVector.y /= magnitude; 10850 } 10851 10852 /** 10853 * Called when smooth scroll is started. This might be a good time to do setup. 10854 */ 10855 abstract protected void onStart(); 10856 10857 /** 10858 * Called when smooth scroller is stopped. This is a good place to cleanup your state etc. 10859 * @see #stop() 10860 */ 10861 abstract protected void onStop(); 10862 10863 /** 10864 * <p>RecyclerView will call this method each time it scrolls until it can find the target 10865 * position in the layout.</p> 10866 * <p>SmoothScroller should check dx, dy and if scroll should be changed, update the 10867 * provided {@link Action} to define the next scroll.</p> 10868 * 10869 * @param dx Last scroll amount horizontally 10870 * @param dy Last scroll amount vertically 10871 * @param state Transient state of RecyclerView 10872 * @param action If you want to trigger a new smooth scroll and cancel the previous one, 10873 * update this object. 10874 */ 10875 abstract protected void onSeekTargetStep(int dx, int dy, State state, Action action); 10876 10877 /** 10878 * Called when the target position is laid out. This is the last callback SmoothScroller 10879 * will receive and it should update the provided {@link Action} to define the scroll 10880 * details towards the target view. 10881 * @param targetView The view element which render the target position. 10882 * @param state Transient state of RecyclerView 10883 * @param action Action instance that you should update to define final scroll action 10884 * towards the targetView 10885 */ 10886 abstract protected void onTargetFound(View targetView, State state, Action action); 10887 10888 /** 10889 * Holds information about a smooth scroll request by a {@link SmoothScroller}. 10890 */ 10891 public static class Action { 10892 10893 public static final int UNDEFINED_DURATION = Integer.MIN_VALUE; 10894 10895 private int mDx; 10896 10897 private int mDy; 10898 10899 private int mDuration; 10900 10901 private int mJumpToPosition = NO_POSITION; 10902 10903 private Interpolator mInterpolator; 10904 10905 private boolean changed = false; 10906 10907 // we track this variable to inform custom implementer if they are updating the action 10908 // in every animation callback 10909 private int consecutiveUpdates = 0; 10910 10911 /** 10912 * @param dx Pixels to scroll horizontally 10913 * @param dy Pixels to scroll vertically 10914 */ 10915 public Action(int dx, int dy) { 10916 this(dx, dy, UNDEFINED_DURATION, null); 10917 } 10918 10919 /** 10920 * @param dx Pixels to scroll horizontally 10921 * @param dy Pixels to scroll vertically 10922 * @param duration Duration of the animation in milliseconds 10923 */ 10924 public Action(int dx, int dy, int duration) { 10925 this(dx, dy, duration, null); 10926 } 10927 10928 /** 10929 * @param dx Pixels to scroll horizontally 10930 * @param dy Pixels to scroll vertically 10931 * @param duration Duration of the animation in milliseconds 10932 * @param interpolator Interpolator to be used when calculating scroll position in each 10933 * animation step 10934 */ 10935 public Action(int dx, int dy, int duration, Interpolator interpolator) { 10936 mDx = dx; 10937 mDy = dy; 10938 mDuration = duration; 10939 mInterpolator = interpolator; 10940 } 10941 10942 /** 10943 * Instead of specifying pixels to scroll, use the target position to jump using 10944 * {@link RecyclerView#scrollToPosition(int)}. 10945 * <p> 10946 * You may prefer using this method if scroll target is really far away and you prefer 10947 * to jump to a location and smooth scroll afterwards. 10948 * <p> 10949 * Note that calling this method takes priority over other update methods such as 10950 * {@link #update(int, int, int, Interpolator)}, {@link #setX(float)}, 10951 * {@link #setY(float)} and #{@link #setInterpolator(Interpolator)}. If you call 10952 * {@link #jumpTo(int)}, the other changes will not be considered for this animation 10953 * frame. 10954 * 10955 * @param targetPosition The target item position to scroll to using instant scrolling. 10956 */ 10957 public void jumpTo(int targetPosition) { 10958 mJumpToPosition = targetPosition; 10959 } 10960 10961 boolean hasJumpTarget() { 10962 return mJumpToPosition >= 0; 10963 } 10964 10965 void runIfNecessary(RecyclerView recyclerView) { 10966 if (mJumpToPosition >= 0) { 10967 final int position = mJumpToPosition; 10968 mJumpToPosition = NO_POSITION; 10969 recyclerView.jumpToPositionForSmoothScroller(position); 10970 changed = false; 10971 return; 10972 } 10973 if (changed) { 10974 validate(); 10975 if (mInterpolator == null) { 10976 if (mDuration == UNDEFINED_DURATION) { 10977 recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy); 10978 } else { 10979 recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration); 10980 } 10981 } else { 10982 recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration, mInterpolator); 10983 } 10984 consecutiveUpdates ++; 10985 if (consecutiveUpdates > 10) { 10986 // A new action is being set in every animation step. This looks like a bad 10987 // implementation. Inform developer. 10988 Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure" 10989 + " you are not changing it unless necessary"); 10990 } 10991 changed = false; 10992 } else { 10993 consecutiveUpdates = 0; 10994 } 10995 } 10996 10997 private void validate() { 10998 if (mInterpolator != null && mDuration < 1) { 10999 throw new IllegalStateException("If you provide an interpolator, you must" 11000 + " set a positive duration"); 11001 } else if (mDuration < 1) { 11002 throw new IllegalStateException("Scroll duration must be a positive number"); 11003 } 11004 } 11005 11006 public int getDx() { 11007 return mDx; 11008 } 11009 11010 public void setDx(int dx) { 11011 changed = true; 11012 mDx = dx; 11013 } 11014 11015 public int getDy() { 11016 return mDy; 11017 } 11018 11019 public void setDy(int dy) { 11020 changed = true; 11021 mDy = dy; 11022 } 11023 11024 public int getDuration() { 11025 return mDuration; 11026 } 11027 11028 public void setDuration(int duration) { 11029 changed = true; 11030 mDuration = duration; 11031 } 11032 11033 public Interpolator getInterpolator() { 11034 return mInterpolator; 11035 } 11036 11037 /** 11038 * Sets the interpolator to calculate scroll steps 11039 * @param interpolator The interpolator to use. If you specify an interpolator, you must 11040 * also set the duration. 11041 * @see #setDuration(int) 11042 */ 11043 public void setInterpolator(Interpolator interpolator) { 11044 changed = true; 11045 mInterpolator = interpolator; 11046 } 11047 11048 /** 11049 * Updates the action with given parameters. 11050 * @param dx Pixels to scroll horizontally 11051 * @param dy Pixels to scroll vertically 11052 * @param duration Duration of the animation in milliseconds 11053 * @param interpolator Interpolator to be used when calculating scroll position in each 11054 * animation step 11055 */ 11056 public void update(int dx, int dy, int duration, Interpolator interpolator) { 11057 mDx = dx; 11058 mDy = dy; 11059 mDuration = duration; 11060 mInterpolator = interpolator; 11061 changed = true; 11062 } 11063 } 11064 11065 /** 11066 * An interface which is optionally implemented by custom {@link RecyclerView.LayoutManager} 11067 * to provide a hint to a {@link SmoothScroller} about the location of the target position. 11068 */ 11069 public interface ScrollVectorProvider { 11070 /** 11071 * Should calculate the vector that points to the direction where the target position 11072 * can be found. 11073 * <p> 11074 * This method is used by the {@link LinearSmoothScroller} to initiate a scroll towards 11075 * the target position. 11076 * <p> 11077 * The magnitude of the vector is not important. It is always normalized before being 11078 * used by the {@link LinearSmoothScroller}. 11079 * <p> 11080 * LayoutManager should not check whether the position exists in the adapter or not. 11081 * 11082 * @param targetPosition the target position to which the returned vector should point 11083 * 11084 * @return the scroll vector for a given position. 11085 */ 11086 PointF computeScrollVectorForPosition(int targetPosition); 11087 } 11088 } 11089 11090 static class AdapterDataObservable extends Observable<AdapterDataObserver> { 11091 public boolean hasObservers() { 11092 return !mObservers.isEmpty(); 11093 } 11094 11095 public void notifyChanged() { 11096 // since onChanged() is implemented by the app, it could do anything, including 11097 // removing itself from {@link mObservers} - and that could cause problems if 11098 // an iterator is used on the ArrayList {@link mObservers}. 11099 // to avoid such problems, just march thru the list in the reverse order. 11100 for (int i = mObservers.size() - 1; i >= 0; i--) { 11101 mObservers.get(i).onChanged(); 11102 } 11103 } 11104 11105 public void notifyItemRangeChanged(int positionStart, int itemCount) { 11106 notifyItemRangeChanged(positionStart, itemCount, null); 11107 } 11108 11109 public void notifyItemRangeChanged(int positionStart, int itemCount, Object payload) { 11110 // since onItemRangeChanged() is implemented by the app, it could do anything, including 11111 // removing itself from {@link mObservers} - and that could cause problems if 11112 // an iterator is used on the ArrayList {@link mObservers}. 11113 // to avoid such problems, just march thru the list in the reverse order. 11114 for (int i = mObservers.size() - 1; i >= 0; i--) { 11115 mObservers.get(i).onItemRangeChanged(positionStart, itemCount, payload); 11116 } 11117 } 11118 11119 public void notifyItemRangeInserted(int positionStart, int itemCount) { 11120 // since onItemRangeInserted() is implemented by the app, it could do anything, 11121 // including removing itself from {@link mObservers} - and that could cause problems if 11122 // an iterator is used on the ArrayList {@link mObservers}. 11123 // to avoid such problems, just march thru the list in the reverse order. 11124 for (int i = mObservers.size() - 1; i >= 0; i--) { 11125 mObservers.get(i).onItemRangeInserted(positionStart, itemCount); 11126 } 11127 } 11128 11129 public void notifyItemRangeRemoved(int positionStart, int itemCount) { 11130 // since onItemRangeRemoved() is implemented by the app, it could do anything, including 11131 // removing itself from {@link mObservers} - and that could cause problems if 11132 // an iterator is used on the ArrayList {@link mObservers}. 11133 // to avoid such problems, just march thru the list in the reverse order. 11134 for (int i = mObservers.size() - 1; i >= 0; i--) { 11135 mObservers.get(i).onItemRangeRemoved(positionStart, itemCount); 11136 } 11137 } 11138 11139 public void notifyItemMoved(int fromPosition, int toPosition) { 11140 for (int i = mObservers.size() - 1; i >= 0; i--) { 11141 mObservers.get(i).onItemRangeMoved(fromPosition, toPosition, 1); 11142 } 11143 } 11144 } 11145 11146 /** 11147 * This is public so that the CREATOR can be access on cold launch. 11148 * @hide 11149 */ 11150 @RestrictTo(LIBRARY_GROUP) 11151 public static class SavedState extends AbsSavedState { 11152 11153 Parcelable mLayoutState; 11154 11155 /** 11156 * called by CREATOR 11157 */ 11158 SavedState(Parcel in, ClassLoader loader) { 11159 super(in, loader); 11160 mLayoutState = in.readParcelable( 11161 loader != null ? loader : LayoutManager.class.getClassLoader()); 11162 } 11163 11164 /** 11165 * Called by onSaveInstanceState 11166 */ 11167 SavedState(Parcelable superState) { 11168 super(superState); 11169 } 11170 11171 @Override 11172 public void writeToParcel(Parcel dest, int flags) { 11173 super.writeToParcel(dest, flags); 11174 dest.writeParcelable(mLayoutState, 0); 11175 } 11176 11177 void copyFrom(SavedState other) { 11178 mLayoutState = other.mLayoutState; 11179 } 11180 11181 public static final Creator<SavedState> CREATOR = ParcelableCompat.newCreator( 11182 new ParcelableCompatCreatorCallbacks<SavedState>() { 11183 @Override 11184 public SavedState createFromParcel(Parcel in, ClassLoader loader) { 11185 return new SavedState(in, loader); 11186 } 11187 11188 @Override 11189 public SavedState[] newArray(int size) { 11190 return new SavedState[size]; 11191 } 11192 }); 11193 } 11194 /** 11195 * <p>Contains useful information about the current RecyclerView state like target scroll 11196 * position or view focus. State object can also keep arbitrary data, identified by resource 11197 * ids.</p> 11198 * <p>Often times, RecyclerView components will need to pass information between each other. 11199 * To provide a well defined data bus between components, RecyclerView passes the same State 11200 * object to component callbacks and these components can use it to exchange data.</p> 11201 * <p>If you implement custom components, you can use State's put/get/remove methods to pass 11202 * data between your components without needing to manage their lifecycles.</p> 11203 */ 11204 public static class State { 11205 static final int STEP_START = 1; 11206 static final int STEP_LAYOUT = 1 << 1; 11207 static final int STEP_ANIMATIONS = 1 << 2; 11208 11209 void assertLayoutStep(int accepted) { 11210 if ((accepted & mLayoutStep) == 0) { 11211 throw new IllegalStateException("Layout state should be one of " 11212 + Integer.toBinaryString(accepted) + " but it is " 11213 + Integer.toBinaryString(mLayoutStep)); 11214 } 11215 } 11216 11217 11218 /** Owned by SmoothScroller */ 11219 private int mTargetPosition = RecyclerView.NO_POSITION; 11220 11221 private SparseArray<Object> mData; 11222 11223 //////////////////////////////////////////////////////////////////////////////////////////// 11224 // Fields below are carried from one layout pass to the next 11225 //////////////////////////////////////////////////////////////////////////////////////////// 11226 11227 /** 11228 * Number of items adapter had in the previous layout. 11229 */ 11230 int mPreviousLayoutItemCount = 0; 11231 11232 /** 11233 * Number of items that were NOT laid out but has been deleted from the adapter after the 11234 * previous layout. 11235 */ 11236 int mDeletedInvisibleItemCountSincePreviousLayout = 0; 11237 11238 //////////////////////////////////////////////////////////////////////////////////////////// 11239 // Fields below must be updated or cleared before they are used (generally before a pass) 11240 //////////////////////////////////////////////////////////////////////////////////////////// 11241 11242 @IntDef(flag = true, value = { 11243 STEP_START, STEP_LAYOUT, STEP_ANIMATIONS 11244 }) 11245 @Retention(RetentionPolicy.SOURCE) 11246 @interface LayoutState {} 11247 11248 @LayoutState 11249 int mLayoutStep = STEP_START; 11250 11251 /** 11252 * Number of items adapter has. 11253 */ 11254 int mItemCount = 0; 11255 11256 boolean mStructureChanged = false; 11257 11258 boolean mInPreLayout = false; 11259 11260 boolean mTrackOldChangeHolders = false; 11261 11262 boolean mIsMeasuring = false; 11263 11264 //////////////////////////////////////////////////////////////////////////////////////////// 11265 // Fields below are always reset outside of the pass (or passes) that use them 11266 //////////////////////////////////////////////////////////////////////////////////////////// 11267 11268 boolean mRunSimpleAnimations = false; 11269 11270 boolean mRunPredictiveAnimations = false; 11271 11272 /** 11273 * This data is saved before a layout calculation happens. After the layout is finished, 11274 * if the previously focused view has been replaced with another view for the same item, we 11275 * move the focus to the new item automatically. 11276 */ 11277 int mFocusedItemPosition; 11278 long mFocusedItemId; 11279 // when a sub child has focus, record its id and see if we can directly request focus on 11280 // that one instead 11281 int mFocusedSubChildId; 11282 11283 //////////////////////////////////////////////////////////////////////////////////////////// 11284 11285 State reset() { 11286 mTargetPosition = RecyclerView.NO_POSITION; 11287 if (mData != null) { 11288 mData.clear(); 11289 } 11290 mItemCount = 0; 11291 mStructureChanged = false; 11292 mIsMeasuring = false; 11293 return this; 11294 } 11295 11296 /** 11297 * Prepare for a prefetch occurring on the RecyclerView in between traversals, potentially 11298 * prior to any layout passes. 11299 * 11300 * <p>Don't touch any state stored between layout passes, only reset per-layout state, so 11301 * that Recycler#getViewForPosition() can function safely.</p> 11302 */ 11303 void prepareForNestedPrefetch(Adapter adapter) { 11304 mLayoutStep = STEP_START; 11305 mItemCount = adapter.getItemCount(); 11306 mStructureChanged = false; 11307 mInPreLayout = false; 11308 mTrackOldChangeHolders = false; 11309 mIsMeasuring = false; 11310 } 11311 11312 /** 11313 * Returns true if the RecyclerView is currently measuring the layout. This value is 11314 * {@code true} only if the LayoutManager opted into the auto measure API and RecyclerView 11315 * has non-exact measurement specs. 11316 * <p> 11317 * Note that if the LayoutManager supports predictive animations and it is calculating the 11318 * pre-layout step, this value will be {@code false} even if the RecyclerView is in 11319 * {@code onMeasure} call. This is because pre-layout means the previous state of the 11320 * RecyclerView and measurements made for that state cannot change the RecyclerView's size. 11321 * LayoutManager is always guaranteed to receive another call to 11322 * {@link LayoutManager#onLayoutChildren(Recycler, State)} when this happens. 11323 * 11324 * @return True if the RecyclerView is currently calculating its bounds, false otherwise. 11325 */ 11326 public boolean isMeasuring() { 11327 return mIsMeasuring; 11328 } 11329 11330 /** 11331 * Returns true if 11332 * @return 11333 */ 11334 public boolean isPreLayout() { 11335 return mInPreLayout; 11336 } 11337 11338 /** 11339 * Returns whether RecyclerView will run predictive animations in this layout pass 11340 * or not. 11341 * 11342 * @return true if RecyclerView is calculating predictive animations to be run at the end 11343 * of the layout pass. 11344 */ 11345 public boolean willRunPredictiveAnimations() { 11346 return mRunPredictiveAnimations; 11347 } 11348 11349 /** 11350 * Returns whether RecyclerView will run simple animations in this layout pass 11351 * or not. 11352 * 11353 * @return true if RecyclerView is calculating simple animations to be run at the end of 11354 * the layout pass. 11355 */ 11356 public boolean willRunSimpleAnimations() { 11357 return mRunSimpleAnimations; 11358 } 11359 11360 /** 11361 * Removes the mapping from the specified id, if there was any. 11362 * @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* to 11363 * preserve cross functionality and avoid conflicts. 11364 */ 11365 public void remove(int resourceId) { 11366 if (mData == null) { 11367 return; 11368 } 11369 mData.remove(resourceId); 11370 } 11371 11372 /** 11373 * Gets the Object mapped from the specified id, or <code>null</code> 11374 * if no such data exists. 11375 * 11376 * @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* 11377 * to 11378 * preserve cross functionality and avoid conflicts. 11379 */ 11380 public <T> T get(int resourceId) { 11381 if (mData == null) { 11382 return null; 11383 } 11384 return (T) mData.get(resourceId); 11385 } 11386 11387 /** 11388 * Adds a mapping from the specified id to the specified value, replacing the previous 11389 * mapping from the specified key if there was one. 11390 * 11391 * @param resourceId Id of the resource you want to add. It is suggested to use R.id.* to 11392 * preserve cross functionality and avoid conflicts. 11393 * @param data The data you want to associate with the resourceId. 11394 */ 11395 public void put(int resourceId, Object data) { 11396 if (mData == null) { 11397 mData = new SparseArray<Object>(); 11398 } 11399 mData.put(resourceId, data); 11400 } 11401 11402 /** 11403 * If scroll is triggered to make a certain item visible, this value will return the 11404 * adapter index of that item. 11405 * @return Adapter index of the target item or 11406 * {@link RecyclerView#NO_POSITION} if there is no target 11407 * position. 11408 */ 11409 public int getTargetScrollPosition() { 11410 return mTargetPosition; 11411 } 11412 11413 /** 11414 * Returns if current scroll has a target position. 11415 * @return true if scroll is being triggered to make a certain position visible 11416 * @see #getTargetScrollPosition() 11417 */ 11418 public boolean hasTargetScrollPosition() { 11419 return mTargetPosition != RecyclerView.NO_POSITION; 11420 } 11421 11422 /** 11423 * @return true if the structure of the data set has changed since the last call to 11424 * onLayoutChildren, false otherwise 11425 */ 11426 public boolean didStructureChange() { 11427 return mStructureChanged; 11428 } 11429 11430 /** 11431 * Returns the total number of items that can be laid out. Note that this number is not 11432 * necessarily equal to the number of items in the adapter, so you should always use this 11433 * number for your position calculations and never access the adapter directly. 11434 * <p> 11435 * RecyclerView listens for Adapter's notify events and calculates the effects of adapter 11436 * data changes on existing Views. These calculations are used to decide which animations 11437 * should be run. 11438 * <p> 11439 * To support predictive animations, RecyclerView may rewrite or reorder Adapter changes to 11440 * present the correct state to LayoutManager in pre-layout pass. 11441 * <p> 11442 * For example, a newly added item is not included in pre-layout item count because 11443 * pre-layout reflects the contents of the adapter before the item is added. Behind the 11444 * scenes, RecyclerView offsets {@link Recycler#getViewForPosition(int)} calls such that 11445 * LayoutManager does not know about the new item's existence in pre-layout. The item will 11446 * be available in second layout pass and will be included in the item count. Similar 11447 * adjustments are made for moved and removed items as well. 11448 * <p> 11449 * You can get the adapter's item count via {@link LayoutManager#getItemCount()} method. 11450 * 11451 * @return The number of items currently available 11452 * @see LayoutManager#getItemCount() 11453 */ 11454 public int getItemCount() { 11455 return mInPreLayout ? 11456 (mPreviousLayoutItemCount - mDeletedInvisibleItemCountSincePreviousLayout) : 11457 mItemCount; 11458 } 11459 11460 @Override 11461 public String toString() { 11462 return "State{" + 11463 "mTargetPosition=" + mTargetPosition + 11464 ", mData=" + mData + 11465 ", mItemCount=" + mItemCount + 11466 ", mPreviousLayoutItemCount=" + mPreviousLayoutItemCount + 11467 ", mDeletedInvisibleItemCountSincePreviousLayout=" 11468 + mDeletedInvisibleItemCountSincePreviousLayout + 11469 ", mStructureChanged=" + mStructureChanged + 11470 ", mInPreLayout=" + mInPreLayout + 11471 ", mRunSimpleAnimations=" + mRunSimpleAnimations + 11472 ", mRunPredictiveAnimations=" + mRunPredictiveAnimations + 11473 '}'; 11474 } 11475 } 11476 11477 /** 11478 * This class defines the behavior of fling if the developer wishes to handle it. 11479 * <p> 11480 * Subclasses of {@link OnFlingListener} can be used to implement custom fling behavior. 11481 * 11482 * @see #setOnFlingListener(OnFlingListener) 11483 */ 11484 public static abstract class OnFlingListener { 11485 11486 /** 11487 * Override this to handle a fling given the velocities in both x and y directions. 11488 * Note that this method will only be called if the associated {@link LayoutManager} 11489 * supports scrolling and the fling is not handled by nested scrolls first. 11490 * 11491 * @param velocityX the fling velocity on the X axis 11492 * @param velocityY the fling velocity on the Y axis 11493 * 11494 * @return true if the fling washandled, false otherwise. 11495 */ 11496 public abstract boolean onFling(int velocityX, int velocityY); 11497 } 11498 11499 /** 11500 * Internal listener that manages items after animations finish. This is how items are 11501 * retained (not recycled) during animations, but allowed to be recycled afterwards. 11502 * It depends on the contract with the ItemAnimator to call the appropriate dispatch*Finished() 11503 * method on the animator's listener when it is done animating any item. 11504 */ 11505 private class ItemAnimatorRestoreListener implements ItemAnimator.ItemAnimatorListener { 11506 11507 ItemAnimatorRestoreListener() { 11508 } 11509 11510 @Override 11511 public void onAnimationFinished(ViewHolder item) { 11512 item.setIsRecyclable(true); 11513 if (item.mShadowedHolder != null && item.mShadowingHolder == null) { // old vh 11514 item.mShadowedHolder = null; 11515 } 11516 // always null this because an OldViewHolder can never become NewViewHolder w/o being 11517 // recycled. 11518 item.mShadowingHolder = null; 11519 if (!item.shouldBeKeptAsChild()) { 11520 if (!removeAnimatingView(item.itemView) && item.isTmpDetached()) { 11521 removeDetachedView(item.itemView, false); 11522 } 11523 } 11524 } 11525 } 11526 11527 /** 11528 * This class defines the animations that take place on items as changes are made 11529 * to the adapter. 11530 * 11531 * Subclasses of ItemAnimator can be used to implement custom animations for actions on 11532 * ViewHolder items. The RecyclerView will manage retaining these items while they 11533 * are being animated, but implementors must call {@link #dispatchAnimationFinished(ViewHolder)} 11534 * when a ViewHolder's animation is finished. In other words, there must be a matching 11535 * {@link #dispatchAnimationFinished(ViewHolder)} call for each 11536 * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) animateAppearance()}, 11537 * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo) 11538 * animateChange()} 11539 * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) animatePersistence()}, 11540 * and 11541 * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11542 * animateDisappearance()} call. 11543 * 11544 * <p>By default, RecyclerView uses {@link DefaultItemAnimator}.</p> 11545 * 11546 * @see #setItemAnimator(ItemAnimator) 11547 */ 11548 @SuppressWarnings("UnusedParameters") 11549 public static abstract class ItemAnimator { 11550 11551 /** 11552 * The Item represented by this ViewHolder is updated. 11553 * <p> 11554 * @see #recordPreLayoutInformation(State, ViewHolder, int, List) 11555 */ 11556 public static final int FLAG_CHANGED = ViewHolder.FLAG_UPDATE; 11557 11558 /** 11559 * The Item represented by this ViewHolder is removed from the adapter. 11560 * <p> 11561 * @see #recordPreLayoutInformation(State, ViewHolder, int, List) 11562 */ 11563 public static final int FLAG_REMOVED = ViewHolder.FLAG_REMOVED; 11564 11565 /** 11566 * Adapter {@link Adapter#notifyDataSetChanged()} has been called and the content 11567 * represented by this ViewHolder is invalid. 11568 * <p> 11569 * @see #recordPreLayoutInformation(State, ViewHolder, int, List) 11570 */ 11571 public static final int FLAG_INVALIDATED = ViewHolder.FLAG_INVALID; 11572 11573 /** 11574 * The position of the Item represented by this ViewHolder has been changed. This flag is 11575 * not bound to {@link Adapter#notifyItemMoved(int, int)}. It might be set in response to 11576 * any adapter change that may have a side effect on this item. (e.g. The item before this 11577 * one has been removed from the Adapter). 11578 * <p> 11579 * @see #recordPreLayoutInformation(State, ViewHolder, int, List) 11580 */ 11581 public static final int FLAG_MOVED = ViewHolder.FLAG_MOVED; 11582 11583 /** 11584 * This ViewHolder was not laid out but has been added to the layout in pre-layout state 11585 * by the {@link LayoutManager}. This means that the item was already in the Adapter but 11586 * invisible and it may become visible in the post layout phase. LayoutManagers may prefer 11587 * to add new items in pre-layout to specify their virtual location when they are invisible 11588 * (e.g. to specify the item should <i>animate in</i> from below the visible area). 11589 * <p> 11590 * @see #recordPreLayoutInformation(State, ViewHolder, int, List) 11591 */ 11592 public static final int FLAG_APPEARED_IN_PRE_LAYOUT 11593 = ViewHolder.FLAG_APPEARED_IN_PRE_LAYOUT; 11594 11595 /** 11596 * The set of flags that might be passed to 11597 * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11598 */ 11599 @IntDef(flag=true, value={ 11600 FLAG_CHANGED, FLAG_REMOVED, FLAG_MOVED, FLAG_INVALIDATED, 11601 FLAG_APPEARED_IN_PRE_LAYOUT 11602 }) 11603 @Retention(RetentionPolicy.SOURCE) 11604 public @interface AdapterChanges {} 11605 private ItemAnimatorListener mListener = null; 11606 private ArrayList<ItemAnimatorFinishedListener> mFinishedListeners = 11607 new ArrayList<ItemAnimatorFinishedListener>(); 11608 11609 private long mAddDuration = 120; 11610 private long mRemoveDuration = 120; 11611 private long mMoveDuration = 250; 11612 private long mChangeDuration = 250; 11613 11614 /** 11615 * Gets the current duration for which all move animations will run. 11616 * 11617 * @return The current move duration 11618 */ 11619 public long getMoveDuration() { 11620 return mMoveDuration; 11621 } 11622 11623 /** 11624 * Sets the duration for which all move animations will run. 11625 * 11626 * @param moveDuration The move duration 11627 */ 11628 public void setMoveDuration(long moveDuration) { 11629 mMoveDuration = moveDuration; 11630 } 11631 11632 /** 11633 * Gets the current duration for which all add animations will run. 11634 * 11635 * @return The current add duration 11636 */ 11637 public long getAddDuration() { 11638 return mAddDuration; 11639 } 11640 11641 /** 11642 * Sets the duration for which all add animations will run. 11643 * 11644 * @param addDuration The add duration 11645 */ 11646 public void setAddDuration(long addDuration) { 11647 mAddDuration = addDuration; 11648 } 11649 11650 /** 11651 * Gets the current duration for which all remove animations will run. 11652 * 11653 * @return The current remove duration 11654 */ 11655 public long getRemoveDuration() { 11656 return mRemoveDuration; 11657 } 11658 11659 /** 11660 * Sets the duration for which all remove animations will run. 11661 * 11662 * @param removeDuration The remove duration 11663 */ 11664 public void setRemoveDuration(long removeDuration) { 11665 mRemoveDuration = removeDuration; 11666 } 11667 11668 /** 11669 * Gets the current duration for which all change animations will run. 11670 * 11671 * @return The current change duration 11672 */ 11673 public long getChangeDuration() { 11674 return mChangeDuration; 11675 } 11676 11677 /** 11678 * Sets the duration for which all change animations will run. 11679 * 11680 * @param changeDuration The change duration 11681 */ 11682 public void setChangeDuration(long changeDuration) { 11683 mChangeDuration = changeDuration; 11684 } 11685 11686 /** 11687 * Internal only: 11688 * Sets the listener that must be called when the animator is finished 11689 * animating the item (or immediately if no animation happens). This is set 11690 * internally and is not intended to be set by external code. 11691 * 11692 * @param listener The listener that must be called. 11693 */ 11694 void setListener(ItemAnimatorListener listener) { 11695 mListener = listener; 11696 } 11697 11698 /** 11699 * Called by the RecyclerView before the layout begins. Item animator should record 11700 * necessary information about the View before it is potentially rebound, moved or removed. 11701 * <p> 11702 * The data returned from this method will be passed to the related <code>animate**</code> 11703 * methods. 11704 * <p> 11705 * Note that this method may be called after pre-layout phase if LayoutManager adds new 11706 * Views to the layout in pre-layout pass. 11707 * <p> 11708 * The default implementation returns an {@link ItemHolderInfo} which holds the bounds of 11709 * the View and the adapter change flags. 11710 * 11711 * @param state The current State of RecyclerView which includes some useful data 11712 * about the layout that will be calculated. 11713 * @param viewHolder The ViewHolder whose information should be recorded. 11714 * @param changeFlags Additional information about what changes happened in the Adapter 11715 * about the Item represented by this ViewHolder. For instance, if 11716 * item is deleted from the adapter, {@link #FLAG_REMOVED} will be set. 11717 * @param payloads The payload list that was previously passed to 11718 * {@link Adapter#notifyItemChanged(int, Object)} or 11719 * {@link Adapter#notifyItemRangeChanged(int, int, Object)}. 11720 * 11721 * @return An ItemHolderInfo instance that preserves necessary information about the 11722 * ViewHolder. This object will be passed back to related <code>animate**</code> methods 11723 * after layout is complete. 11724 * 11725 * @see #recordPostLayoutInformation(State, ViewHolder) 11726 * @see #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11727 * @see #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11728 * @see #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo) 11729 * @see #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11730 */ 11731 public @NonNull ItemHolderInfo recordPreLayoutInformation(@NonNull State state, 11732 @NonNull ViewHolder viewHolder, @AdapterChanges int changeFlags, 11733 @NonNull List<Object> payloads) { 11734 return obtainHolderInfo().setFrom(viewHolder); 11735 } 11736 11737 /** 11738 * Called by the RecyclerView after the layout is complete. Item animator should record 11739 * necessary information about the View's final state. 11740 * <p> 11741 * The data returned from this method will be passed to the related <code>animate**</code> 11742 * methods. 11743 * <p> 11744 * The default implementation returns an {@link ItemHolderInfo} which holds the bounds of 11745 * the View. 11746 * 11747 * @param state The current State of RecyclerView which includes some useful data about 11748 * the layout that will be calculated. 11749 * @param viewHolder The ViewHolder whose information should be recorded. 11750 * 11751 * @return An ItemHolderInfo that preserves necessary information about the ViewHolder. 11752 * This object will be passed back to related <code>animate**</code> methods when 11753 * RecyclerView decides how items should be animated. 11754 * 11755 * @see #recordPreLayoutInformation(State, ViewHolder, int, List) 11756 * @see #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11757 * @see #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11758 * @see #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo) 11759 * @see #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11760 */ 11761 public @NonNull ItemHolderInfo recordPostLayoutInformation(@NonNull State state, 11762 @NonNull ViewHolder viewHolder) { 11763 return obtainHolderInfo().setFrom(viewHolder); 11764 } 11765 11766 /** 11767 * Called by the RecyclerView when a ViewHolder has disappeared from the layout. 11768 * <p> 11769 * This means that the View was a child of the LayoutManager when layout started but has 11770 * been removed by the LayoutManager. It might have been removed from the adapter or simply 11771 * become invisible due to other factors. You can distinguish these two cases by checking 11772 * the change flags that were passed to 11773 * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11774 * <p> 11775 * Note that when a ViewHolder both changes and disappears in the same layout pass, the 11776 * animation callback method which will be called by the RecyclerView depends on the 11777 * ItemAnimator's decision whether to re-use the same ViewHolder or not, and also the 11778 * LayoutManager's decision whether to layout the changed version of a disappearing 11779 * ViewHolder or not. RecyclerView will call 11780 * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo) 11781 * animateChange} instead of {@code animateDisappearance} if and only if the ItemAnimator 11782 * returns {@code false} from 11783 * {@link #canReuseUpdatedViewHolder(ViewHolder) canReuseUpdatedViewHolder} and the 11784 * LayoutManager lays out a new disappearing view that holds the updated information. 11785 * Built-in LayoutManagers try to avoid laying out updated versions of disappearing views. 11786 * <p> 11787 * If LayoutManager supports predictive animations, it might provide a target disappear 11788 * location for the View by laying it out in that location. When that happens, 11789 * RecyclerView will call {@link #recordPostLayoutInformation(State, ViewHolder)} and the 11790 * response of that call will be passed to this method as the <code>postLayoutInfo</code>. 11791 * <p> 11792 * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation 11793 * is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it 11794 * decides not to animate the view). 11795 * 11796 * @param viewHolder The ViewHolder which should be animated 11797 * @param preLayoutInfo The information that was returned from 11798 * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11799 * @param postLayoutInfo The information that was returned from 11800 * {@link #recordPostLayoutInformation(State, ViewHolder)}. Might be 11801 * null if the LayoutManager did not layout the item. 11802 * 11803 * @return true if a later call to {@link #runPendingAnimations()} is requested, 11804 * false otherwise. 11805 */ 11806 public abstract boolean animateDisappearance(@NonNull ViewHolder viewHolder, 11807 @NonNull ItemHolderInfo preLayoutInfo, @Nullable ItemHolderInfo postLayoutInfo); 11808 11809 /** 11810 * Called by the RecyclerView when a ViewHolder is added to the layout. 11811 * <p> 11812 * In detail, this means that the ViewHolder was <b>not</b> a child when the layout started 11813 * but has been added by the LayoutManager. It might be newly added to the adapter or 11814 * simply become visible due to other factors. 11815 * <p> 11816 * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation 11817 * is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it 11818 * decides not to animate the view). 11819 * 11820 * @param viewHolder The ViewHolder which should be animated 11821 * @param preLayoutInfo The information that was returned from 11822 * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11823 * Might be null if Item was just added to the adapter or 11824 * LayoutManager does not support predictive animations or it could 11825 * not predict that this ViewHolder will become visible. 11826 * @param postLayoutInfo The information that was returned from {@link 11827 * #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11828 * 11829 * @return true if a later call to {@link #runPendingAnimations()} is requested, 11830 * false otherwise. 11831 */ 11832 public abstract boolean animateAppearance(@NonNull ViewHolder viewHolder, 11833 @Nullable ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo); 11834 11835 /** 11836 * Called by the RecyclerView when a ViewHolder is present in both before and after the 11837 * layout and RecyclerView has not received a {@link Adapter#notifyItemChanged(int)} call 11838 * for it or a {@link Adapter#notifyDataSetChanged()} call. 11839 * <p> 11840 * This ViewHolder still represents the same data that it was representing when the layout 11841 * started but its position / size may be changed by the LayoutManager. 11842 * <p> 11843 * If the Item's layout position didn't change, RecyclerView still calls this method because 11844 * it does not track this information (or does not necessarily know that an animation is 11845 * not required). Your ItemAnimator should handle this case and if there is nothing to 11846 * animate, it should call {@link #dispatchAnimationFinished(ViewHolder)} and return 11847 * <code>false</code>. 11848 * <p> 11849 * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation 11850 * is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it 11851 * decides not to animate the view). 11852 * 11853 * @param viewHolder The ViewHolder which should be animated 11854 * @param preLayoutInfo The information that was returned from 11855 * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11856 * @param postLayoutInfo The information that was returned from {@link 11857 * #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11858 * 11859 * @return true if a later call to {@link #runPendingAnimations()} is requested, 11860 * false otherwise. 11861 */ 11862 public abstract boolean animatePersistence(@NonNull ViewHolder viewHolder, 11863 @NonNull ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo); 11864 11865 /** 11866 * Called by the RecyclerView when an adapter item is present both before and after the 11867 * layout and RecyclerView has received a {@link Adapter#notifyItemChanged(int)} call 11868 * for it. This method may also be called when 11869 * {@link Adapter#notifyDataSetChanged()} is called and adapter has stable ids so that 11870 * RecyclerView could still rebind views to the same ViewHolders. If viewType changes when 11871 * {@link Adapter#notifyDataSetChanged()} is called, this method <b>will not</b> be called, 11872 * instead, {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)} will be 11873 * called for the new ViewHolder and the old one will be recycled. 11874 * <p> 11875 * If this method is called due to a {@link Adapter#notifyDataSetChanged()} call, there is 11876 * a good possibility that item contents didn't really change but it is rebound from the 11877 * adapter. {@link DefaultItemAnimator} will skip animating the View if its location on the 11878 * screen didn't change and your animator should handle this case as well and avoid creating 11879 * unnecessary animations. 11880 * <p> 11881 * When an item is updated, ItemAnimator has a chance to ask RecyclerView to keep the 11882 * previous presentation of the item as-is and supply a new ViewHolder for the updated 11883 * presentation (see: {@link #canReuseUpdatedViewHolder(ViewHolder, List)}. 11884 * This is useful if you don't know the contents of the Item and would like 11885 * to cross-fade the old and the new one ({@link DefaultItemAnimator} uses this technique). 11886 * <p> 11887 * When you are writing a custom item animator for your layout, it might be more performant 11888 * and elegant to re-use the same ViewHolder and animate the content changes manually. 11889 * <p> 11890 * When {@link Adapter#notifyItemChanged(int)} is called, the Item's view type may change. 11891 * If the Item's view type has changed or ItemAnimator returned <code>false</code> for 11892 * this ViewHolder when {@link #canReuseUpdatedViewHolder(ViewHolder, List)} was called, the 11893 * <code>oldHolder</code> and <code>newHolder</code> will be different ViewHolder instances 11894 * which represent the same Item. In that case, only the new ViewHolder is visible 11895 * to the LayoutManager but RecyclerView keeps old ViewHolder attached for animations. 11896 * <p> 11897 * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} for each distinct 11898 * ViewHolder when their animation is complete 11899 * (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it decides not to 11900 * animate the view). 11901 * <p> 11902 * If oldHolder and newHolder are the same instance, you should call 11903 * {@link #dispatchAnimationFinished(ViewHolder)} <b>only once</b>. 11904 * <p> 11905 * Note that when a ViewHolder both changes and disappears in the same layout pass, the 11906 * animation callback method which will be called by the RecyclerView depends on the 11907 * ItemAnimator's decision whether to re-use the same ViewHolder or not, and also the 11908 * LayoutManager's decision whether to layout the changed version of a disappearing 11909 * ViewHolder or not. RecyclerView will call 11910 * {@code animateChange} instead of 11911 * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11912 * animateDisappearance} if and only if the ItemAnimator returns {@code false} from 11913 * {@link #canReuseUpdatedViewHolder(ViewHolder) canReuseUpdatedViewHolder} and the 11914 * LayoutManager lays out a new disappearing view that holds the updated information. 11915 * Built-in LayoutManagers try to avoid laying out updated versions of disappearing views. 11916 * 11917 * @param oldHolder The ViewHolder before the layout is started, might be the same 11918 * instance with newHolder. 11919 * @param newHolder The ViewHolder after the layout is finished, might be the same 11920 * instance with oldHolder. 11921 * @param preLayoutInfo The information that was returned from 11922 * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11923 * @param postLayoutInfo The information that was returned from {@link 11924 * #recordPreLayoutInformation(State, ViewHolder, int, List)}. 11925 * 11926 * @return true if a later call to {@link #runPendingAnimations()} is requested, 11927 * false otherwise. 11928 */ 11929 public abstract boolean animateChange(@NonNull ViewHolder oldHolder, 11930 @NonNull ViewHolder newHolder, 11931 @NonNull ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo); 11932 11933 @AdapterChanges static int buildAdapterChangeFlagsForAnimations(ViewHolder viewHolder) { 11934 int flags = viewHolder.mFlags & (FLAG_INVALIDATED | FLAG_REMOVED | FLAG_CHANGED); 11935 if (viewHolder.isInvalid()) { 11936 return FLAG_INVALIDATED; 11937 } 11938 if ((flags & FLAG_INVALIDATED) == 0) { 11939 final int oldPos = viewHolder.getOldPosition(); 11940 final int pos = viewHolder.getAdapterPosition(); 11941 if (oldPos != NO_POSITION && pos != NO_POSITION && oldPos != pos){ 11942 flags |= FLAG_MOVED; 11943 } 11944 } 11945 return flags; 11946 } 11947 11948 /** 11949 * Called when there are pending animations waiting to be started. This state 11950 * is governed by the return values from 11951 * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11952 * animateAppearance()}, 11953 * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo) 11954 * animateChange()} 11955 * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11956 * animatePersistence()}, and 11957 * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 11958 * animateDisappearance()}, which inform the RecyclerView that the ItemAnimator wants to be 11959 * called later to start the associated animations. runPendingAnimations() will be scheduled 11960 * to be run on the next frame. 11961 */ 11962 abstract public void runPendingAnimations(); 11963 11964 /** 11965 * Method called when an animation on a view should be ended immediately. 11966 * This could happen when other events, like scrolling, occur, so that 11967 * animating views can be quickly put into their proper end locations. 11968 * Implementations should ensure that any animations running on the item 11969 * are canceled and affected properties are set to their end values. 11970 * Also, {@link #dispatchAnimationFinished(ViewHolder)} should be called for each finished 11971 * animation since the animations are effectively done when this method is called. 11972 * 11973 * @param item The item for which an animation should be stopped. 11974 */ 11975 abstract public void endAnimation(ViewHolder item); 11976 11977 /** 11978 * Method called when all item animations should be ended immediately. 11979 * This could happen when other events, like scrolling, occur, so that 11980 * animating views can be quickly put into their proper end locations. 11981 * Implementations should ensure that any animations running on any items 11982 * are canceled and affected properties are set to their end values. 11983 * Also, {@link #dispatchAnimationFinished(ViewHolder)} should be called for each finished 11984 * animation since the animations are effectively done when this method is called. 11985 */ 11986 abstract public void endAnimations(); 11987 11988 /** 11989 * Method which returns whether there are any item animations currently running. 11990 * This method can be used to determine whether to delay other actions until 11991 * animations end. 11992 * 11993 * @return true if there are any item animations currently running, false otherwise. 11994 */ 11995 abstract public boolean isRunning(); 11996 11997 /** 11998 * Method to be called by subclasses when an animation is finished. 11999 * <p> 12000 * For each call RecyclerView makes to 12001 * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 12002 * animateAppearance()}, 12003 * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) 12004 * animatePersistence()}, or 12005 * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 12006 * animateDisappearance()}, there 12007 * should 12008 * be a matching {@link #dispatchAnimationFinished(ViewHolder)} call by the subclass. 12009 * <p> 12010 * For {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo) 12011 * animateChange()}, subclass should call this method for both the <code>oldHolder</code> 12012 * and <code>newHolder</code> (if they are not the same instance). 12013 * 12014 * @param viewHolder The ViewHolder whose animation is finished. 12015 * @see #onAnimationFinished(ViewHolder) 12016 */ 12017 public final void dispatchAnimationFinished(ViewHolder viewHolder) { 12018 onAnimationFinished(viewHolder); 12019 if (mListener != null) { 12020 mListener.onAnimationFinished(viewHolder); 12021 } 12022 } 12023 12024 /** 12025 * Called after {@link #dispatchAnimationFinished(ViewHolder)} is called by the 12026 * ItemAnimator. 12027 * 12028 * @param viewHolder The ViewHolder whose animation is finished. There might still be other 12029 * animations running on this ViewHolder. 12030 * @see #dispatchAnimationFinished(ViewHolder) 12031 */ 12032 public void onAnimationFinished(ViewHolder viewHolder) { 12033 } 12034 12035 /** 12036 * Method to be called by subclasses when an animation is started. 12037 * <p> 12038 * For each call RecyclerView makes to 12039 * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 12040 * animateAppearance()}, 12041 * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) 12042 * animatePersistence()}, or 12043 * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) 12044 * animateDisappearance()}, there should be a matching 12045 * {@link #dispatchAnimationStarted(ViewHolder)} call by the subclass. 12046 * <p> 12047 * For {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo) 12048 * animateChange()}, subclass should call this method for both the <code>oldHolder</code> 12049 * and <code>newHolder</code> (if they are not the same instance). 12050 * <p> 12051 * If your ItemAnimator decides not to animate a ViewHolder, it should call 12052 * {@link #dispatchAnimationFinished(ViewHolder)} <b>without</b> calling 12053 * {@link #dispatchAnimationStarted(ViewHolder)}. 12054 * 12055 * @param viewHolder The ViewHolder whose animation is starting. 12056 * @see #onAnimationStarted(ViewHolder) 12057 */ 12058 public final void dispatchAnimationStarted(ViewHolder viewHolder) { 12059 onAnimationStarted(viewHolder); 12060 } 12061 12062 /** 12063 * Called when a new animation is started on the given ViewHolder. 12064 * 12065 * @param viewHolder The ViewHolder which started animating. Note that the ViewHolder 12066 * might already be animating and this might be another animation. 12067 * @see #dispatchAnimationStarted(ViewHolder) 12068 */ 12069 public void onAnimationStarted(ViewHolder viewHolder) { 12070 12071 } 12072 12073 /** 12074 * Like {@link #isRunning()}, this method returns whether there are any item 12075 * animations currently running. Additionally, the listener passed in will be called 12076 * when there are no item animations running, either immediately (before the method 12077 * returns) if no animations are currently running, or when the currently running 12078 * animations are {@link #dispatchAnimationsFinished() finished}. 12079 * 12080 * <p>Note that the listener is transient - it is either called immediately and not 12081 * stored at all, or stored only until it is called when running animations 12082 * are finished sometime later.</p> 12083 * 12084 * @param listener A listener to be called immediately if no animations are running 12085 * or later when currently-running animations have finished. A null listener is 12086 * equivalent to calling {@link #isRunning()}. 12087 * @return true if there are any item animations currently running, false otherwise. 12088 */ 12089 public final boolean isRunning(ItemAnimatorFinishedListener listener) { 12090 boolean running = isRunning(); 12091 if (listener != null) { 12092 if (!running) { 12093 listener.onAnimationsFinished(); 12094 } else { 12095 mFinishedListeners.add(listener); 12096 } 12097 } 12098 return running; 12099 } 12100 12101 /** 12102 * When an item is changed, ItemAnimator can decide whether it wants to re-use 12103 * the same ViewHolder for animations or RecyclerView should create a copy of the 12104 * item and ItemAnimator will use both to run the animation (e.g. cross-fade). 12105 * <p> 12106 * Note that this method will only be called if the {@link ViewHolder} still has the same 12107 * type ({@link Adapter#getItemViewType(int)}). Otherwise, ItemAnimator will always receive 12108 * both {@link ViewHolder}s in the 12109 * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)} method. 12110 * <p> 12111 * If your application is using change payloads, you can override 12112 * {@link #canReuseUpdatedViewHolder(ViewHolder, List)} to decide based on payloads. 12113 * 12114 * @param viewHolder The ViewHolder which represents the changed item's old content. 12115 * 12116 * @return True if RecyclerView should just rebind to the same ViewHolder or false if 12117 * RecyclerView should create a new ViewHolder and pass this ViewHolder to the 12118 * ItemAnimator to animate. Default implementation returns <code>true</code>. 12119 * 12120 * @see #canReuseUpdatedViewHolder(ViewHolder, List) 12121 */ 12122 public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder) { 12123 return true; 12124 } 12125 12126 /** 12127 * When an item is changed, ItemAnimator can decide whether it wants to re-use 12128 * the same ViewHolder for animations or RecyclerView should create a copy of the 12129 * item and ItemAnimator will use both to run the animation (e.g. cross-fade). 12130 * <p> 12131 * Note that this method will only be called if the {@link ViewHolder} still has the same 12132 * type ({@link Adapter#getItemViewType(int)}). Otherwise, ItemAnimator will always receive 12133 * both {@link ViewHolder}s in the 12134 * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)} method. 12135 * 12136 * @param viewHolder The ViewHolder which represents the changed item's old content. 12137 * @param payloads A non-null list of merged payloads that were sent with change 12138 * notifications. Can be empty if the adapter is invalidated via 12139 * {@link RecyclerView.Adapter#notifyDataSetChanged()}. The same list of 12140 * payloads will be passed into 12141 * {@link RecyclerView.Adapter#onBindViewHolder(ViewHolder, int, List)} 12142 * method <b>if</b> this method returns <code>true</code>. 12143 * 12144 * @return True if RecyclerView should just rebind to the same ViewHolder or false if 12145 * RecyclerView should create a new ViewHolder and pass this ViewHolder to the 12146 * ItemAnimator to animate. Default implementation calls 12147 * {@link #canReuseUpdatedViewHolder(ViewHolder)}. 12148 * 12149 * @see #canReuseUpdatedViewHolder(ViewHolder) 12150 */ 12151 public boolean canReuseUpdatedViewHolder(@NonNull ViewHolder viewHolder, 12152 @NonNull List<Object> payloads) { 12153 return canReuseUpdatedViewHolder(viewHolder); 12154 } 12155 12156 /** 12157 * This method should be called by ItemAnimator implementations to notify 12158 * any listeners that all pending and active item animations are finished. 12159 */ 12160 public final void dispatchAnimationsFinished() { 12161 final int count = mFinishedListeners.size(); 12162 for (int i = 0; i < count; ++i) { 12163 mFinishedListeners.get(i).onAnimationsFinished(); 12164 } 12165 mFinishedListeners.clear(); 12166 } 12167 12168 /** 12169 * Returns a new {@link ItemHolderInfo} which will be used to store information about the 12170 * ViewHolder. This information will later be passed into <code>animate**</code> methods. 12171 * <p> 12172 * You can override this method if you want to extend {@link ItemHolderInfo} and provide 12173 * your own instances. 12174 * 12175 * @return A new {@link ItemHolderInfo}. 12176 */ 12177 public ItemHolderInfo obtainHolderInfo() { 12178 return new ItemHolderInfo(); 12179 } 12180 12181 /** 12182 * The interface to be implemented by listeners to animation events from this 12183 * ItemAnimator. This is used internally and is not intended for developers to 12184 * create directly. 12185 */ 12186 interface ItemAnimatorListener { 12187 void onAnimationFinished(ViewHolder item); 12188 } 12189 12190 /** 12191 * This interface is used to inform listeners when all pending or running animations 12192 * in an ItemAnimator are finished. This can be used, for example, to delay an action 12193 * in a data set until currently-running animations are complete. 12194 * 12195 * @see #isRunning(ItemAnimatorFinishedListener) 12196 */ 12197 public interface ItemAnimatorFinishedListener { 12198 void onAnimationsFinished(); 12199 } 12200 12201 /** 12202 * A simple data structure that holds information about an item's bounds. 12203 * This information is used in calculating item animations. Default implementation of 12204 * {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int, List)} and 12205 * {@link #recordPostLayoutInformation(RecyclerView.State, ViewHolder)} returns this data 12206 * structure. You can extend this class if you would like to keep more information about 12207 * the Views. 12208 * <p> 12209 * If you want to provide your own implementation but still use `super` methods to record 12210 * basic information, you can override {@link #obtainHolderInfo()} to provide your own 12211 * instances. 12212 */ 12213 public static class ItemHolderInfo { 12214 12215 /** 12216 * The left edge of the View (excluding decorations) 12217 */ 12218 public int left; 12219 12220 /** 12221 * The top edge of the View (excluding decorations) 12222 */ 12223 public int top; 12224 12225 /** 12226 * The right edge of the View (excluding decorations) 12227 */ 12228 public int right; 12229 12230 /** 12231 * The bottom edge of the View (excluding decorations) 12232 */ 12233 public int bottom; 12234 12235 /** 12236 * The change flags that were passed to 12237 * {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int, List)}. 12238 */ 12239 @AdapterChanges 12240 public int changeFlags; 12241 12242 public ItemHolderInfo() { 12243 } 12244 12245 /** 12246 * Sets the {@link #left}, {@link #top}, {@link #right} and {@link #bottom} values from 12247 * the given ViewHolder. Clears all {@link #changeFlags}. 12248 * 12249 * @param holder The ViewHolder whose bounds should be copied. 12250 * @return This {@link ItemHolderInfo} 12251 */ 12252 public ItemHolderInfo setFrom(RecyclerView.ViewHolder holder) { 12253 return setFrom(holder, 0); 12254 } 12255 12256 /** 12257 * Sets the {@link #left}, {@link #top}, {@link #right} and {@link #bottom} values from 12258 * the given ViewHolder and sets the {@link #changeFlags} to the given flags parameter. 12259 * 12260 * @param holder The ViewHolder whose bounds should be copied. 12261 * @param flags The adapter change flags that were passed into 12262 * {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int, 12263 * List)}. 12264 * @return This {@link ItemHolderInfo} 12265 */ 12266 public ItemHolderInfo setFrom(RecyclerView.ViewHolder holder, 12267 @AdapterChanges int flags) { 12268 final View view = holder.itemView; 12269 this.left = view.getLeft(); 12270 this.top = view.getTop(); 12271 this.right = view.getRight(); 12272 this.bottom = view.getBottom(); 12273 return this; 12274 } 12275 } 12276 } 12277 12278 @Override 12279 protected int getChildDrawingOrder(int childCount, int i) { 12280 if (mChildDrawingOrderCallback == null) { 12281 return super.getChildDrawingOrder(childCount, i); 12282 } else { 12283 return mChildDrawingOrderCallback.onGetChildDrawingOrder(childCount, i); 12284 } 12285 } 12286 12287 /** 12288 * A callback interface that can be used to alter the drawing order of RecyclerView children. 12289 * <p> 12290 * It works using the {@link ViewGroup#getChildDrawingOrder(int, int)} method, so any case 12291 * that applies to that method also applies to this callback. For example, changing the drawing 12292 * order of two views will not have any effect if their elevation values are different since 12293 * elevation overrides the result of this callback. 12294 */ 12295 public interface ChildDrawingOrderCallback { 12296 /** 12297 * Returns the index of the child to draw for this iteration. Override this 12298 * if you want to change the drawing order of children. By default, it 12299 * returns i. 12300 * 12301 * @param i The current iteration. 12302 * @return The index of the child to draw this iteration. 12303 * 12304 * @see RecyclerView#setChildDrawingOrderCallback(RecyclerView.ChildDrawingOrderCallback) 12305 */ 12306 int onGetChildDrawingOrder(int childCount, int i); 12307 } 12308 12309 private NestedScrollingChildHelper getScrollingChildHelper() { 12310 if (mScrollingChildHelper == null) { 12311 mScrollingChildHelper = new NestedScrollingChildHelper(this); 12312 } 12313 return mScrollingChildHelper; 12314 } 12315} 12316