RecyclerView.java revision 4bacf13ec17763ba2e2d049d32a4a1dcca77a433
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 android.content.Context; 21import android.database.Observable; 22import android.graphics.Canvas; 23import android.graphics.PointF; 24import android.graphics.Rect; 25import android.os.Build; 26import android.os.Parcel; 27import android.os.Parcelable; 28import android.support.annotation.Nullable; 29import android.support.v4.util.ArrayMap; 30import android.support.v4.view.MotionEventCompat; 31import android.support.v4.view.VelocityTrackerCompat; 32import android.support.v4.view.ViewCompat; 33import android.support.v4.widget.EdgeEffectCompat; 34import android.support.v4.widget.ScrollerCompat; 35import static android.support.v7.widget.AdapterHelper.UpdateOp; 36import static android.support.v7.widget.AdapterHelper.Callback; 37import android.util.AttributeSet; 38import android.util.Log; 39import android.util.SparseArray; 40import android.util.SparseIntArray; 41import android.view.FocusFinder; 42import android.view.MotionEvent; 43import android.view.VelocityTracker; 44import android.view.View; 45import android.view.ViewConfiguration; 46import android.view.ViewGroup; 47import android.view.ViewParent; 48import android.view.animation.Interpolator; 49 50import java.util.ArrayList; 51import java.util.Collections; 52import java.util.List; 53 54/** 55 * A flexible view for providing a limited window into a large data set. 56 * 57 * <h3>Glossary of terms:</h3> 58 * 59 * <ul> 60 * <li><em>Adapter:</em> A subclass of {@link Adapter} responsible for providing views 61 * that represent items in a data set.</li> 62 * <li><em>Position:</em> The position of a data item within an <em>Adapter</em>.</li> 63 * <li><em>Index:</em> The index of an attached child view as used in a call to 64 * {@link ViewGroup#getChildAt}. Contrast with <em>Position.</em></li> 65 * <li><em>Binding:</em> The process of preparing a child view to display data corresponding 66 * to a <em>position</em> within the adapter.</li> 67 * <li><em>Recycle (view):</em> A view previously used to display data for a specific adapter 68 * position may be placed in a cache for later reuse to display the same type of data again 69 * later. This can drastically improve performance by skipping initial layout inflation 70 * or construction.</li> 71 * <li><em>Scrap (view):</em> A child view that has entered into a temporarily detached 72 * state during layout. Scrap views may be reused without becoming fully detached 73 * from the parent RecyclerView, either unmodified if no rebinding is required or modified 74 * by the adapter if the view was considered <em>dirty</em>.</li> 75 * <li><em>Dirty (view):</em> A child view that must be rebound by the adapter before 76 * being displayed.</li> 77 * </ul> 78 */ 79public class RecyclerView extends ViewGroup { 80 private static final String TAG = "RecyclerView"; 81 82 private static final boolean DEBUG = false; 83 84 /** 85 * On Kitkat, there is a bug which prevents DisplayList from being invalidated if a View is two 86 * levels deep(wrt to ViewHolder.itemView). DisplayList can be invalidated by setting 87 * View's visibility to INVISIBLE when View is detached. On Kitkat, Recycler recursively 88 * traverses itemView and invalidates display list for each ViewGroup that matches this 89 * criteria. 90 */ 91 private static final boolean FORCE_INVALIDATE_DISPLAY_LIST = Build.VERSION.SDK_INT == 19 || 92 Build.VERSION.SDK_INT == 20; 93 94 private static final boolean DISPATCH_TEMP_DETACH = false; 95 public static final int HORIZONTAL = 0; 96 public static final int VERTICAL = 1; 97 98 public static final int NO_POSITION = -1; 99 public static final long NO_ID = -1; 100 public static final int INVALID_TYPE = -1; 101 102 private static final int MAX_SCROLL_DURATION = 2000; 103 104 private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver(); 105 106 final Recycler mRecycler = new Recycler(); 107 108 private SavedState mPendingSavedState; 109 110 AdapterHelper mAdapterHelper; 111 112 ChildHelper mChildHelper; 113 114 final List<View> mDisappearingViewsInLayoutPass = new ArrayList<View>(); 115 116 /** 117 * Prior to L, there is no way to query this variable which is why we override the setter and 118 * track it here. 119 */ 120 private boolean mClipToPadding; 121 122 /** 123 * Note: this Runnable is only ever posted if: 124 * 1) We've been through first layout 125 * 2) We know we have a fixed size (mHasFixedSize) 126 * 3) We're attached 127 */ 128 private final Runnable mUpdateChildViewsRunnable = new Runnable() { 129 public void run() { 130 if (!mAdapterHelper.hasPendingUpdates()) { 131 return; 132 } 133 if (!mFirstLayoutComplete) { 134 // a layout request will happen, we should not do layout here. 135 return; 136 } 137 if (mDataSetHasChangedAfterLayout) { 138 dispatchLayout(); 139 } else { 140 eatRequestLayout(); 141 mAdapterHelper.preProcess(); 142 if (!mLayoutRequestEaten) { 143 // We run this after pre-processing is complete so that ViewHolders have their 144 // final adapter positions. No need to run it if a layout is already requested. 145 rebindUpdatedViewHolders(); 146 } 147 resumeRequestLayout(true); 148 } 149 } 150 }; 151 152 private final Rect mTempRect = new Rect(); 153 private Adapter mAdapter; 154 private LayoutManager mLayout; 155 private RecyclerListener mRecyclerListener; 156 private final ArrayList<ItemDecoration> mItemDecorations = new ArrayList<ItemDecoration>(); 157 private final ArrayList<OnItemTouchListener> mOnItemTouchListeners = 158 new ArrayList<OnItemTouchListener>(); 159 private OnItemTouchListener mActiveOnItemTouchListener; 160 private boolean mIsAttached; 161 private boolean mHasFixedSize; 162 private boolean mFirstLayoutComplete; 163 private boolean mEatRequestLayout; 164 private boolean mLayoutRequestEaten; 165 private boolean mAdapterUpdateDuringMeasure; 166 private final boolean mPostUpdatesOnAnimation; 167 168 /** 169 * Set to true when an adapter data set changed notification is received. 170 * In that case, we cannot run any animations since we don't know what happened. 171 */ 172 private boolean mDataSetHasChangedAfterLayout = false; 173 174 /** 175 * This variable is set to true during a dispatchLayout and/or scroll. 176 * Some methods should not be called during these periods (e.g. adapter data change). 177 * Doing so will create hard to find bugs so we better check it and throw an exception. 178 * 179 * @see #assertInLayoutOrScroll(String) 180 * @see #assertNotInLayoutOrScroll(String) 181 */ 182 private boolean mRunningLayoutOrScroll = false; 183 184 private EdgeEffectCompat mLeftGlow, mTopGlow, mRightGlow, mBottomGlow; 185 186 ItemAnimator mItemAnimator = new DefaultItemAnimator(); 187 188 private static final int INVALID_POINTER = -1; 189 190 /** 191 * The RecyclerView is not currently scrolling. 192 * @see #getScrollState() 193 */ 194 public static final int SCROLL_STATE_IDLE = 0; 195 196 /** 197 * The RecyclerView is currently being dragged by outside input such as user touch input. 198 * @see #getScrollState() 199 */ 200 public static final int SCROLL_STATE_DRAGGING = 1; 201 202 /** 203 * The RecyclerView is currently animating to a final position while not under 204 * outside control. 205 * @see #getScrollState() 206 */ 207 public static final int SCROLL_STATE_SETTLING = 2; 208 209 // Touch/scrolling handling 210 211 private int mScrollState = SCROLL_STATE_IDLE; 212 private int mScrollPointerId = INVALID_POINTER; 213 private VelocityTracker mVelocityTracker; 214 private int mInitialTouchX; 215 private int mInitialTouchY; 216 private int mLastTouchX; 217 private int mLastTouchY; 218 private final int mTouchSlop; 219 private final int mMinFlingVelocity; 220 private final int mMaxFlingVelocity; 221 222 private final ViewFlinger mViewFlinger = new ViewFlinger(); 223 224 final State mState = new State(); 225 226 private OnScrollListener mScrollListener; 227 228 // For use in item animations 229 boolean mItemsAddedOrRemoved = false; 230 boolean mItemsChanged = false; 231 private ItemAnimator.ItemAnimatorListener mItemAnimatorListener = 232 new ItemAnimatorRestoreListener(); 233 private boolean mPostedAnimatorRunner = false; 234 private Runnable mItemAnimatorRunner = new Runnable() { 235 @Override 236 public void run() { 237 if (mItemAnimator != null) { 238 mItemAnimator.runPendingAnimations(); 239 } 240 mPostedAnimatorRunner = false; 241 } 242 }; 243 244 private static final Interpolator sQuinticInterpolator = new Interpolator() { 245 public float getInterpolation(float t) { 246 t -= 1.0f; 247 return t * t * t * t * t + 1.0f; 248 } 249 }; 250 251 public RecyclerView(Context context) { 252 this(context, null); 253 } 254 255 public RecyclerView(Context context, AttributeSet attrs) { 256 this(context, attrs, 0); 257 } 258 259 public RecyclerView(Context context, AttributeSet attrs, int defStyle) { 260 super(context, attrs, defStyle); 261 262 final int version = Build.VERSION.SDK_INT; 263 mPostUpdatesOnAnimation = version >= 16; 264 265 final ViewConfiguration vc = ViewConfiguration.get(context); 266 mTouchSlop = vc.getScaledTouchSlop(); 267 mMinFlingVelocity = vc.getScaledMinimumFlingVelocity(); 268 mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity(); 269 setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER); 270 271 mItemAnimator.setListener(mItemAnimatorListener); 272 initAdapterManager(); 273 initChildrenHelper(); 274 } 275 276 private void initChildrenHelper() { 277 mChildHelper = new ChildHelper(new ChildHelper.Callback() { 278 @Override 279 public int getChildCount() { 280 return RecyclerView.this.getChildCount(); 281 } 282 283 @Override 284 public void addView(View child, int index) { 285 RecyclerView.this.addView(child, index); 286 } 287 288 @Override 289 public int indexOfChild(View view) { 290 return RecyclerView.this.indexOfChild(view); 291 } 292 293 @Override 294 public void removeViewAt(int index) { 295 RecyclerView.this.removeViewAt(index); 296 } 297 298 @Override 299 public View getChildAt(int offset) { 300 return RecyclerView.this.getChildAt(offset); 301 } 302 303 @Override 304 public void removeAllViews() { 305 RecyclerView.this.removeAllViews(); 306 } 307 308 @Override 309 public ViewHolder getChildViewHolder(View view) { 310 return getChildViewHolderInt(view); 311 } 312 313 @Override 314 public void attachViewToParent(View child, int index, 315 ViewGroup.LayoutParams layoutParams) { 316 RecyclerView.this.attachViewToParent(child, index, layoutParams); 317 } 318 319 @Override 320 public void detachViewFromParent(int offset) { 321 RecyclerView.this.detachViewFromParent(offset); 322 } 323 }); 324 } 325 326 void initAdapterManager() { 327 mAdapterHelper = new AdapterHelper(new Callback() { 328 @Override 329 public ViewHolder findViewHolder(int position) { 330 return findViewHolderForPosition(position, true); 331 } 332 333 @Override 334 public void offsetPositionsForRemovingInvisible(int start, int count) { 335 offsetPositionRecordsForRemove(start, count, true); 336 mItemsAddedOrRemoved = true; 337 mState.mDeletedInvisibleItemCountSincePreviousLayout += count; 338 } 339 340 @Override 341 public void offsetPositionsForRemovingLaidOutOrNewView(int positionStart, int itemCount) { 342 offsetPositionRecordsForRemove(positionStart, itemCount, false); 343 mItemsAddedOrRemoved = true; 344 } 345 346 @Override 347 public void markViewHoldersUpdated(int positionStart, int itemCount) { 348 viewRangeUpdate(positionStart, itemCount); 349 mItemsChanged = true; 350 } 351 352 @Override 353 public void onDispatchFirstPass(UpdateOp op) { 354 dispatchUpdate(op); 355 } 356 357 void dispatchUpdate(UpdateOp op) { 358 switch (op.cmd) { 359 case UpdateOp.ADD: 360 mLayout.onItemsAdded(RecyclerView.this, op.positionStart, op.itemCount); 361 break; 362 case UpdateOp.REMOVE: 363 mLayout.onItemsRemoved(RecyclerView.this, op.positionStart, op.itemCount); 364 break; 365 case UpdateOp.UPDATE: 366 mLayout.onItemsUpdated(RecyclerView.this, op.positionStart, op.itemCount); 367 break; 368 case UpdateOp.MOVE: 369 mLayout.onItemsMoved(RecyclerView.this, op.positionStart, op.itemCount, 1); 370 break; 371 } 372 } 373 374 @Override 375 public void onDispatchSecondPass(UpdateOp op) { 376 dispatchUpdate(op); 377 } 378 379 @Override 380 public void offsetPositionsForAdd(int positionStart, int itemCount) { 381 offsetPositionRecordsForInsert(positionStart, itemCount); 382 mItemsAddedOrRemoved = true; 383 } 384 385 @Override 386 public void offsetPositionsForMove(int from, int to) { 387 offsetPositionRecordsForMove(from, to); 388 // should we create mItemsMoved ? 389 mItemsAddedOrRemoved = true; 390 } 391 }); 392 } 393 394 /** 395 * RecyclerView can perform several optimizations if it can know in advance that changes in 396 * adapter content cannot change the size of the RecyclerView itself. 397 * If your use of RecyclerView falls into this category, set this to true. 398 * 399 * @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView. 400 */ 401 public void setHasFixedSize(boolean hasFixedSize) { 402 mHasFixedSize = hasFixedSize; 403 } 404 405 /** 406 * @return true if the app has specified that changes in adapter content cannot change 407 * the size of the RecyclerView itself. 408 */ 409 public boolean hasFixedSize() { 410 return mHasFixedSize; 411 } 412 413 @Override 414 public void setClipToPadding(boolean clipToPadding) { 415 if (clipToPadding != mClipToPadding) { 416 invalidateGlows(); 417 } 418 mClipToPadding = clipToPadding; 419 super.setClipToPadding(clipToPadding); 420 if (mFirstLayoutComplete) { 421 requestLayout(); 422 } 423 } 424 425 /** 426 * Swaps the current adapter with the provided one. It is similar to 427 * {@link #setAdapter(Adapter)} but assumes existing adapter and the new adapter uses the same 428 * {@link ViewHolder} and does not clear the RecycledViewPool. 429 * <p> 430 * Note that it still calls onAdapterChanged callbacks. 431 * 432 * @param adapter The new adapter to set, or null to set no adapter. 433 * @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing 434 * Views. If adapters have stable ids and/or you want to 435 * animate the disappearing views, you may prefer to set 436 * this to false. 437 * @see #setAdapter(Adapter) 438 */ 439 public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) { 440 setAdapterInternal(adapter, true, removeAndRecycleExistingViews); 441 mDataSetHasChangedAfterLayout = true; 442 requestLayout(); 443 } 444 /** 445 * Set a new adapter to provide child views on demand. 446 * <p> 447 * When adapter is changed, all existing views are recycled back to the pool. If the pool has 448 * only one adapter, it will be cleared. 449 * 450 * @param adapter The new adapter to set, or null to set no adapter. 451 * @see #swapAdapter(Adapter, boolean) 452 */ 453 public void setAdapter(Adapter adapter) { 454 setAdapterInternal(adapter, false, true); 455 requestLayout(); 456 } 457 458 /** 459 * Replaces the current adapter with the new one and triggers listeners. 460 * @param adapter The new adapter 461 * @param compatibleWithPrevious If true, the new adapter is using the same View Holders and 462 * item types with the current adapter (helps us avoid cache 463 * invalidation). 464 * @param removeAndRecycleViews If true, we'll remove and recycle all existing views. If 465 * compatibleWithPrevious is false, this parameter is ignored. 466 */ 467 private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious, 468 boolean removeAndRecycleViews) { 469 if (mAdapter != null) { 470 mAdapter.unregisterAdapterDataObserver(mObserver); 471 } 472 if (!compatibleWithPrevious || removeAndRecycleViews) { 473 // end all running animations 474 if (mItemAnimator != null) { 475 mItemAnimator.endAnimations(); 476 } 477 // Since animations are ended, mLayout.children should be equal to 478 // recyclerView.children. This may not be true if item animator's end does not work as 479 // expected. (e.g. not release children instantly). It is safer to use mLayout's child 480 // count. 481 if (mLayout != null) { 482 mLayout.removeAndRecycleAllViews(mRecycler); 483 mLayout.removeAndRecycleScrapInt(mRecycler, true); 484 } 485 } 486 mAdapterHelper.reset(); 487 final Adapter oldAdapter = mAdapter; 488 mAdapter = adapter; 489 if (adapter != null) { 490 adapter.registerAdapterDataObserver(mObserver); 491 } 492 if (mLayout != null) { 493 mLayout.onAdapterChanged(oldAdapter, mAdapter); 494 } 495 mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious); 496 mState.mStructureChanged = true; 497 markKnownViewsInvalid(); 498 } 499 500 /** 501 * Retrieves the previously set adapter or null if no adapter is set. 502 * 503 * @return The previously set adapter 504 * @see #setAdapter(Adapter) 505 */ 506 public Adapter getAdapter() { 507 return mAdapter; 508 } 509 510 /** 511 * Register a listener that will be notified whenever a child view is recycled. 512 * 513 * <p>This listener will be called when a LayoutManager or the RecyclerView decides 514 * that a child view is no longer needed. If an application associates expensive 515 * or heavyweight data with item views, this may be a good place to release 516 * or free those resources.</p> 517 * 518 * @param listener Listener to register, or null to clear 519 */ 520 public void setRecyclerListener(RecyclerListener listener) { 521 mRecyclerListener = listener; 522 } 523 524 /** 525 * Set the {@link LayoutManager} that this RecyclerView will use. 526 * 527 * <p>In contrast to other adapter-backed views such as {@link android.widget.ListView} 528 * or {@link android.widget.GridView}, RecyclerView allows client code to provide custom 529 * layout arrangements for child views. These arrangements are controlled by the 530 * {@link LayoutManager}. A LayoutManager must be provided for RecyclerView to function.</p> 531 * 532 * <p>Several default strategies are provided for common uses such as lists and grids.</p> 533 * 534 * @param layout LayoutManager to use 535 */ 536 public void setLayoutManager(LayoutManager layout) { 537 if (layout == mLayout) { 538 return; 539 } 540 // TODO We should do this switch a dispachLayout pass and animate children. There is a good 541 // chance that LayoutManagers will re-use views. 542 if (mLayout != null) { 543 if (mIsAttached) { 544 mLayout.onDetachedFromWindow(this, mRecycler); 545 } 546 mLayout.setRecyclerView(null); 547 } 548 mRecycler.clear(); 549 mChildHelper.removeAllViewsUnfiltered(); 550 mLayout = layout; 551 if (layout != null) { 552 if (layout.mRecyclerView != null) { 553 throw new IllegalArgumentException("LayoutManager " + layout + 554 " is already attached to a RecyclerView: " + layout.mRecyclerView); 555 } 556 mLayout.setRecyclerView(this); 557 if (mIsAttached) { 558 mLayout.onAttachedToWindow(this); 559 } 560 } 561 requestLayout(); 562 } 563 564 @Override 565 protected Parcelable onSaveInstanceState() { 566 SavedState state = new SavedState(super.onSaveInstanceState()); 567 if (mPendingSavedState != null) { 568 state.copyFrom(mPendingSavedState); 569 } else if (mLayout != null) { 570 state.mLayoutState = mLayout.onSaveInstanceState(); 571 } else { 572 state.mLayoutState = null; 573 } 574 575 return state; 576 } 577 578 @Override 579 protected void onRestoreInstanceState(Parcelable state) { 580 mPendingSavedState = (SavedState) state; 581 super.onRestoreInstanceState(mPendingSavedState.getSuperState()); 582 if (mLayout != null && mPendingSavedState.mLayoutState != null) { 583 mLayout.onRestoreInstanceState(mPendingSavedState.mLayoutState); 584 } 585 } 586 587 /** 588 * Adds a view to the animatingViews list. 589 * mAnimatingViews holds the child views that are currently being kept around 590 * purely for the purpose of being animated out of view. They are drawn as a regular 591 * part of the child list of the RecyclerView, but they are invisible to the LayoutManager 592 * as they are managed separately from the regular child views. 593 * @param view The view to be removed 594 */ 595 private void addAnimatingView(View view) { 596 final boolean alreadyParented = view.getParent() == this; 597 mRecycler.unscrapView(getChildViewHolder(view)); 598 if (!alreadyParented) { 599 mChildHelper.addView(view, true); 600 } else { 601 mChildHelper.hide(view); 602 } 603 } 604 605 /** 606 * Removes a view from the animatingViews list. 607 * @param view The view to be removed 608 * @see #addAnimatingView(View) 609 */ 610 private void removeAnimatingView(View view) { 611 eatRequestLayout(); 612 if (mChildHelper.removeViewIfHidden(view)) { 613 final ViewHolder viewHolder = getChildViewHolderInt(view); 614 mRecycler.unscrapView(viewHolder); 615 mRecycler.recycleViewHolderInternal(viewHolder); 616 if (DEBUG) { 617 Log.d(TAG, "after removing animated view: " + view + ", " + this); 618 } 619 } 620 resumeRequestLayout(false); 621 } 622 623 /** 624 * Return the {@link LayoutManager} currently responsible for 625 * layout policy for this RecyclerView. 626 * 627 * @return The currently bound LayoutManager 628 */ 629 public LayoutManager getLayoutManager() { 630 return mLayout; 631 } 632 633 /** 634 * Retrieve this RecyclerView's {@link RecycledViewPool}. This method will never return null; 635 * if no pool is set for this view a new one will be created. See 636 * {@link #setRecycledViewPool(RecycledViewPool) setRecycledViewPool} for more information. 637 * 638 * @return The pool used to store recycled item views for reuse. 639 * @see #setRecycledViewPool(RecycledViewPool) 640 */ 641 public RecycledViewPool getRecycledViewPool() { 642 return mRecycler.getRecycledViewPool(); 643 } 644 645 /** 646 * Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views. 647 * This can be useful if you have multiple RecyclerViews with adapters that use the same 648 * view types, for example if you have several data sets with the same kinds of item views 649 * displayed by a {@link android.support.v4.view.ViewPager ViewPager}. 650 * 651 * @param pool Pool to set. If this parameter is null a new pool will be created and used. 652 */ 653 public void setRecycledViewPool(RecycledViewPool pool) { 654 mRecycler.setRecycledViewPool(pool); 655 } 656 657 /** 658 * Sets a new {@link ViewCacheExtension} to be used by the Recycler. 659 * 660 * @param extension ViewCacheExtension to be used or null if you want to clear the existing one. 661 * 662 * @see {@link ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)} 663 */ 664 public void setViewCacheExtension(ViewCacheExtension extension) { 665 mRecycler.setViewCacheExtension(extension); 666 } 667 668 /** 669 * Set the number of offscreen views to retain before adding them to the potentially shared 670 * {@link #getRecycledViewPool() recycled view pool}. 671 * 672 * <p>The offscreen view cache stays aware of changes in the attached adapter, allowing 673 * a LayoutManager to reuse those views unmodified without needing to return to the adapter 674 * to rebind them.</p> 675 * 676 * @param size Number of views to cache offscreen before returning them to the general 677 * recycled view pool 678 */ 679 public void setItemViewCacheSize(int size) { 680 mRecycler.setViewCacheSize(size); 681 } 682 683 /** 684 * Return the current scrolling state of the RecyclerView. 685 * 686 * @return {@link #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or 687 * {@link #SCROLL_STATE_SETTLING} 688 */ 689 public int getScrollState() { 690 return mScrollState; 691 } 692 693 private void setScrollState(int state) { 694 if (state == mScrollState) { 695 return; 696 } 697 mScrollState = state; 698 if (state != SCROLL_STATE_SETTLING) { 699 stopScroll(); 700 } 701 if (mScrollListener != null) { 702 mScrollListener.onScrollStateChanged(this, state); 703 } 704 mLayout.onScrollStateChanged(state); 705 } 706 707 /** 708 * Add an {@link ItemDecoration} to this RecyclerView. Item decorations can 709 * affect both measurement and drawing of individual item views. 710 * 711 * <p>Item decorations are ordered. Decorations placed earlier in the list will 712 * be run/queried/drawn first for their effects on item views. Padding added to views 713 * will be nested; a padding added by an earlier decoration will mean further 714 * item decorations in the list will be asked to draw/pad within the previous decoration's 715 * given area.</p> 716 * 717 * @param decor Decoration to add 718 * @param index Position in the decoration chain to insert this decoration at. If this value 719 * is negative the decoration will be added at the end. 720 */ 721 public void addItemDecoration(ItemDecoration decor, int index) { 722 if (mLayout != null) { 723 mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll or" 724 + " layout"); 725 } 726 if (mItemDecorations.isEmpty()) { 727 setWillNotDraw(false); 728 } 729 if (index < 0) { 730 mItemDecorations.add(decor); 731 } else { 732 mItemDecorations.add(index, decor); 733 } 734 markItemDecorInsetsDirty(); 735 requestLayout(); 736 } 737 738 /** 739 * Add an {@link ItemDecoration} to this RecyclerView. Item decorations can 740 * affect both measurement and drawing of individual item views. 741 * 742 * <p>Item decorations are ordered. Decorations placed earlier in the list will 743 * be run/queried/drawn first for their effects on item views. Padding added to views 744 * will be nested; a padding added by an earlier decoration will mean further 745 * item decorations in the list will be asked to draw/pad within the previous decoration's 746 * given area.</p> 747 * 748 * @param decor Decoration to add 749 */ 750 public void addItemDecoration(ItemDecoration decor) { 751 addItemDecoration(decor, -1); 752 } 753 754 /** 755 * Remove an {@link ItemDecoration} from this RecyclerView. 756 * 757 * <p>The given decoration will no longer impact the measurement and drawing of 758 * item views.</p> 759 * 760 * @param decor Decoration to remove 761 * @see #addItemDecoration(ItemDecoration) 762 */ 763 public void removeItemDecoration(ItemDecoration decor) { 764 if (mLayout != null) { 765 mLayout.assertNotInLayoutOrScroll("Cannot remove item decoration during a scroll or" 766 + " layout"); 767 } 768 mItemDecorations.remove(decor); 769 if (mItemDecorations.isEmpty()) { 770 setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER); 771 } 772 markItemDecorInsetsDirty(); 773 requestLayout(); 774 } 775 776 /** 777 * Set a listener that will be notified of any changes in scroll state or position. 778 * 779 * @param listener Listener to set or null to clear 780 */ 781 public void setOnScrollListener(OnScrollListener listener) { 782 mScrollListener = listener; 783 } 784 785 /** 786 * Convenience method to scroll to a certain position. 787 * 788 * RecyclerView does not implement scrolling logic, rather forwards the call to 789 * {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)} 790 * @param position Scroll to this adapter position 791 * @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int) 792 */ 793 public void scrollToPosition(int position) { 794 stopScroll(); 795 mLayout.scrollToPosition(position); 796 awakenScrollBars(); 797 } 798 799 /** 800 * Starts a smooth scroll to an adapter position. 801 * <p> 802 * To support smooth scrolling, you must override 803 * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a 804 * {@link SmoothScroller}. 805 * <p> 806 * {@link LayoutManager} is responsible for creating the actual scroll action. If you want to 807 * provide a custom smooth scroll logic, override 808 * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your 809 * LayoutManager. 810 * 811 * @param position The adapter position to scroll to 812 * @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int) 813 */ 814 public void smoothScrollToPosition(int position) { 815 mLayout.smoothScrollToPosition(this, mState, position); 816 } 817 818 @Override 819 public void scrollTo(int x, int y) { 820 throw new UnsupportedOperationException( 821 "RecyclerView does not support scrolling to an absolute position."); 822 } 823 824 @Override 825 public void scrollBy(int x, int y) { 826 if (mLayout == null) { 827 throw new IllegalStateException("Cannot scroll without a LayoutManager set. " + 828 "Call setLayoutManager with a non-null argument."); 829 } 830 final boolean canScrollHorizontal = mLayout.canScrollHorizontally(); 831 final boolean canScrollVertical = mLayout.canScrollVertically(); 832 if (canScrollHorizontal || canScrollVertical) { 833 scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0); 834 } 835 } 836 837 /** 838 * Helper method reflect data changes to the state. 839 * <p> 840 * Adapter changes during a scroll may trigger a crash because scroll assumes no data change 841 * but data actually changed. 842 * <p> 843 * This method consumes all deferred changes to avoid that case. 844 */ 845 private void consumePendingUpdateOperations() { 846 if (mAdapterHelper.hasPendingUpdates()) { 847 mUpdateChildViewsRunnable.run(); 848 } 849 } 850 851 /** 852 * Does not perform bounds checking. Used by internal methods that have already validated input. 853 */ 854 void scrollByInternal(int x, int y) { 855 int overscrollX = 0, overscrollY = 0; 856 int hresult = 0, vresult = 0; 857 consumePendingUpdateOperations(); 858 if (mAdapter != null) { 859 eatRequestLayout(); 860 mRunningLayoutOrScroll = true; 861 if (x != 0) { 862 hresult = mLayout.scrollHorizontallyBy(x, mRecycler, mState); 863 overscrollX = x - hresult; 864 } 865 if (y != 0) { 866 vresult = mLayout.scrollVerticallyBy(y, mRecycler, mState); 867 overscrollY = y - vresult; 868 } 869 if (supportsChangeAnimations()) { 870 // Fix up shadow views used by changing animations 871 int count = mChildHelper.getChildCount(); 872 for (int i = 0; i < count; i++) { 873 View view = mChildHelper.getChildAt(i); 874 ViewHolder holder = getChildViewHolder(view); 875 if (holder != null && holder.mShadowingHolder != null) { 876 ViewHolder shadowingHolder = holder.mShadowingHolder; 877 View shadowingView = shadowingHolder != null ? shadowingHolder.itemView : null; 878 if (shadowingView != null) { 879 int left = view.getLeft(); 880 int top = view.getTop(); 881 if (left != shadowingView.getLeft() || top != shadowingView.getTop()) { 882 shadowingView.layout(left, top, 883 left + shadowingView.getWidth(), 884 top + shadowingView.getHeight()); 885 } 886 } 887 } 888 } 889 } 890 mRunningLayoutOrScroll = false; 891 resumeRequestLayout(false); 892 } 893 if (!mItemDecorations.isEmpty()) { 894 invalidate(); 895 } 896 if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) { 897 considerReleasingGlowsOnScroll(x, y); 898 pullGlows(overscrollX, overscrollY); 899 } 900 if (mScrollListener != null && (hresult != 0 || vresult != 0)) { 901 mScrollListener.onScrolled(this, hresult, vresult); 902 } 903 if (!awakenScrollBars()) { 904 invalidate(); 905 } 906 } 907 908 /** 909 * <p>Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal 910 * range. This value is used to compute the length of the thumb within the scrollbar's track. 911 * </p> 912 * 913 * <p>The range is expressed in arbitrary units that must be the same as the units used by 914 * {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollExtent()}.</p> 915 * 916 * <p>Default implementation returns 0.</p> 917 * 918 * <p>If you want to support scroll bars, override 919 * {@link RecyclerView.LayoutManager#computeHorizontalScrollOffset(RecyclerView.State)} in your 920 * LayoutManager. </p> 921 * 922 * @return The horizontal offset of the scrollbar's thumb 923 * @see android.support.v7.widget.RecyclerView.LayoutManager#computeHorizontalScrollOffset 924 * (RecyclerView.Adapter) 925 */ 926 @Override 927 protected int computeHorizontalScrollOffset() { 928 return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollOffset(mState) 929 : 0; 930 } 931 932 /** 933 * <p>Compute the horizontal extent of the horizontal scrollbar's thumb within the 934 * horizontal range. This value is used to compute the length of the thumb within the 935 * scrollbar's track.</p> 936 * 937 * <p>The range is expressed in arbitrary units that must be the same as the units used by 938 * {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollOffset()}.</p> 939 * 940 * <p>Default implementation returns 0.</p> 941 * 942 * <p>If you want to support scroll bars, override 943 * {@link RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)} in your 944 * LayoutManager.</p> 945 * 946 * @return The horizontal extent of the scrollbar's thumb 947 * @see RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State) 948 */ 949 @Override 950 protected int computeHorizontalScrollExtent() { 951 return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollExtent(mState) : 0; 952 } 953 954 /** 955 * <p>Compute the horizontal range that the horizontal scrollbar represents.</p> 956 * 957 * <p>The range is expressed in arbitrary units that must be the same as the units used by 958 * {@link #computeHorizontalScrollExtent()} and {@link #computeHorizontalScrollOffset()}.</p> 959 * 960 * <p>Default implementation returns 0.</p> 961 * 962 * <p>If you want to support scroll bars, override 963 * {@link RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)} in your 964 * LayoutManager.</p> 965 * 966 * @return The total horizontal range represented by the vertical scrollbar 967 * @see RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State) 968 */ 969 @Override 970 protected int computeHorizontalScrollRange() { 971 return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollRange(mState) : 0; 972 } 973 974 /** 975 * <p>Compute the vertical offset of the vertical scrollbar's thumb within the vertical range. 976 * This value is used to compute the length of the thumb within the scrollbar's track. </p> 977 * 978 * <p>The range is expressed in arbitrary units that must be the same as the units used by 979 * {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollExtent()}.</p> 980 * 981 * <p>Default implementation returns 0.</p> 982 * 983 * <p>If you want to support scroll bars, override 984 * {@link RecyclerView.LayoutManager#computeVerticalScrollOffset(RecyclerView.State)} in your 985 * LayoutManager.</p> 986 * 987 * @return The vertical offset of the scrollbar's thumb 988 * @see android.support.v7.widget.RecyclerView.LayoutManager#computeVerticalScrollOffset 989 * (RecyclerView.Adapter) 990 */ 991 @Override 992 protected int computeVerticalScrollOffset() { 993 return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollOffset(mState) : 0; 994 } 995 996 /** 997 * <p>Compute the vertical extent of the vertical scrollbar's thumb within the vertical range. 998 * This value is used to compute the length of the thumb within the scrollbar's track.</p> 999 * 1000 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1001 * {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollOffset()}.</p> 1002 * 1003 * <p>Default implementation returns 0.</p> 1004 * 1005 * <p>If you want to support scroll bars, override 1006 * {@link RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)} in your 1007 * LayoutManager.</p> 1008 * 1009 * @return The vertical extent of the scrollbar's thumb 1010 * @see RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State) 1011 */ 1012 @Override 1013 protected int computeVerticalScrollExtent() { 1014 return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollExtent(mState) : 0; 1015 } 1016 1017 /** 1018 * <p>Compute the vertical range that the vertical scrollbar represents.</p> 1019 * 1020 * <p>The range is expressed in arbitrary units that must be the same as the units used by 1021 * {@link #computeVerticalScrollExtent()} and {@link #computeVerticalScrollOffset()}.</p> 1022 * 1023 * <p>Default implementation returns 0.</p> 1024 * 1025 * <p>If you want to support scroll bars, override 1026 * {@link RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)} in your 1027 * LayoutManager.</p> 1028 * 1029 * @return The total vertical range represented by the vertical scrollbar 1030 * @see RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State) 1031 */ 1032 @Override 1033 protected int computeVerticalScrollRange() { 1034 return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollRange(mState) : 0; 1035 } 1036 1037 1038 void eatRequestLayout() { 1039 if (!mEatRequestLayout) { 1040 mEatRequestLayout = true; 1041 mLayoutRequestEaten = false; 1042 } 1043 } 1044 1045 void resumeRequestLayout(boolean performLayoutChildren) { 1046 if (mEatRequestLayout) { 1047 if (performLayoutChildren && mLayoutRequestEaten && 1048 mLayout != null && mAdapter != null) { 1049 dispatchLayout(); 1050 } 1051 mEatRequestLayout = false; 1052 mLayoutRequestEaten = false; 1053 } 1054 } 1055 1056 /** 1057 * Animate a scroll by the given amount of pixels along either axis. 1058 * 1059 * @param dx Pixels to scroll horizontally 1060 * @param dy Pixels to scroll vertically 1061 */ 1062 public void smoothScrollBy(int dx, int dy) { 1063 if (dx != 0 || dy != 0) { 1064 mViewFlinger.smoothScrollBy(dx, dy); 1065 } 1066 } 1067 1068 /** 1069 * Begin a standard fling with an initial velocity along each axis in pixels per second. 1070 * If the velocity given is below the system-defined minimum this method will return false 1071 * and no fling will occur. 1072 * 1073 * @param velocityX Initial horizontal velocity in pixels per second 1074 * @param velocityY Initial vertical velocity in pixels per second 1075 * @return true if the fling was started, false if the velocity was too low to fling 1076 */ 1077 public boolean fling(int velocityX, int velocityY) { 1078 if (Math.abs(velocityX) < mMinFlingVelocity) { 1079 velocityX = 0; 1080 } 1081 if (Math.abs(velocityY) < mMinFlingVelocity) { 1082 velocityY = 0; 1083 } 1084 velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity)); 1085 velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity)); 1086 if (velocityX != 0 || velocityY != 0) { 1087 mViewFlinger.fling(velocityX, velocityY); 1088 return true; 1089 } 1090 return false; 1091 } 1092 1093 /** 1094 * Stop any current scroll in progress, such as one started by 1095 * {@link #smoothScrollBy(int, int)}, {@link #fling(int, int)} or a touch-initiated fling. 1096 */ 1097 public void stopScroll() { 1098 mViewFlinger.stop(); 1099 mLayout.stopSmoothScroller(); 1100 } 1101 1102 /** 1103 * Apply a pull to relevant overscroll glow effects 1104 */ 1105 private void pullGlows(int overscrollX, int overscrollY) { 1106 if (overscrollX < 0) { 1107 ensureLeftGlow(); 1108 mLeftGlow.onPull(-overscrollX / (float) getWidth()); 1109 } else if (overscrollX > 0) { 1110 ensureRightGlow(); 1111 mRightGlow.onPull(overscrollX / (float) getWidth()); 1112 } 1113 1114 if (overscrollY < 0) { 1115 ensureTopGlow(); 1116 mTopGlow.onPull(-overscrollY / (float) getHeight()); 1117 } else if (overscrollY > 0) { 1118 ensureBottomGlow(); 1119 mBottomGlow.onPull(overscrollY / (float) getHeight()); 1120 } 1121 1122 if (overscrollX != 0 || overscrollY != 0) { 1123 ViewCompat.postInvalidateOnAnimation(this); 1124 } 1125 } 1126 1127 private void releaseGlows() { 1128 boolean needsInvalidate = false; 1129 if (mLeftGlow != null) needsInvalidate = mLeftGlow.onRelease(); 1130 if (mTopGlow != null) needsInvalidate |= mTopGlow.onRelease(); 1131 if (mRightGlow != null) needsInvalidate |= mRightGlow.onRelease(); 1132 if (mBottomGlow != null) needsInvalidate |= mBottomGlow.onRelease(); 1133 if (needsInvalidate) { 1134 ViewCompat.postInvalidateOnAnimation(this); 1135 } 1136 } 1137 1138 private void considerReleasingGlowsOnScroll(int dx, int dy) { 1139 boolean needsInvalidate = false; 1140 if (mLeftGlow != null && !mLeftGlow.isFinished() && dx > 0) { 1141 needsInvalidate = mLeftGlow.onRelease(); 1142 } 1143 if (mRightGlow != null && !mRightGlow.isFinished() && dx < 0) { 1144 needsInvalidate |= mRightGlow.onRelease(); 1145 } 1146 if (mTopGlow != null && !mTopGlow.isFinished() && dy > 0) { 1147 needsInvalidate |= mTopGlow.onRelease(); 1148 } 1149 if (mBottomGlow != null && !mBottomGlow.isFinished() && dy < 0) { 1150 needsInvalidate |= mBottomGlow.onRelease(); 1151 } 1152 if (needsInvalidate) { 1153 ViewCompat.postInvalidateOnAnimation(this); 1154 } 1155 } 1156 1157 void absorbGlows(int velocityX, int velocityY) { 1158 if (velocityX < 0) { 1159 ensureLeftGlow(); 1160 mLeftGlow.onAbsorb(-velocityX); 1161 } else if (velocityX > 0) { 1162 ensureRightGlow(); 1163 mRightGlow.onAbsorb(velocityX); 1164 } 1165 1166 if (velocityY < 0) { 1167 ensureTopGlow(); 1168 mTopGlow.onAbsorb(-velocityY); 1169 } else if (velocityY > 0) { 1170 ensureBottomGlow(); 1171 mBottomGlow.onAbsorb(velocityY); 1172 } 1173 1174 if (velocityX != 0 || velocityY != 0) { 1175 ViewCompat.postInvalidateOnAnimation(this); 1176 } 1177 } 1178 1179 void ensureLeftGlow() { 1180 if (mLeftGlow != null) { 1181 return; 1182 } 1183 mLeftGlow = new EdgeEffectCompat(getContext()); 1184 if (mClipToPadding) { 1185 mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), 1186 getMeasuredWidth() - getPaddingLeft() - getPaddingRight()); 1187 } else { 1188 mLeftGlow.setSize(getMeasuredHeight(), getMeasuredWidth()); 1189 } 1190 } 1191 1192 void ensureRightGlow() { 1193 if (mRightGlow != null) { 1194 return; 1195 } 1196 mRightGlow = new EdgeEffectCompat(getContext()); 1197 if (mClipToPadding) { 1198 mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), 1199 getMeasuredWidth() - getPaddingLeft() - getPaddingRight()); 1200 } else { 1201 mRightGlow.setSize(getMeasuredHeight(), getMeasuredWidth()); 1202 } 1203 } 1204 1205 void ensureTopGlow() { 1206 if (mTopGlow != null) { 1207 return; 1208 } 1209 mTopGlow = new EdgeEffectCompat(getContext()); 1210 if (mClipToPadding) { 1211 mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), 1212 getMeasuredHeight() - getPaddingTop() - getPaddingBottom()); 1213 } else { 1214 mTopGlow.setSize(getMeasuredWidth(), getMeasuredHeight()); 1215 } 1216 1217 } 1218 1219 void ensureBottomGlow() { 1220 if (mBottomGlow != null) { 1221 return; 1222 } 1223 mBottomGlow = new EdgeEffectCompat(getContext()); 1224 if (mClipToPadding) { 1225 mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), 1226 getMeasuredHeight() - getPaddingTop() - getPaddingBottom()); 1227 } else { 1228 mBottomGlow.setSize(getMeasuredWidth(), getMeasuredHeight()); 1229 } 1230 } 1231 1232 void invalidateGlows() { 1233 mLeftGlow = mRightGlow = mTopGlow = mBottomGlow = null; 1234 } 1235 1236 // Focus handling 1237 1238 @Override 1239 public View focusSearch(View focused, int direction) { 1240 View result = mLayout.onInterceptFocusSearch(focused, direction); 1241 if (result != null) { 1242 return result; 1243 } 1244 final FocusFinder ff = FocusFinder.getInstance(); 1245 result = ff.findNextFocus(this, focused, direction); 1246 if (result == null && mAdapter != null) { 1247 eatRequestLayout(); 1248 result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState); 1249 resumeRequestLayout(false); 1250 } 1251 return result != null ? result : super.focusSearch(focused, direction); 1252 } 1253 1254 @Override 1255 public void requestChildFocus(View child, View focused) { 1256 if (!mLayout.onRequestChildFocus(this, mState, child, focused) && focused != null) { 1257 mTempRect.set(0, 0, focused.getWidth(), focused.getHeight()); 1258 offsetDescendantRectToMyCoords(focused, mTempRect); 1259 offsetRectIntoDescendantCoords(child, mTempRect); 1260 requestChildRectangleOnScreen(child, mTempRect, !mFirstLayoutComplete); 1261 } 1262 super.requestChildFocus(child, focused); 1263 } 1264 1265 @Override 1266 public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { 1267 return mLayout.requestChildRectangleOnScreen(this, child, rect, immediate); 1268 } 1269 1270 @Override 1271 public void addFocusables(ArrayList<View> views, int direction, int focusableMode) { 1272 if (!mLayout.onAddFocusables(this, views, direction, focusableMode)) { 1273 super.addFocusables(views, direction, focusableMode); 1274 } 1275 } 1276 1277 @Override 1278 protected void onAttachedToWindow() { 1279 super.onAttachedToWindow(); 1280 mIsAttached = true; 1281 mFirstLayoutComplete = false; 1282 if (mLayout != null) { 1283 mLayout.onAttachedToWindow(this); 1284 } 1285 mPostedAnimatorRunner = false; 1286 } 1287 1288 @Override 1289 protected void onDetachedFromWindow() { 1290 super.onDetachedFromWindow(); 1291 mFirstLayoutComplete = false; 1292 1293 stopScroll(); 1294 mIsAttached = false; 1295 if (mLayout != null) { 1296 mLayout.onDetachedFromWindow(this, mRecycler); 1297 } 1298 removeCallbacks(mItemAnimatorRunner); 1299 } 1300 1301 /** 1302 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 1303 * {@link IllegalStateException} if it <b>is not</b>. 1304 * 1305 * @param message The message for the exception. Can be null. 1306 * @see #assertNotInLayoutOrScroll(String) 1307 */ 1308 void assertInLayoutOrScroll(String message) { 1309 if (!mRunningLayoutOrScroll) { 1310 if (message == null) { 1311 throw new IllegalStateException("Cannot call this method unless RecyclerView is " 1312 + "computing a layout or scrolling"); 1313 } 1314 throw new IllegalStateException(message); 1315 1316 } 1317 } 1318 1319 /** 1320 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 1321 * {@link IllegalStateException} if it <b>is</b>. 1322 * 1323 * @param message The message for the exception. Can be null. 1324 * @see #assertInLayoutOrScroll(String) 1325 */ 1326 void assertNotInLayoutOrScroll(String message) { 1327 if (mRunningLayoutOrScroll) { 1328 if (message == null) { 1329 throw new IllegalStateException("Cannot call this method while RecyclerView is " 1330 + "computing a layout or scrolling"); 1331 } 1332 throw new IllegalStateException(message); 1333 } 1334 } 1335 1336 /** 1337 * Add an {@link OnItemTouchListener} to intercept touch events before they are dispatched 1338 * to child views or this view's standard scrolling behavior. 1339 * 1340 * <p>Client code may use listeners to implement item manipulation behavior. Once a listener 1341 * returns true from 1342 * {@link OnItemTouchListener#onInterceptTouchEvent(RecyclerView, MotionEvent)} its 1343 * {@link OnItemTouchListener#onTouchEvent(RecyclerView, MotionEvent)} method will be called 1344 * for each incoming MotionEvent until the end of the gesture.</p> 1345 * 1346 * @param listener Listener to add 1347 */ 1348 public void addOnItemTouchListener(OnItemTouchListener listener) { 1349 mOnItemTouchListeners.add(listener); 1350 } 1351 1352 /** 1353 * Remove an {@link OnItemTouchListener}. It will no longer be able to intercept touch events. 1354 * 1355 * @param listener Listener to remove 1356 */ 1357 public void removeOnItemTouchListener(OnItemTouchListener listener) { 1358 mOnItemTouchListeners.remove(listener); 1359 if (mActiveOnItemTouchListener == listener) { 1360 mActiveOnItemTouchListener = null; 1361 } 1362 } 1363 1364 private boolean dispatchOnItemTouchIntercept(MotionEvent e) { 1365 final int action = e.getAction(); 1366 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_DOWN) { 1367 mActiveOnItemTouchListener = null; 1368 } 1369 1370 final int listenerCount = mOnItemTouchListeners.size(); 1371 for (int i = 0; i < listenerCount; i++) { 1372 final OnItemTouchListener listener = mOnItemTouchListeners.get(i); 1373 if (listener.onInterceptTouchEvent(this, e) && action != MotionEvent.ACTION_CANCEL) { 1374 mActiveOnItemTouchListener = listener; 1375 return true; 1376 } 1377 } 1378 return false; 1379 } 1380 1381 private boolean dispatchOnItemTouch(MotionEvent e) { 1382 final int action = e.getAction(); 1383 if (mActiveOnItemTouchListener != null) { 1384 if (action == MotionEvent.ACTION_DOWN) { 1385 // Stale state from a previous gesture, we're starting a new one. Clear it. 1386 mActiveOnItemTouchListener = null; 1387 } else { 1388 mActiveOnItemTouchListener.onTouchEvent(this, e); 1389 if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 1390 // Clean up for the next gesture. 1391 mActiveOnItemTouchListener = null; 1392 } 1393 return true; 1394 } 1395 } 1396 1397 // Listeners will have already received the ACTION_DOWN via dispatchOnItemTouchIntercept 1398 // as called from onInterceptTouchEvent; skip it. 1399 if (action != MotionEvent.ACTION_DOWN) { 1400 final int listenerCount = mOnItemTouchListeners.size(); 1401 for (int i = 0; i < listenerCount; i++) { 1402 final OnItemTouchListener listener = mOnItemTouchListeners.get(i); 1403 if (listener.onInterceptTouchEvent(this, e)) { 1404 mActiveOnItemTouchListener = listener; 1405 return true; 1406 } 1407 } 1408 } 1409 return false; 1410 } 1411 1412 @Override 1413 public boolean onInterceptTouchEvent(MotionEvent e) { 1414 if (dispatchOnItemTouchIntercept(e)) { 1415 cancelTouch(); 1416 return true; 1417 } 1418 1419 final boolean canScrollHorizontally = mLayout.canScrollHorizontally(); 1420 final boolean canScrollVertically = mLayout.canScrollVertically(); 1421 1422 if (mVelocityTracker == null) { 1423 mVelocityTracker = VelocityTracker.obtain(); 1424 } 1425 mVelocityTracker.addMovement(e); 1426 1427 final int action = MotionEventCompat.getActionMasked(e); 1428 final int actionIndex = MotionEventCompat.getActionIndex(e); 1429 1430 switch (action) { 1431 case MotionEvent.ACTION_DOWN: 1432 mScrollPointerId = MotionEventCompat.getPointerId(e, 0); 1433 mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f); 1434 mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f); 1435 1436 if (mScrollState == SCROLL_STATE_SETTLING) { 1437 getParent().requestDisallowInterceptTouchEvent(true); 1438 setScrollState(SCROLL_STATE_DRAGGING); 1439 } 1440 break; 1441 1442 case MotionEventCompat.ACTION_POINTER_DOWN: 1443 mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex); 1444 mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f); 1445 mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f); 1446 break; 1447 1448 case MotionEvent.ACTION_MOVE: { 1449 final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId); 1450 if (index < 0) { 1451 Log.e(TAG, "Error processing scroll; pointer index for id " + 1452 mScrollPointerId + " not found. Did any MotionEvents get skipped?"); 1453 return false; 1454 } 1455 1456 final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f); 1457 final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f); 1458 if (mScrollState != SCROLL_STATE_DRAGGING) { 1459 final int dx = x - mInitialTouchX; 1460 final int dy = y - mInitialTouchY; 1461 boolean startScroll = false; 1462 if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) { 1463 mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1); 1464 startScroll = true; 1465 } 1466 if (canScrollVertically && Math.abs(dy) > mTouchSlop) { 1467 mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1); 1468 startScroll = true; 1469 } 1470 if (startScroll) { 1471 getParent().requestDisallowInterceptTouchEvent(true); 1472 setScrollState(SCROLL_STATE_DRAGGING); 1473 } 1474 } 1475 } break; 1476 1477 case MotionEventCompat.ACTION_POINTER_UP: { 1478 onPointerUp(e); 1479 } break; 1480 1481 case MotionEvent.ACTION_UP: { 1482 mVelocityTracker.clear(); 1483 } break; 1484 1485 case MotionEvent.ACTION_CANCEL: { 1486 cancelTouch(); 1487 } 1488 } 1489 return mScrollState == SCROLL_STATE_DRAGGING; 1490 } 1491 1492 @Override 1493 public boolean onTouchEvent(MotionEvent e) { 1494 if (dispatchOnItemTouch(e)) { 1495 cancelTouch(); 1496 return true; 1497 } 1498 1499 final boolean canScrollHorizontally = mLayout.canScrollHorizontally(); 1500 final boolean canScrollVertically = mLayout.canScrollVertically(); 1501 1502 if (mVelocityTracker == null) { 1503 mVelocityTracker = VelocityTracker.obtain(); 1504 } 1505 mVelocityTracker.addMovement(e); 1506 1507 final int action = MotionEventCompat.getActionMasked(e); 1508 final int actionIndex = MotionEventCompat.getActionIndex(e); 1509 1510 switch (action) { 1511 case MotionEvent.ACTION_DOWN: { 1512 mScrollPointerId = MotionEventCompat.getPointerId(e, 0); 1513 mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f); 1514 mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f); 1515 } break; 1516 1517 case MotionEventCompat.ACTION_POINTER_DOWN: { 1518 mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex); 1519 mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f); 1520 mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f); 1521 } break; 1522 1523 case MotionEvent.ACTION_MOVE: { 1524 final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId); 1525 if (index < 0) { 1526 Log.e(TAG, "Error processing scroll; pointer index for id " + 1527 mScrollPointerId + " not found. Did any MotionEvents get skipped?"); 1528 return false; 1529 } 1530 1531 final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f); 1532 final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f); 1533 if (mScrollState != SCROLL_STATE_DRAGGING) { 1534 final int dx = x - mInitialTouchX; 1535 final int dy = y - mInitialTouchY; 1536 boolean startScroll = false; 1537 if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) { 1538 mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1); 1539 startScroll = true; 1540 } 1541 if (canScrollVertically && Math.abs(dy) > mTouchSlop) { 1542 mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1); 1543 startScroll = true; 1544 } 1545 if (startScroll) { 1546 getParent().requestDisallowInterceptTouchEvent(true); 1547 setScrollState(SCROLL_STATE_DRAGGING); 1548 } 1549 } 1550 if (mScrollState == SCROLL_STATE_DRAGGING) { 1551 final int dx = x - mLastTouchX; 1552 final int dy = y - mLastTouchY; 1553 scrollByInternal(canScrollHorizontally ? -dx : 0, 1554 canScrollVertically ? -dy : 0); 1555 } 1556 mLastTouchX = x; 1557 mLastTouchY = y; 1558 } break; 1559 1560 case MotionEventCompat.ACTION_POINTER_UP: { 1561 onPointerUp(e); 1562 } break; 1563 1564 case MotionEvent.ACTION_UP: { 1565 mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity); 1566 final float xvel = canScrollHorizontally ? 1567 -VelocityTrackerCompat.getXVelocity(mVelocityTracker, mScrollPointerId) : 0; 1568 final float yvel = canScrollVertically ? 1569 -VelocityTrackerCompat.getYVelocity(mVelocityTracker, mScrollPointerId) : 0; 1570 if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) { 1571 setScrollState(SCROLL_STATE_IDLE); 1572 } 1573 mVelocityTracker.clear(); 1574 releaseGlows(); 1575 } break; 1576 1577 case MotionEvent.ACTION_CANCEL: { 1578 cancelTouch(); 1579 } break; 1580 } 1581 1582 return true; 1583 } 1584 1585 private void cancelTouch() { 1586 mVelocityTracker.clear(); 1587 releaseGlows(); 1588 setScrollState(SCROLL_STATE_IDLE); 1589 } 1590 1591 private void onPointerUp(MotionEvent e) { 1592 final int actionIndex = MotionEventCompat.getActionIndex(e); 1593 if (MotionEventCompat.getPointerId(e, actionIndex) == mScrollPointerId) { 1594 // Pick a new pointer to pick up the slack. 1595 final int newIndex = actionIndex == 0 ? 1 : 0; 1596 mScrollPointerId = MotionEventCompat.getPointerId(e, newIndex); 1597 mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, newIndex) + 0.5f); 1598 mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, newIndex) + 0.5f); 1599 } 1600 } 1601 1602 @Override 1603 protected void onMeasure(int widthSpec, int heightSpec) { 1604 if (mAdapterUpdateDuringMeasure) { 1605 eatRequestLayout(); 1606 processAdapterUpdatesAndSetAnimationFlags(); 1607 1608 if (mState.mRunPredictiveAnimations) { 1609 // TODO: try to provide a better approach. 1610 // When RV decides to run predictive animations, we need to measure in pre-layout 1611 // state so that pre-layout pass results in correct layout. 1612 // On the other hand, this will prevent the layout manager from resizing properly. 1613 mState.mInPreLayout = true; 1614 } else { 1615 // consume remaining updates to provide a consistent state with the layout pass. 1616 mAdapterHelper.consumeUpdatesInOnePass(); 1617 mState.mInPreLayout = false; 1618 } 1619 mAdapterUpdateDuringMeasure = false; 1620 resumeRequestLayout(false); 1621 } 1622 1623 if (mAdapter != null) { 1624 mState.mItemCount = mAdapter.getItemCount(); 1625 } else { 1626 mState.mItemCount = 0; 1627 } 1628 1629 mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec); 1630 mState.mInPreLayout = false; // clear 1631 } 1632 1633 @Override 1634 protected void onSizeChanged(int w, int h, int oldw, int oldh) { 1635 super.onSizeChanged(w, h, oldw, oldh); 1636 if (w != oldw || h != oldh) { 1637 invalidateGlows(); 1638 } 1639 } 1640 1641 /** 1642 * Sets the {@link ItemAnimator} that will handle animations involving changes 1643 * to the items in this RecyclerView. By default, RecyclerView instantiates and 1644 * uses an instance of {@link DefaultItemAnimator}. Whether item animations are 1645 * enabled for the RecyclerView depends on the ItemAnimator and whether 1646 * the LayoutManager {@link LayoutManager#supportsPredictiveItemAnimations() 1647 * supports item animations}. 1648 * 1649 * @param animator The ItemAnimator being set. If null, no animations will occur 1650 * when changes occur to the items in this RecyclerView. 1651 */ 1652 public void setItemAnimator(ItemAnimator animator) { 1653 if (mItemAnimator != null) { 1654 mItemAnimator.endAnimations(); 1655 mItemAnimator.setListener(null); 1656 } 1657 mItemAnimator = animator; 1658 if (mItemAnimator != null) { 1659 mItemAnimator.setListener(mItemAnimatorListener); 1660 } 1661 } 1662 1663 /** 1664 * Gets the current ItemAnimator for this RecyclerView. A null return value 1665 * indicates that there is no animator and that item changes will happen without 1666 * any animations. By default, RecyclerView instantiates and 1667 * uses an instance of {@link DefaultItemAnimator}. 1668 * 1669 * @return ItemAnimator The current ItemAnimator. If null, no animations will occur 1670 * when changes occur to the items in this RecyclerView. 1671 */ 1672 public ItemAnimator getItemAnimator() { 1673 return mItemAnimator; 1674 } 1675 1676 private boolean supportsChangeAnimations() { 1677 return mItemAnimator != null && mItemAnimator.getSupportsChangeAnimations(); 1678 } 1679 1680 /** 1681 * Post a runnable to the next frame to run pending item animations. Only the first such 1682 * request will be posted, governed by the mPostedAnimatorRunner flag. 1683 */ 1684 private void postAnimationRunner() { 1685 if (!mPostedAnimatorRunner && mIsAttached) { 1686 ViewCompat.postOnAnimation(this, mItemAnimatorRunner); 1687 mPostedAnimatorRunner = true; 1688 } 1689 } 1690 1691 private boolean predictiveItemAnimationsEnabled() { 1692 return (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations()); 1693 } 1694 1695 /** 1696 * Consumes adapter updates and calculates which type of animations we want to run. 1697 * Called in onMeasure and dispatchLayout. 1698 * <p> 1699 * This method may process only the pre-layout state of updates or all of them. 1700 */ 1701 private void processAdapterUpdatesAndSetAnimationFlags() { 1702 if (mDataSetHasChangedAfterLayout) { 1703 // Processing these items have no value since data set changed unexpectedly. 1704 // Instead, we just reset it. 1705 mAdapterHelper.reset(); 1706 markKnownViewsInvalid(); 1707 mLayout.onItemsChanged(this); 1708 } 1709 // simple animations are a subset of advanced animations (which will cause a 1710 // pre-layout step) 1711 // If layout supports predictive animations, pre-process to decide if we want to run them 1712 if (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations()) { 1713 mAdapterHelper.preProcess(); 1714 } else { 1715 mAdapterHelper.consumeUpdatesInOnePass(); 1716 } 1717 boolean animationTypeSupported = (mItemsAddedOrRemoved && !mItemsChanged) || 1718 (mItemsAddedOrRemoved || (mItemsChanged && supportsChangeAnimations())); 1719 mState.mRunSimpleAnimations = mFirstLayoutComplete && mItemAnimator != null && 1720 (mDataSetHasChangedAfterLayout || animationTypeSupported || 1721 mLayout.mRequestedSimpleAnimations) && 1722 (!mDataSetHasChangedAfterLayout || mAdapter.hasStableIds()); 1723 mState.mRunPredictiveAnimations = mState.mRunSimpleAnimations && 1724 animationTypeSupported && !mDataSetHasChangedAfterLayout && 1725 predictiveItemAnimationsEnabled(); 1726 } 1727 1728 /** 1729 * Wrapper around layoutChildren() that handles animating changes caused by layout. 1730 * Animations work on the assumption that there are five different kinds of items 1731 * in play: 1732 * PERSISTENT: items are visible before and after layout 1733 * REMOVED: items were visible before layout and were removed by the app 1734 * ADDED: items did not exist before layout and were added by the app 1735 * DISAPPEARING: items exist in the data set before/after, but changed from 1736 * visible to non-visible in the process of layout (they were moved off 1737 * screen as a side-effect of other changes) 1738 * APPEARING: items exist in the data set before/after, but changed from 1739 * non-visible to visible in the process of layout (they were moved on 1740 * screen as a side-effect of other changes) 1741 * The overall approach figures out what items exist before/after layout and 1742 * infers one of the five above states for each of the items. Then the animations 1743 * are set up accordingly: 1744 * PERSISTENT views are moved ({@link ItemAnimator#animateMove(ViewHolder, int, int, int, int)}) 1745 * REMOVED views are removed ({@link ItemAnimator#animateRemove(ViewHolder)}) 1746 * ADDED views are added ({@link ItemAnimator#animateAdd(ViewHolder)}) 1747 * DISAPPEARING views are moved off screen 1748 * APPEARING views are moved on screen 1749 */ 1750 void dispatchLayout() { 1751 if (mAdapter == null) { 1752 Log.e(TAG, "No adapter attached; skipping layout"); 1753 return; 1754 } 1755 mDisappearingViewsInLayoutPass.clear(); 1756 eatRequestLayout(); 1757 mRunningLayoutOrScroll = true; 1758 1759 processAdapterUpdatesAndSetAnimationFlags(); 1760 1761 mState.mOldChangedHolders = mState.mRunSimpleAnimations && mItemsChanged 1762 && supportsChangeAnimations() ? new ArrayMap<Long, ViewHolder>() : null; 1763 mItemsAddedOrRemoved = mItemsChanged = false; 1764 ArrayMap<View, Rect> appearingViewInitialBounds = null; 1765 mState.mInPreLayout = mState.mRunPredictiveAnimations; 1766 mState.mItemCount = mAdapter.getItemCount(); 1767 1768 if (mState.mRunSimpleAnimations) { 1769 // Step 0: Find out where all non-removed items are, pre-layout 1770 mState.mPreLayoutHolderMap.clear(); 1771 mState.mPostLayoutHolderMap.clear(); 1772 int count = mChildHelper.getChildCount(); 1773 for (int i = 0; i < count; ++i) { 1774 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 1775 if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) { 1776 continue; 1777 } 1778 final View view = holder.itemView; 1779 mState.mPreLayoutHolderMap.put(holder, new ItemHolderInfo(holder, 1780 view.getLeft(), view.getTop(), view.getRight(), view.getBottom())); 1781 } 1782 } 1783 if (mState.mRunPredictiveAnimations) { 1784 // Step 1: run prelayout: This will use the old positions of items. The layout manager 1785 // is expected to layout everything, even removed items (though not to add removed 1786 // items back to the container). This gives the pre-layout position of APPEARING views 1787 // which come into existence as part of the real layout. 1788 1789 // Save old positions so that LayoutManager can run its mapping logic. 1790 saveOldPositions(); 1791 // processAdapterUpdatesAndSetAnimationFlags already run pre-layout animations. 1792 if (mState.mOldChangedHolders != null) { 1793 int count = mChildHelper.getChildCount(); 1794 for (int i = 0; i < count; ++i) { 1795 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 1796 if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) { 1797 long key = getChangedHolderKey(holder); 1798 mState.mOldChangedHolders.put(key, holder); 1799 mState.mPreLayoutHolderMap.remove(holder); 1800 } 1801 } 1802 } 1803 1804 final boolean didStructureChange = mState.mStructureChanged; 1805 mState.mStructureChanged = false; 1806 // temporarily disable flag because we are asking for previous layout 1807 mLayout.onLayoutChildren(mRecycler, mState); 1808 mState.mStructureChanged = didStructureChange; 1809 1810 appearingViewInitialBounds = new ArrayMap<View, Rect>(); 1811 for (int i = 0; i < mChildHelper.getChildCount(); ++i) { 1812 boolean found = false; 1813 View child = mChildHelper.getChildAt(i); 1814 if (getChildViewHolderInt(child).shouldIgnore()) { 1815 continue; 1816 } 1817 for (int j = 0; j < mState.mPreLayoutHolderMap.size(); ++j) { 1818 ViewHolder holder = mState.mPreLayoutHolderMap.keyAt(j); 1819 if (holder.itemView == child) { 1820 found = true; 1821 continue; 1822 } 1823 } 1824 if (!found) { 1825 appearingViewInitialBounds.put(child, new Rect(child.getLeft(), child.getTop(), 1826 child.getRight(), child.getBottom())); 1827 } 1828 } 1829 // we don't process disappearing list because they may re-appear in post layout pass. 1830 clearOldPositions(); 1831 mAdapterHelper.consumePostponedUpdates(); 1832 } else { 1833 clearOldPositions(); 1834 // in case pre layout did run but we decided not to run predictive animations. 1835 mAdapterHelper.consumeUpdatesInOnePass(); 1836 if (mState.mOldChangedHolders != null) { 1837 int count = mChildHelper.getChildCount(); 1838 for (int i = 0; i < count; ++i) { 1839 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 1840 if (holder.isChanged() && !holder.isRemoved() && !holder.shouldIgnore()) { 1841 long key = getChangedHolderKey(holder); 1842 mState.mOldChangedHolders.put(key, holder); 1843 mState.mPreLayoutHolderMap.remove(holder); 1844 } 1845 } 1846 } 1847 } 1848 mState.mItemCount = mAdapter.getItemCount(); 1849 mState.mDeletedInvisibleItemCountSincePreviousLayout = 0; 1850 1851 // Step 2: Run layout 1852 mState.mInPreLayout = false; 1853 mLayout.onLayoutChildren(mRecycler, mState); 1854 1855 mState.mStructureChanged = false; 1856 mPendingSavedState = null; 1857 1858 // onLayoutChildren may have caused client code to disable item animations; re-check 1859 mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null; 1860 1861 if (mState.mRunSimpleAnimations) { 1862 // Step 3: Find out where things are now, post-layout 1863 ArrayMap<Long, ViewHolder> newChangedHolders = mState.mOldChangedHolders != null ? 1864 new ArrayMap<Long, ViewHolder>() : null; 1865 int count = mChildHelper.getChildCount(); 1866 for (int i = 0; i < count; ++i) { 1867 ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 1868 if (holder.shouldIgnore()) { 1869 continue; 1870 } 1871 final View view = holder.itemView; 1872 long key = getChangedHolderKey(holder); 1873 if (newChangedHolders != null && mState.mOldChangedHolders.get(key) != null) { 1874 newChangedHolders.put(key, holder); 1875 } else { 1876 mState.mPostLayoutHolderMap.put(holder, new ItemHolderInfo(holder, 1877 view.getLeft(), view.getTop(), view.getRight(), view.getBottom())); 1878 } 1879 } 1880 processDisappearingList(); 1881 // Step 4: Animate DISAPPEARING and REMOVED items 1882 int preLayoutCount = mState.mPreLayoutHolderMap.size(); 1883 for (int i = preLayoutCount - 1; i >= 0; i--) { 1884 ViewHolder itemHolder = mState.mPreLayoutHolderMap.keyAt(i); 1885 if (!mState.mPostLayoutHolderMap.containsKey(itemHolder)) { 1886 ItemHolderInfo disappearingItem = mState.mPreLayoutHolderMap.valueAt(i); 1887 mState.mPreLayoutHolderMap.removeAt(i); 1888 1889 View disappearingItemView = disappearingItem.holder.itemView; 1890 removeDetachedView(disappearingItemView, false); 1891 mRecycler.unscrapView(disappearingItem.holder); 1892 1893 animateDisappearance(disappearingItem); 1894 } 1895 } 1896 // Step 5: Animate APPEARING and ADDED items 1897 int postLayoutCount = mState.mPostLayoutHolderMap.size(); 1898 if (postLayoutCount > 0) { 1899 for (int i = postLayoutCount - 1; i >= 0; i--) { 1900 ViewHolder itemHolder = mState.mPostLayoutHolderMap.keyAt(i); 1901 ItemHolderInfo info = mState.mPostLayoutHolderMap.valueAt(i); 1902 if ((mState.mPreLayoutHolderMap.isEmpty() || 1903 !mState.mPreLayoutHolderMap.containsKey(itemHolder))) { 1904 mState.mPostLayoutHolderMap.removeAt(i); 1905 Rect initialBounds = (appearingViewInitialBounds != null) ? 1906 appearingViewInitialBounds.get(itemHolder.itemView) : null; 1907 animateAppearance(itemHolder, initialBounds, 1908 info.left, info.top); 1909 } 1910 } 1911 } 1912 // Step 6: Animate PERSISTENT items 1913 count = mState.mPostLayoutHolderMap.size(); 1914 for (int i = 0; i < count; ++i) { 1915 ViewHolder postHolder = mState.mPostLayoutHolderMap.keyAt(i); 1916 ItemHolderInfo postInfo = mState.mPostLayoutHolderMap.valueAt(i); 1917 ItemHolderInfo preInfo = mState.mPreLayoutHolderMap.get(postHolder); 1918 if (preInfo != null && postInfo != null) { 1919 if (preInfo.left != postInfo.left || preInfo.top != postInfo.top) { 1920 postHolder.setIsRecyclable(false); 1921 if (DEBUG) { 1922 Log.d(TAG, "PERSISTENT: " + postHolder + 1923 " with view " + postHolder.itemView); 1924 } 1925 if (mItemAnimator.animateMove(postHolder, 1926 preInfo.left, preInfo.top, postInfo.left, postInfo.top)) { 1927 postAnimationRunner(); 1928 } 1929 } 1930 } 1931 } 1932 // Step 7: Animate CHANGING items 1933 count = mState.mOldChangedHolders != null ? mState.mOldChangedHolders.size() : 0; 1934 // traverse reverse in case view gets recycled while we are traversing the list. 1935 for (int i = count - 1; i >= 0; i--) { 1936 long key = mState.mOldChangedHolders.keyAt(i); 1937 ViewHolder oldHolder = mState.mOldChangedHolders.get(key); 1938 View oldView = oldHolder.itemView; 1939 if (oldHolder.shouldIgnore()) { 1940 continue; 1941 } 1942 // We probably don't need this check anymore since these views are removed from 1943 // the list if they are recycled. 1944 if (mRecycler.mChangedScrap != null && 1945 mRecycler.mChangedScrap.contains(oldHolder)) { 1946 animateChange(oldHolder, newChangedHolders.get(key)); 1947 } else if (DEBUG) { 1948 Log.e(TAG, "cannot find old changed holder in changed scrap :/" + oldHolder); 1949 } 1950 } 1951 } 1952 resumeRequestLayout(false); 1953 mLayout.removeAndRecycleScrapInt(mRecycler, !mState.mRunPredictiveAnimations); 1954 mState.mPreviousLayoutItemCount = mState.mItemCount; 1955 mDataSetHasChangedAfterLayout = false; 1956 mState.mRunSimpleAnimations = false; 1957 mState.mRunPredictiveAnimations = false; 1958 mRunningLayoutOrScroll = false; 1959 mLayout.mRequestedSimpleAnimations = false; 1960 if (mRecycler.mChangedScrap != null) { 1961 mRecycler.mChangedScrap.clear(); 1962 } 1963 mState.mOldChangedHolders = null; 1964 } 1965 1966 /** 1967 * Returns a unique key to be used while handling change animations. 1968 * It might be child's position or stable id depending on the adapter type. 1969 */ 1970 long getChangedHolderKey(ViewHolder holder) { 1971 return mAdapter.hasStableIds() ? holder.getItemId() : holder.mPosition; 1972 } 1973 1974 /** 1975 * A LayoutManager may want to layout a view just to animate disappearance. 1976 * This method handles those views and triggers remove animation on them. 1977 */ 1978 private void processDisappearingList() { 1979 final int count = mDisappearingViewsInLayoutPass.size(); 1980 for (int i = 0; i < count; i ++) { 1981 View view = mDisappearingViewsInLayoutPass.get(i); 1982 ViewHolder vh = getChildViewHolderInt(view); 1983 final ItemHolderInfo info = mState.mPreLayoutHolderMap.remove(vh); 1984 if (!mState.isPreLayout()) { 1985 mState.mPostLayoutHolderMap.remove(vh); 1986 } 1987 if (info != null) { 1988 animateDisappearance(info); 1989 } else { 1990 // let it disappear from the position it becomes visible 1991 animateDisappearance(new ItemHolderInfo(vh, view.getLeft(), view.getTop(), 1992 view.getRight(), view.getBottom())); 1993 } 1994 } 1995 mDisappearingViewsInLayoutPass.clear(); 1996 } 1997 1998 private void animateAppearance(ViewHolder itemHolder, Rect beforeBounds, int afterLeft, 1999 int afterTop) { 2000 View newItemView = itemHolder.itemView; 2001 if (beforeBounds != null && 2002 (beforeBounds.left != afterLeft || beforeBounds.top != afterTop)) { 2003 // slide items in if before/after locations differ 2004 itemHolder.setIsRecyclable(false); 2005 if (DEBUG) { 2006 Log.d(TAG, "APPEARING: " + itemHolder + " with view " + newItemView); 2007 } 2008 if (mItemAnimator.animateMove(itemHolder, 2009 beforeBounds.left, beforeBounds.top, 2010 afterLeft, afterTop)) { 2011 postAnimationRunner(); 2012 } 2013 } else { 2014 if (DEBUG) { 2015 Log.d(TAG, "ADDED: " + itemHolder + " with view " + newItemView); 2016 } 2017 itemHolder.setIsRecyclable(false); 2018 if (mItemAnimator.animateAdd(itemHolder)) { 2019 postAnimationRunner(); 2020 } 2021 } 2022 } 2023 2024 private void animateDisappearance(ItemHolderInfo disappearingItem) { 2025 View disappearingItemView = disappearingItem.holder.itemView; 2026 addAnimatingView(disappearingItemView); 2027 int oldLeft = disappearingItem.left; 2028 int oldTop = disappearingItem.top; 2029 int newLeft = disappearingItemView.getLeft(); 2030 int newTop = disappearingItemView.getTop(); 2031 if (oldLeft != newLeft || oldTop != newTop) { 2032 disappearingItem.holder.setIsRecyclable(false); 2033 disappearingItemView.layout(newLeft, newTop, 2034 newLeft + disappearingItemView.getWidth(), 2035 newTop + disappearingItemView.getHeight()); 2036 if (DEBUG) { 2037 Log.d(TAG, "DISAPPEARING: " + disappearingItem.holder + 2038 " with view " + disappearingItemView); 2039 } 2040 if (mItemAnimator.animateMove(disappearingItem.holder, oldLeft, oldTop, 2041 newLeft, newTop)) { 2042 postAnimationRunner(); 2043 } 2044 } else { 2045 if (DEBUG) { 2046 Log.d(TAG, "REMOVED: " + disappearingItem.holder + 2047 " with view " + disappearingItemView); 2048 } 2049 disappearingItem.holder.setIsRecyclable(false); 2050 if (mItemAnimator.animateRemove(disappearingItem.holder)) { 2051 postAnimationRunner(); 2052 } 2053 } 2054 } 2055 2056 private void animateChange(ViewHolder oldHolder, ViewHolder newHolder) { 2057 oldHolder.setIsRecyclable(false); 2058 removeDetachedView(oldHolder.itemView, false); 2059 addAnimatingView(oldHolder.itemView); 2060 oldHolder.mShadowedHolder = newHolder; 2061 mRecycler.unscrapView(oldHolder); 2062 if (DEBUG) { 2063 Log.d(TAG, "CHANGED: " + oldHolder + " with view " + oldHolder.itemView); 2064 } 2065 final int fromLeft = oldHolder.itemView.getLeft(); 2066 final int fromTop = oldHolder.itemView.getTop(); 2067 final int toLeft, toTop; 2068 if (newHolder == null || newHolder.shouldIgnore()) { 2069 toLeft = fromLeft; 2070 toTop = fromTop; 2071 } else { 2072 toLeft = newHolder.itemView.getLeft(); 2073 toTop = newHolder.itemView.getTop(); 2074 newHolder.setIsRecyclable(false); 2075 newHolder.mShadowingHolder = oldHolder; 2076 } 2077 if(mItemAnimator.animateChange(oldHolder, newHolder, 2078 fromLeft, fromTop, toLeft, toTop)) { 2079 postAnimationRunner(); 2080 } 2081 } 2082 2083 @Override 2084 protected void onLayout(boolean changed, int l, int t, int r, int b) { 2085 eatRequestLayout(); 2086 dispatchLayout(); 2087 resumeRequestLayout(false); 2088 mFirstLayoutComplete = true; 2089 } 2090 2091 @Override 2092 public void requestLayout() { 2093 if (!mEatRequestLayout) { 2094 super.requestLayout(); 2095 } else { 2096 mLayoutRequestEaten = true; 2097 } 2098 } 2099 2100 void markItemDecorInsetsDirty() { 2101 final int childCount = mChildHelper.getUnfilteredChildCount(); 2102 for (int i = 0; i < childCount; i++) { 2103 final View child = mChildHelper.getUnfilteredChildAt(i); 2104 ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true; 2105 } 2106 mRecycler.markItemDecorInsetsDirty(); 2107 } 2108 2109 @Override 2110 public void draw(Canvas c) { 2111 super.draw(c); 2112 2113 final int count = mItemDecorations.size(); 2114 for (int i = 0; i < count; i++) { 2115 mItemDecorations.get(i).onDrawOver(c, this, mState); 2116 } 2117 // TODO If padding is not 0 and chilChildrenToPadding is false, to draw glows properly, we 2118 // need find children closest to edges. Not sure if it is worth the effort. 2119 boolean needsInvalidate = false; 2120 if (mLeftGlow != null && !mLeftGlow.isFinished()) { 2121 final int restore = c.save(); 2122 final int padding = mClipToPadding ? getPaddingBottom() : 0; 2123 c.rotate(270); 2124 c.translate(-getHeight() + padding, 0); 2125 needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c); 2126 c.restoreToCount(restore); 2127 } 2128 if (mTopGlow != null && !mTopGlow.isFinished()) { 2129 final int restore = c.save(); 2130 if (mClipToPadding) { 2131 c.translate(getPaddingLeft(), getPaddingTop()); 2132 } 2133 needsInvalidate |= mTopGlow != null && mTopGlow.draw(c); 2134 c.restoreToCount(restore); 2135 } 2136 if (mRightGlow != null && !mRightGlow.isFinished()) { 2137 final int restore = c.save(); 2138 final int width = getWidth(); 2139 final int padding = mClipToPadding ? getPaddingTop() : 0; 2140 c.rotate(90); 2141 c.translate(-padding, -width); 2142 needsInvalidate |= mRightGlow != null && mRightGlow.draw(c); 2143 c.restoreToCount(restore); 2144 } 2145 if (mBottomGlow != null && !mBottomGlow.isFinished()) { 2146 final int restore = c.save(); 2147 c.rotate(180); 2148 if (mClipToPadding) { 2149 c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom()); 2150 } else { 2151 c.translate(-getWidth(), -getHeight()); 2152 } 2153 needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c); 2154 c.restoreToCount(restore); 2155 } 2156 2157 // If some views are animating, ItemDecorators are likely to move/change with them. 2158 // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's 2159 // display lists are not invalidated. 2160 if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 && 2161 mItemAnimator.isRunning()) { 2162 needsInvalidate = true; 2163 } 2164 2165 if (needsInvalidate) { 2166 ViewCompat.postInvalidateOnAnimation(this); 2167 } 2168 } 2169 2170 @Override 2171 public void onDraw(Canvas c) { 2172 super.onDraw(c); 2173 2174 final int count = mItemDecorations.size(); 2175 for (int i = 0; i < count; i++) { 2176 mItemDecorations.get(i).onDraw(c, this, mState); 2177 } 2178 } 2179 2180 @Override 2181 protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { 2182 return p instanceof LayoutParams && mLayout.checkLayoutParams((LayoutParams) p); 2183 } 2184 2185 @Override 2186 protected ViewGroup.LayoutParams generateDefaultLayoutParams() { 2187 if (mLayout == null) { 2188 throw new IllegalStateException("RecyclerView has no LayoutManager"); 2189 } 2190 return mLayout.generateDefaultLayoutParams(); 2191 } 2192 2193 @Override 2194 public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) { 2195 if (mLayout == null) { 2196 throw new IllegalStateException("RecyclerView has no LayoutManager"); 2197 } 2198 return mLayout.generateLayoutParams(getContext(), attrs); 2199 } 2200 2201 @Override 2202 protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) { 2203 if (mLayout == null) { 2204 throw new IllegalStateException("RecyclerView has no LayoutManager"); 2205 } 2206 return mLayout.generateLayoutParams(p); 2207 } 2208 2209 void saveOldPositions() { 2210 final int childCount = mChildHelper.getUnfilteredChildCount(); 2211 for (int i = 0; i < childCount; i++) { 2212 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2213 if (DEBUG && holder.mPosition == -1 && !holder.isRemoved()) { 2214 throw new IllegalStateException("view holder cannot have position -1 unless it" 2215 + " is removed"); 2216 } 2217 if (!holder.shouldIgnore()) { 2218 holder.saveOldPosition(); 2219 } 2220 } 2221 } 2222 2223 void clearOldPositions() { 2224 final int childCount = mChildHelper.getUnfilteredChildCount(); 2225 for (int i = 0; i < childCount; i++) { 2226 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2227 if (!holder.shouldIgnore()) { 2228 holder.clearOldPosition(); 2229 } 2230 } 2231 mRecycler.clearOldPositions(); 2232 } 2233 2234 void offsetPositionRecordsForMove(int from, int to) { 2235 final int childCount = mChildHelper.getUnfilteredChildCount(); 2236 final int start, end, inBetweenOffset; 2237 if (from < to) { 2238 start = from; 2239 end = to; 2240 inBetweenOffset = -1; 2241 } else { 2242 start = to; 2243 end = from; 2244 inBetweenOffset = 1; 2245 } 2246 2247 for (int i = 0; i < childCount; i++) { 2248 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2249 if (holder == null || holder.mPosition < start || holder.mPosition > end) { 2250 continue; 2251 } 2252 if (DEBUG) { 2253 Log.d(TAG, "offsetPositionRecordsForMove attached child " + i + " holder " + 2254 holder); 2255 } 2256 if (holder.mPosition == from) { 2257 holder.offsetPosition(to - from, false); 2258 } else { 2259 holder.offsetPosition(inBetweenOffset, false); 2260 } 2261 2262 mState.mStructureChanged = true; 2263 } 2264 mRecycler.offsetPositionRecordsForMove(from, to); 2265 requestLayout(); 2266 } 2267 2268 void offsetPositionRecordsForInsert(int positionStart, int itemCount) { 2269 final int childCount = mChildHelper.getUnfilteredChildCount(); 2270 for (int i = 0; i < childCount; i++) { 2271 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2272 if (holder != null && !holder.shouldIgnore() && holder.mPosition >= positionStart) { 2273 if (DEBUG) { 2274 Log.d(TAG, "offsetPositionRecordsForInsert attached child " + i + " holder " + 2275 holder + " now at position " + (holder.mPosition + itemCount)); 2276 } 2277 holder.offsetPosition(itemCount, false); 2278 mState.mStructureChanged = true; 2279 } 2280 } 2281 mRecycler.offsetPositionRecordsForInsert(positionStart, itemCount); 2282 requestLayout(); 2283 } 2284 2285 void offsetPositionRecordsForRemove(int positionStart, int itemCount, 2286 boolean applyToPreLayout) { 2287 final int positionEnd = positionStart + itemCount; 2288 final int childCount = mChildHelper.getUnfilteredChildCount(); 2289 for (int i = 0; i < childCount; i++) { 2290 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2291 if (holder != null && !holder.shouldIgnore()) { 2292 if (holder.mPosition >= positionEnd) { 2293 if (DEBUG) { 2294 Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i + 2295 " holder " + holder + " now at position " + 2296 (holder.mPosition - itemCount)); 2297 } 2298 holder.offsetPosition(-itemCount, applyToPreLayout); 2299 mState.mStructureChanged = true; 2300 } else if (holder.mPosition >= positionStart) { 2301 if (DEBUG) { 2302 Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i + 2303 " holder " + holder + " now REMOVED"); 2304 } 2305 holder.addFlags(ViewHolder.FLAG_REMOVED); 2306 mState.mStructureChanged = true; 2307 holder.offsetPosition(-itemCount, applyToPreLayout); 2308 } 2309 } 2310 } 2311 mRecycler.offsetPositionRecordsForRemove(positionStart, itemCount, applyToPreLayout); 2312 requestLayout(); 2313 } 2314 2315 /** 2316 * Rebind existing views for the given range, or create as needed. 2317 * 2318 * @param positionStart Adapter position to start at 2319 * @param itemCount Number of views that must explicitly be rebound 2320 */ 2321 void viewRangeUpdate(int positionStart, int itemCount) { 2322 final int childCount = mChildHelper.getUnfilteredChildCount(); 2323 final int positionEnd = positionStart + itemCount; 2324 2325 for (int i = 0; i < childCount; i++) { 2326 final View child = mChildHelper.getUnfilteredChildAt(i); 2327 final ViewHolder holder = getChildViewHolderInt(child); 2328 if (holder == null || holder.shouldIgnore()) { 2329 continue; 2330 } 2331 if (holder.mPosition >= positionStart && holder.mPosition < positionEnd) { 2332 // We re-bind these view holders after pre-processing is complete so that 2333 // ViewHolders have their final positions assigned. 2334 holder.addFlags(ViewHolder.FLAG_UPDATE); 2335 if (supportsChangeAnimations()) { 2336 holder.addFlags(ViewHolder.FLAG_CHANGED); 2337 } 2338 // lp cannot be null since we get ViewHolder from it. 2339 ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true; 2340 } 2341 } 2342 mRecycler.viewRangeUpdate(positionStart, itemCount); 2343 } 2344 2345 void rebindUpdatedViewHolders() { 2346 final int childCount = mChildHelper.getChildCount(); 2347 for (int i = 0; i < childCount; i++) { 2348 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i)); 2349 // validate type is correct 2350 if (holder == null || holder.shouldIgnore()) { 2351 continue; 2352 } 2353 if (holder.isRemoved() || holder.isInvalid()) { 2354 requestLayout(); 2355 } else if (holder.needsUpdate()) { 2356 final int type = mAdapter.getItemViewType(holder.mPosition); 2357 if (holder.getItemViewType() == type) { 2358 // Binding an attached view will request a layout if needed. 2359 if (!holder.isChanged() || !supportsChangeAnimations()) { 2360 mAdapter.bindViewHolder(holder, holder.mPosition); 2361 } else { 2362 // Don't rebind changed holders if change animations are enabled. 2363 // We want the old contents for the animation and will get a new 2364 // holder for the new contents. 2365 requestLayout(); 2366 } 2367 } else { 2368 // binding to a new view will need re-layout anyways. We can as well trigger 2369 // it here so that it happens during layout 2370 holder.addFlags(ViewHolder.FLAG_INVALID); 2371 requestLayout(); 2372 } 2373 } 2374 } 2375 } 2376 2377 /** 2378 * Mark all known views as invalid. Used in response to a, "the whole world might have changed" 2379 * data change event. 2380 */ 2381 void markKnownViewsInvalid() { 2382 final int childCount = mChildHelper.getUnfilteredChildCount(); 2383 for (int i = 0; i < childCount; i++) { 2384 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2385 if (holder != null && !holder.shouldIgnore()) { 2386 holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID); 2387 } 2388 } 2389 markItemDecorInsetsDirty(); 2390 mRecycler.markKnownViewsInvalid(); 2391 } 2392 2393 /** 2394 * Invalidates all ItemDecorations. If RecyclerView has item decorations, calling this method 2395 * will trigger a {@link #requestLayout()} call. 2396 */ 2397 public void invalidateItemDecorations() { 2398 if (mItemDecorations.size() == 0) { 2399 return; 2400 } 2401 if (mLayout != null) { 2402 mLayout.assertNotInLayoutOrScroll("Cannot invalidate item decorations during a scroll" 2403 + " or layout"); 2404 } 2405 markItemDecorInsetsDirty(); 2406 requestLayout(); 2407 } 2408 2409 /** 2410 * Retrieve the {@link ViewHolder} for the given child view. 2411 * 2412 * @param child Child of this RecyclerView to query for its ViewHolder 2413 * @return The child view's ViewHolder 2414 */ 2415 public ViewHolder getChildViewHolder(View child) { 2416 final ViewParent parent = child.getParent(); 2417 if (parent != null && parent != this) { 2418 throw new IllegalArgumentException("View " + child + " is not a direct child of " + 2419 this); 2420 } 2421 return getChildViewHolderInt(child); 2422 } 2423 2424 static ViewHolder getChildViewHolderInt(View child) { 2425 if (child == null) { 2426 return null; 2427 } 2428 return ((LayoutParams) child.getLayoutParams()).mViewHolder; 2429 } 2430 2431 /** 2432 * Return the adapter position that the given child view corresponds to. 2433 * 2434 * @param child Child View to query 2435 * @return Adapter position corresponding to the given view or {@link #NO_POSITION} 2436 */ 2437 public int getChildPosition(View child) { 2438 final ViewHolder holder = getChildViewHolderInt(child); 2439 return holder != null ? holder.getPosition() : NO_POSITION; 2440 } 2441 2442 /** 2443 * Return the stable item id that the given child view corresponds to. 2444 * 2445 * @param child Child View to query 2446 * @return Item id corresponding to the given view or {@link #NO_ID} 2447 */ 2448 public long getChildItemId(View child) { 2449 if (mAdapter == null || !mAdapter.hasStableIds()) { 2450 return NO_ID; 2451 } 2452 final ViewHolder holder = getChildViewHolderInt(child); 2453 return holder != null ? holder.getItemId() : NO_ID; 2454 } 2455 2456 /** 2457 * Return the ViewHolder for the item in the given position of the data set. 2458 * 2459 * @param position The position of the item in the data set of the adapter 2460 * @return The ViewHolder at <code>position</code> 2461 */ 2462 public ViewHolder findViewHolderForPosition(int position) { 2463 return findViewHolderForPosition(position, false); 2464 } 2465 2466 ViewHolder findViewHolderForPosition(int position, boolean checkNewPosition) { 2467 final int childCount = mChildHelper.getUnfilteredChildCount(); 2468 for (int i = 0; i < childCount; i++) { 2469 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2470 if (holder != null && !holder.isRemoved()) { 2471 if (checkNewPosition) { 2472 if (holder.mPosition == position) { 2473 return holder; 2474 } 2475 } else if (holder.getPosition() == position) { 2476 return holder; 2477 } 2478 } 2479 } 2480 // This method should not query cached views. It creates a problem during adapter updates 2481 // when we are dealing with already laid out views. Also, for the public method, it is more 2482 // reasonable to return null if position is not laid out. 2483 return null; 2484 } 2485 2486 /** 2487 * Return the ViewHolder for the item with the given id. The RecyclerView must 2488 * use an Adapter with {@link Adapter#setHasStableIds(boolean) stableIds} to 2489 * return a non-null value. 2490 * 2491 * @param id The id for the requested item 2492 * @return The ViewHolder with the given <code>id</code>, of null if there 2493 * is no such item. 2494 */ 2495 public ViewHolder findViewHolderForItemId(long id) { 2496 final int childCount = mChildHelper.getUnfilteredChildCount(); 2497 for (int i = 0; i < childCount; i++) { 2498 final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i)); 2499 if (holder != null && holder.getItemId() == id) { 2500 return holder; 2501 } 2502 } 2503 // this method should not query cached views. They are not children so they 2504 // should not be returned in this public method 2505 return null; 2506 } 2507 2508 /** 2509 * Find the topmost view under the given point. 2510 * 2511 * @param x Horizontal position in pixels to search 2512 * @param y Vertical position in pixels to search 2513 * @return The child view under (x, y) or null if no matching child is found 2514 */ 2515 public View findChildViewUnder(float x, float y) { 2516 final int count = mChildHelper.getChildCount(); 2517 for (int i = count - 1; i >= 0; i--) { 2518 final View child = mChildHelper.getChildAt(i); 2519 final float translationX = ViewCompat.getTranslationX(child); 2520 final float translationY = ViewCompat.getTranslationY(child); 2521 if (x >= child.getLeft() + translationX && 2522 x <= child.getRight() + translationX && 2523 y >= child.getTop() + translationY && 2524 y <= child.getBottom() + translationY) { 2525 return child; 2526 } 2527 } 2528 return null; 2529 } 2530 2531 /** 2532 * Offset the bounds of all child views by <code>dy</code> pixels. 2533 * Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}. 2534 * 2535 * @param dy Vertical pixel offset to apply to the bounds of all child views 2536 */ 2537 public void offsetChildrenVertical(int dy) { 2538 final int childCount = mChildHelper.getChildCount(); 2539 for (int i = 0; i < childCount; i++) { 2540 mChildHelper.getChildAt(i).offsetTopAndBottom(dy); 2541 } 2542 } 2543 2544 /** 2545 * Called when an item view is attached to this RecyclerView. 2546 * 2547 * <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications 2548 * of child views as they become attached. This will be called before a 2549 * {@link LayoutManager} measures or lays out the view and is a good time to perform these 2550 * changes.</p> 2551 * 2552 * @param child Child view that is now attached to this RecyclerView and its associated window 2553 */ 2554 public void onChildAttachedToWindow(View child) { 2555 } 2556 2557 /** 2558 * Called when an item view is detached from this RecyclerView. 2559 * 2560 * <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications 2561 * of child views as they become detached. This will be called as a 2562 * {@link LayoutManager} fully detaches the child view from the parent and its window.</p> 2563 * 2564 * @param child Child view that is now detached from this RecyclerView and its associated window 2565 */ 2566 public void onChildDetachedFromWindow(View child) { 2567 } 2568 2569 /** 2570 * Offset the bounds of all child views by <code>dx</code> pixels. 2571 * Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}. 2572 * 2573 * @param dx Horizontal pixel offset to apply to the bounds of all child views 2574 */ 2575 public void offsetChildrenHorizontal(int dx) { 2576 final int childCount = mChildHelper.getChildCount(); 2577 for (int i = 0; i < childCount; i++) { 2578 mChildHelper.getChildAt(i).offsetLeftAndRight(dx); 2579 } 2580 } 2581 2582 Rect getItemDecorInsetsForChild(View child) { 2583 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 2584 if (!lp.mInsetsDirty) { 2585 return lp.mDecorInsets; 2586 } 2587 2588 final Rect insets = lp.mDecorInsets; 2589 insets.set(0, 0, 0, 0); 2590 final int decorCount = mItemDecorations.size(); 2591 for (int i = 0; i < decorCount; i++) { 2592 mTempRect.set(0, 0, 0, 0); 2593 mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState); 2594 insets.left += mTempRect.left; 2595 insets.top += mTempRect.top; 2596 insets.right += mTempRect.right; 2597 insets.bottom += mTempRect.bottom; 2598 } 2599 lp.mInsetsDirty = false; 2600 return insets; 2601 } 2602 2603 private class ViewFlinger implements Runnable { 2604 private int mLastFlingX; 2605 private int mLastFlingY; 2606 private ScrollerCompat mScroller; 2607 private Interpolator mInterpolator = sQuinticInterpolator; 2608 2609 2610 // When set to true, postOnAnimation callbacks are delayed until the run method completes 2611 private boolean mEatRunOnAnimationRequest = false; 2612 2613 // Tracks if postAnimationCallback should be re-attached when it is done 2614 private boolean mReSchedulePostAnimationCallback = false; 2615 2616 public ViewFlinger() { 2617 mScroller = ScrollerCompat.create(getContext(), sQuinticInterpolator); 2618 } 2619 2620 @Override 2621 public void run() { 2622 disableRunOnAnimationRequests(); 2623 consumePendingUpdateOperations(); 2624 // keep a local reference so that if it is changed during onAnimation method, it won't 2625 // cause unexpected behaviors 2626 final ScrollerCompat scroller = mScroller; 2627 final SmoothScroller smoothScroller = mLayout.mSmoothScroller; 2628 if (scroller.computeScrollOffset()) { 2629 final int x = scroller.getCurrX(); 2630 final int y = scroller.getCurrY(); 2631 final int dx = x - mLastFlingX; 2632 final int dy = y - mLastFlingY; 2633 int hresult = 0; 2634 int vresult = 0; 2635 mLastFlingX = x; 2636 mLastFlingY = y; 2637 int overscrollX = 0, overscrollY = 0; 2638 if (mAdapter != null) { 2639 eatRequestLayout(); 2640 mRunningLayoutOrScroll = true; 2641 if (dx != 0) { 2642 hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState); 2643 overscrollX = dx - hresult; 2644 } 2645 if (dy != 0) { 2646 vresult = mLayout.scrollVerticallyBy(dy, mRecycler, mState); 2647 overscrollY = dy - vresult; 2648 } 2649 if (supportsChangeAnimations()) { 2650 // Fix up shadow views used by changing animations 2651 int count = mChildHelper.getChildCount(); 2652 for (int i = 0; i < count; i++) { 2653 View view = mChildHelper.getChildAt(i); 2654 ViewHolder holder = getChildViewHolder(view); 2655 if (holder != null && holder.mShadowingHolder != null) { 2656 View shadowingView = holder.mShadowingHolder != null ? 2657 holder.mShadowingHolder.itemView : null; 2658 if (shadowingView != null) { 2659 int left = view.getLeft(); 2660 int top = view.getTop(); 2661 if (left != shadowingView.getLeft() || 2662 top != shadowingView.getTop()) { 2663 shadowingView.layout(left, top, 2664 left + shadowingView.getWidth(), 2665 top + shadowingView.getHeight()); 2666 } 2667 } 2668 } 2669 } 2670 } 2671 2672 if (smoothScroller != null && !smoothScroller.isPendingInitialRun() && 2673 smoothScroller.isRunning()) { 2674 final int adapterSize = mState.getItemCount(); 2675 if (adapterSize == 0) { 2676 smoothScroller.stop(); 2677 } else if (smoothScroller.getTargetPosition() >= adapterSize) { 2678 smoothScroller.setTargetPosition(adapterSize - 1); 2679 smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY); 2680 } else { 2681 smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY); 2682 } 2683 } 2684 mRunningLayoutOrScroll = false; 2685 resumeRequestLayout(false); 2686 } 2687 final boolean fullyConsumedScroll = dx == hresult && dy == vresult; 2688 if (!mItemDecorations.isEmpty()) { 2689 invalidate(); 2690 } 2691 if (ViewCompat.getOverScrollMode(RecyclerView.this) != 2692 ViewCompat.OVER_SCROLL_NEVER) { 2693 considerReleasingGlowsOnScroll(dx, dy); 2694 } 2695 if (overscrollX != 0 || overscrollY != 0) { 2696 final int vel = (int) scroller.getCurrVelocity(); 2697 2698 int velX = 0; 2699 if (overscrollX != x) { 2700 velX = overscrollX < 0 ? -vel : overscrollX > 0 ? vel : 0; 2701 } 2702 2703 int velY = 0; 2704 if (overscrollY != y) { 2705 velY = overscrollY < 0 ? -vel : overscrollY > 0 ? vel : 0; 2706 } 2707 2708 if (ViewCompat.getOverScrollMode(RecyclerView.this) != 2709 ViewCompat.OVER_SCROLL_NEVER) { 2710 absorbGlows(velX, velY); 2711 } 2712 if ((velX != 0 || overscrollX == x || scroller.getFinalX() == 0) && 2713 (velY != 0 || overscrollY == y || scroller.getFinalY() == 0)) { 2714 scroller.abortAnimation(); 2715 } 2716 } 2717 if (mScrollListener != null && (hresult != 0 || vresult != 0)) { 2718 mScrollListener.onScrolled(RecyclerView.this, hresult, vresult); 2719 } 2720 2721 if (!awakenScrollBars()) { 2722 invalidate(); 2723 } 2724 2725 if (scroller.isFinished() || !fullyConsumedScroll) { 2726 setScrollState(SCROLL_STATE_IDLE); // setting state to idle will stop this. 2727 } else { 2728 postOnAnimation(); 2729 } 2730 } 2731 // call this after the onAnimation is complete not to have inconsistent callbacks etc. 2732 if (smoothScroller != null && smoothScroller.isPendingInitialRun()) { 2733 smoothScroller.onAnimation(0, 0); 2734 } 2735 enableRunOnAnimationRequests(); 2736 } 2737 2738 private void disableRunOnAnimationRequests() { 2739 mReSchedulePostAnimationCallback = false; 2740 mEatRunOnAnimationRequest = true; 2741 } 2742 2743 private void enableRunOnAnimationRequests() { 2744 mEatRunOnAnimationRequest = false; 2745 if (mReSchedulePostAnimationCallback) { 2746 postOnAnimation(); 2747 } 2748 } 2749 2750 void postOnAnimation() { 2751 if (mEatRunOnAnimationRequest) { 2752 mReSchedulePostAnimationCallback = true; 2753 } else { 2754 ViewCompat.postOnAnimation(RecyclerView.this, this); 2755 } 2756 } 2757 2758 public void fling(int velocityX, int velocityY) { 2759 setScrollState(SCROLL_STATE_SETTLING); 2760 mLastFlingX = mLastFlingY = 0; 2761 mScroller.fling(0, 0, velocityX, velocityY, 2762 Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE); 2763 postOnAnimation(); 2764 } 2765 2766 public void smoothScrollBy(int dx, int dy) { 2767 smoothScrollBy(dx, dy, 0, 0); 2768 } 2769 2770 public void smoothScrollBy(int dx, int dy, int vx, int vy) { 2771 smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, vx, vy)); 2772 } 2773 2774 private float distanceInfluenceForSnapDuration(float f) { 2775 f -= 0.5f; // center the values about 0. 2776 f *= 0.3f * Math.PI / 2.0f; 2777 return (float) Math.sin(f); 2778 } 2779 2780 private int computeScrollDuration(int dx, int dy, int vx, int vy) { 2781 final int absDx = Math.abs(dx); 2782 final int absDy = Math.abs(dy); 2783 final boolean horizontal = absDx > absDy; 2784 final int velocity = (int) Math.sqrt(vx * vx + vy * vy); 2785 final int delta = (int) Math.sqrt(dx * dx + dy * dy); 2786 final int containerSize = horizontal ? getWidth() : getHeight(); 2787 final int halfContainerSize = containerSize / 2; 2788 final float distanceRatio = Math.min(1.f, 1.f * delta / containerSize); 2789 final float distance = halfContainerSize + halfContainerSize * 2790 distanceInfluenceForSnapDuration(distanceRatio); 2791 2792 final int duration; 2793 if (velocity > 0) { 2794 duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 2795 } else { 2796 float absDelta = (float) (horizontal ? absDx : absDy); 2797 duration = (int) (((absDelta / containerSize) + 1) * 300); 2798 } 2799 return Math.min(duration, MAX_SCROLL_DURATION); 2800 } 2801 2802 public void smoothScrollBy(int dx, int dy, int duration) { 2803 smoothScrollBy(dx, dy, duration, sQuinticInterpolator); 2804 } 2805 2806 public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) { 2807 if (mInterpolator != interpolator) { 2808 mInterpolator = interpolator; 2809 mScroller = ScrollerCompat.create(getContext(), interpolator); 2810 } 2811 setScrollState(SCROLL_STATE_SETTLING); 2812 mLastFlingX = mLastFlingY = 0; 2813 mScroller.startScroll(0, 0, dx, dy, duration); 2814 postOnAnimation(); 2815 } 2816 2817 public void stop() { 2818 removeCallbacks(this); 2819 mScroller.abortAnimation(); 2820 } 2821 2822 } 2823 2824 private class RecyclerViewDataObserver extends AdapterDataObserver { 2825 @Override 2826 public void onChanged() { 2827 assertNotInLayoutOrScroll(null); 2828 if (mAdapter.hasStableIds()) { 2829 // TODO Determine what actually changed. 2830 // This is more important to implement now since this callback will disable all 2831 // animations because we cannot rely on positions. 2832 mState.mStructureChanged = true; 2833 mDataSetHasChangedAfterLayout = true; 2834 } else { 2835 mState.mStructureChanged = true; 2836 mDataSetHasChangedAfterLayout = true; 2837 } 2838 if (!mAdapterHelper.hasPendingUpdates()) { 2839 requestLayout(); 2840 } 2841 } 2842 2843 @Override 2844 public void onItemRangeChanged(int positionStart, int itemCount) { 2845 assertNotInLayoutOrScroll(null); 2846 if (mAdapterHelper.onItemRangeChanged(positionStart, itemCount)) { 2847 triggerUpdateProcessor(); 2848 } 2849 } 2850 2851 @Override 2852 public void onItemRangeInserted(int positionStart, int itemCount) { 2853 assertNotInLayoutOrScroll(null); 2854 if (mAdapterHelper.onItemRangeInserted(positionStart, itemCount)) { 2855 triggerUpdateProcessor(); 2856 } 2857 } 2858 2859 @Override 2860 public void onItemRangeRemoved(int positionStart, int itemCount) { 2861 assertNotInLayoutOrScroll(null); 2862 if (mAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) { 2863 triggerUpdateProcessor(); 2864 } 2865 } 2866 2867 @Override 2868 public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { 2869 assertNotInLayoutOrScroll(null); 2870 if (mAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) { 2871 triggerUpdateProcessor(); 2872 } 2873 } 2874 2875 void triggerUpdateProcessor() { 2876 if (mPostUpdatesOnAnimation && mHasFixedSize && mIsAttached) { 2877 ViewCompat.postOnAnimation(RecyclerView.this, mUpdateChildViewsRunnable); 2878 } else { 2879 mAdapterUpdateDuringMeasure = true; 2880 requestLayout(); 2881 } 2882 } 2883 } 2884 2885 /** 2886 * RecycledViewPool lets you share Views between multiple RecyclerViews. 2887 * <p> 2888 * If you want to recycle views across RecyclerViews, create an instance of RecycledViewPool 2889 * and use {@link RecyclerView#setRecycledViewPool(RecycledViewPool)}. 2890 * <p> 2891 * RecyclerView automatically creates a pool for itself if you don't provide one. 2892 * 2893 */ 2894 public static class RecycledViewPool { 2895 private SparseArray<ArrayList<ViewHolder>> mScrap = 2896 new SparseArray<ArrayList<ViewHolder>>(); 2897 private SparseIntArray mMaxScrap = new SparseIntArray(); 2898 private int mAttachCount = 0; 2899 2900 private static final int DEFAULT_MAX_SCRAP = 5; 2901 2902 public void clear() { 2903 mScrap.clear(); 2904 } 2905 2906 public void setMaxRecycledViews(int viewType, int max) { 2907 mMaxScrap.put(viewType, max); 2908 final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType); 2909 if (scrapHeap != null) { 2910 while (scrapHeap.size() > max) { 2911 scrapHeap.remove(scrapHeap.size() - 1); 2912 } 2913 } 2914 } 2915 2916 public ViewHolder getRecycledView(int viewType) { 2917 final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType); 2918 if (scrapHeap != null && !scrapHeap.isEmpty()) { 2919 final int index = scrapHeap.size() - 1; 2920 final ViewHolder scrap = scrapHeap.get(index); 2921 scrapHeap.remove(index); 2922 return scrap; 2923 } 2924 return null; 2925 } 2926 2927 int size() { 2928 int count = 0; 2929 for (int i = 0; i < mScrap.size(); i ++) { 2930 ArrayList<ViewHolder> viewHolders = mScrap.valueAt(i); 2931 if (viewHolders != null) { 2932 count += viewHolders.size(); 2933 } 2934 } 2935 return count; 2936 } 2937 2938 public void putRecycledView(ViewHolder scrap) { 2939 final int viewType = scrap.getItemViewType(); 2940 final ArrayList scrapHeap = getScrapHeapForType(viewType); 2941 if (mMaxScrap.get(viewType) <= scrapHeap.size()) { 2942 return; 2943 } 2944 scrap.resetInternal(); 2945 scrapHeap.add(scrap); 2946 } 2947 2948 void attach(Adapter adapter) { 2949 mAttachCount++; 2950 } 2951 2952 void detach() { 2953 mAttachCount--; 2954 } 2955 2956 2957 /** 2958 * Detaches the old adapter and attaches the new one. 2959 * <p> 2960 * RecycledViewPool will clear its cache if it has only one adapter attached and the new 2961 * adapter uses a different ViewHolder than the oldAdapter. 2962 * 2963 * @param oldAdapter The previous adapter instance. Will be detached. 2964 * @param newAdapter The new adapter instance. Will be attached. 2965 * @param compatibleWithPrevious True if both oldAdapter and newAdapter are using the same 2966 * ViewHolder and view types. 2967 */ 2968 void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter, 2969 boolean compatibleWithPrevious) { 2970 if (oldAdapter != null) { 2971 detach(); 2972 } 2973 if (!compatibleWithPrevious && mAttachCount == 0) { 2974 clear(); 2975 } 2976 if (newAdapter != null) { 2977 attach(newAdapter); 2978 } 2979 } 2980 2981 private ArrayList<ViewHolder> getScrapHeapForType(int viewType) { 2982 ArrayList<ViewHolder> scrap = mScrap.get(viewType); 2983 if (scrap == null) { 2984 scrap = new ArrayList<ViewHolder>(); 2985 mScrap.put(viewType, scrap); 2986 if (mMaxScrap.indexOfKey(viewType) < 0) { 2987 mMaxScrap.put(viewType, DEFAULT_MAX_SCRAP); 2988 } 2989 } 2990 return scrap; 2991 } 2992 } 2993 2994 /** 2995 * A Recycler is responsible for managing scrapped or detached item views for reuse. 2996 * 2997 * <p>A "scrapped" view is a view that is still attached to its parent RecyclerView but 2998 * that has been marked for removal or reuse.</p> 2999 * 3000 * <p>Typical use of a Recycler by a {@link LayoutManager} will be to obtain views for 3001 * an adapter's data set representing the data at a given position or item ID. 3002 * If the view to be reused is considered "dirty" the adapter will be asked to rebind it. 3003 * If not, the view can be quickly reused by the LayoutManager with no further work. 3004 * Clean views that have not {@link android.view.View#isLayoutRequested() requested layout} 3005 * may be repositioned by a LayoutManager without remeasurement.</p> 3006 */ 3007 public final class Recycler { 3008 private final ArrayList<ViewHolder> mAttachedScrap = new ArrayList<ViewHolder>(); 3009 private ArrayList<ViewHolder> mChangedScrap = null; 3010 3011 final ArrayList<ViewHolder> mCachedViews = new ArrayList<ViewHolder>(); 3012 3013 private final List<ViewHolder> 3014 mUnmodifiableAttachedScrap = Collections.unmodifiableList(mAttachedScrap); 3015 3016 private int mViewCacheMax = DEFAULT_CACHE_SIZE; 3017 3018 private RecycledViewPool mRecyclerPool; 3019 3020 private ViewCacheExtension mViewCacheExtension; 3021 3022 private static final int DEFAULT_CACHE_SIZE = 2; 3023 3024 /** 3025 * Clear scrap views out of this recycler. Detached views contained within a 3026 * recycled view pool will remain. 3027 */ 3028 public void clear() { 3029 mAttachedScrap.clear(); 3030 recycleAndClearCachedViews(); 3031 } 3032 3033 /** 3034 * Set the maximum number of detached, valid views we should retain for later use. 3035 * 3036 * @param viewCount Number of views to keep before sending views to the shared pool 3037 */ 3038 public void setViewCacheSize(int viewCount) { 3039 mViewCacheMax = viewCount; 3040 // first, try the views that can be recycled 3041 for (int i = mCachedViews.size() - 1; i >= 0 && mCachedViews.size() > viewCount; i--) { 3042 tryToRecycleCachedViewAt(i); 3043 } 3044 // if we could not recycle enough of them, remove some. 3045 while (mCachedViews.size() > viewCount) { 3046 mCachedViews.remove(mCachedViews.size() - 1); 3047 } 3048 } 3049 3050 /** 3051 * Returns an unmodifiable list of ViewHolders that are currently in the scrap list. 3052 * 3053 * @return List of ViewHolders in the scrap list. 3054 */ 3055 public List<ViewHolder> getScrapList() { 3056 return mUnmodifiableAttachedScrap; 3057 } 3058 3059 /** 3060 * Helper method for getViewForPosition. 3061 * <p> 3062 * Checks whether a given view holder can be used for the provided position. 3063 * 3064 * @param holder ViewHolder 3065 * @return true if ViewHolder matches the provided position, false otherwise 3066 */ 3067 boolean validateViewHolderForOffsetPosition(ViewHolder holder) { 3068 // if it is a removed holder, nothing to verify since we cannot ask adapter anymore 3069 // if it is not removed, verify the type and id. 3070 if (holder.isRemoved()) { 3071 return true; 3072 } 3073 if (holder.mPosition < 0 || holder.mPosition >= mAdapter.getItemCount()) { 3074 throw new IndexOutOfBoundsException("Inconsistency detected. Invalid view holder " 3075 + "adapter position" + holder); 3076 } 3077 if (!mState.isPreLayout()) { 3078 // don't check type if it is pre-layout. 3079 final int type = mAdapter.getItemViewType(holder.mPosition); 3080 if (type != holder.getItemViewType()) { 3081 return false; 3082 } 3083 } 3084 if (mAdapter.hasStableIds()) { 3085 return holder.getItemId() == mAdapter.getItemId(holder.mPosition); 3086 } 3087 return true; 3088 } 3089 3090 /** 3091 * Binds the given View to the position. The View can be a View previously retrieved via 3092 * {@link #getViewForPosition(int)} or created by 3093 * {@link Adapter#onCreateViewHolder(ViewGroup, int)}. 3094 * <p> 3095 * Generally, a LayoutManager should acquire its views via {@link #getViewForPosition(int)} 3096 * and let the RecyclerView handle caching. This is a helper method for LayoutManager who 3097 * wants to handle its own recycling logic. 3098 * <p> 3099 * Note that, {@link #getViewForPosition(int)} already binds the View to the position so 3100 * you don't need to call this method unless you want to bind this View to another position. 3101 * 3102 * @param view The view to update. 3103 * @param position The position of the item to bind to this View. 3104 */ 3105 public void bindViewToPosition(View view, int position) { 3106 ViewHolder holder = getChildViewHolderInt(view); 3107 if (holder == null) { 3108 throw new IllegalArgumentException("The view does not have a ViewHolder. You cannot" 3109 + " pass arbitrary views to this method, they should be created by the " 3110 + "Adapter"); 3111 } 3112 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 3113 if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) { 3114 throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item " 3115 + "position " + position + "(offset:" + offsetPosition + ")." 3116 + "state:" + mState.getItemCount()); 3117 } 3118 mAdapter.bindViewHolder(holder, offsetPosition); 3119 if (mState.isPreLayout()) { 3120 holder.mPreLayoutPosition = position; 3121 } 3122 3123 ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); 3124 if (lp == null) { 3125 lp = generateDefaultLayoutParams(); 3126 holder.itemView.setLayoutParams(lp); 3127 } else if (!checkLayoutParams(lp)) { 3128 lp = generateLayoutParams(lp); 3129 holder.itemView.setLayoutParams(lp); 3130 } 3131 ((LayoutParams) lp).mInsetsDirty = true; 3132 ((LayoutParams) lp).mViewHolder = holder; 3133 } 3134 3135 /** 3136 * RecyclerView provides artificial position range (item count) in pre-layout state and 3137 * automatically maps these positions to {@link Adapter} positions when 3138 * {@link #getViewForPosition(int)} or {@link #bindViewToPosition(View, int)} is called. 3139 * <p> 3140 * Usually, LayoutManager does not need to worry about this. However, in some cases, your 3141 * LayoutManager may need to call some custom component with item positions in which 3142 * case you need the actual adapter position instead of the pre layout position. You 3143 * can use this method to convert a pre-layout position to adapter (post layout) position. 3144 * <p> 3145 * Note that if the provided position belongs to a deleted ViewHolder, this method will 3146 * return -1. 3147 * <p> 3148 * Calling this method in post-layout state returns the same value back. 3149 * 3150 * @param position The pre-layout position to convert. Must be greater or equal to 0 and 3151 * less than {@link State#getItemCount()}. 3152 */ 3153 public int convertPreLayoutPositionToPostLayout(int position) { 3154 if (position < 0 || position >= mState.getItemCount()) { 3155 throw new IndexOutOfBoundsException("invalid position " + position + ". State " 3156 + "item count is " + mState.getItemCount()); 3157 } 3158 if (!mState.isPreLayout()) { 3159 return position; 3160 } 3161 return mAdapterHelper.findPositionOffset(position); 3162 } 3163 3164 /** 3165 * Obtain a view initialized for the given position. 3166 * 3167 * This method should be used by {@link LayoutManager} implementations to obtain 3168 * views to represent data from an {@link Adapter}. 3169 * <p> 3170 * The Recycler may reuse a scrap or detached view from a shared pool if one is 3171 * available for the correct view type. If the adapter has not indicated that the 3172 * data at the given position has changed, the Recycler will attempt to hand back 3173 * a scrap view that was previously initialized for that data without rebinding. 3174 * 3175 * @param position Position to obtain a view for 3176 * @return A view representing the data at <code>position</code> from <code>adapter</code> 3177 */ 3178 public View getViewForPosition(int position) { 3179 return getViewForPosition(position, false); 3180 } 3181 3182 View getViewForPosition(int position, boolean dryRun) { 3183 if (position < 0 || position >= mState.getItemCount()) { 3184 throw new IndexOutOfBoundsException("Invalid item position " + position 3185 + "(" + position + "). Item count:" + mState.getItemCount()); 3186 } 3187 ViewHolder holder = null; 3188 // 0) If there is a changed scrap, try to find from there 3189 if (mState.isPreLayout()) { 3190 holder = getChangedScrapViewForPosition(position); 3191 } 3192 // 1) Find from scrap by position 3193 if (holder == null) { 3194 holder = getScrapViewForPosition(position, INVALID_TYPE, dryRun); 3195 if (holder != null) { 3196 if (!validateViewHolderForOffsetPosition(holder)) { 3197 // recycle this scrap 3198 if (!dryRun) { 3199 // we would like to recycle this but need to make sure it is not used by 3200 // animation logic etc. 3201 holder.addFlags(ViewHolder.FLAG_INVALID); 3202 if (holder.isScrap()) { 3203 removeDetachedView(holder.itemView, false); 3204 holder.unScrap(); 3205 } else if (holder.wasReturnedFromScrap()) { 3206 holder.clearReturnedFromScrapFlag(); 3207 } 3208 recycleViewHolderInternal(holder); 3209 } 3210 holder = null; 3211 } 3212 } 3213 } 3214 if (holder == null) { 3215 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 3216 if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) { 3217 throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item " 3218 + "position " + position + "(offset:" + offsetPosition + ")." 3219 + "state:" + mState.getItemCount()); 3220 } 3221 3222 final int type = mAdapter.getItemViewType(offsetPosition); 3223 // 2) Find from scrap via stable ids, if exists 3224 if (mAdapter.hasStableIds()) { 3225 holder = getScrapViewForId(mAdapter.getItemId(offsetPosition), type, dryRun); 3226 if (holder != null) { 3227 // update position 3228 holder.mPosition = offsetPosition; 3229 } 3230 } 3231 if (holder == null && mViewCacheExtension != null) { 3232 // We are NOT sending the offsetPosition because LayoutManager does not 3233 // know it. 3234 final View view = mViewCacheExtension 3235 .getViewForPositionAndType(this, position, type); 3236 if (view != null) { 3237 holder = getChildViewHolder(view); 3238 if (holder == null) { 3239 throw new IllegalArgumentException("getViewForPositionAndType returned" 3240 + " a view which does not have a ViewHolder"); 3241 } else if (holder.shouldIgnore()) { 3242 throw new IllegalArgumentException("getViewForPositionAndType returned" 3243 + " a view that is ignored. You must call stopIgnoring before" 3244 + " returning this view."); 3245 } 3246 } 3247 } 3248 if (holder == null) { // fallback to recycler 3249 // try recycler. 3250 // Head to the shared pool. 3251 if (DEBUG) { 3252 Log.d(TAG, "getViewForPosition(" + position + ") fetching from shared " 3253 + "pool"); 3254 } 3255 holder = getRecycledViewPool() 3256 .getRecycledView(mAdapter.getItemViewType(offsetPosition)); 3257 if (holder != null) { 3258 holder.resetInternal(); 3259 if (FORCE_INVALIDATE_DISPLAY_LIST) { 3260 invalidateDisplayListInt(holder); 3261 } 3262 } 3263 } 3264 if (holder == null) { 3265 holder = mAdapter.createViewHolder(RecyclerView.this, 3266 mAdapter.getItemViewType(offsetPosition)); 3267 if (DEBUG) { 3268 Log.d(TAG, "getViewForPosition created new ViewHolder"); 3269 } 3270 } 3271 } 3272 3273 if (mState.isPreLayout() && holder.isBound()) { 3274 // do not update unless we absolutely have to. 3275 holder.mPreLayoutPosition = position; 3276 } else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) { 3277 if (DEBUG && holder.isRemoved()) { 3278 throw new IllegalStateException("Removed holder should be bound and it should" 3279 + " come here only in pre-layout. Holder: " + holder); 3280 } 3281 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 3282 mAdapter.bindViewHolder(holder, offsetPosition); 3283 if (mState.isPreLayout()) { 3284 holder.mPreLayoutPosition = position; 3285 } 3286 } 3287 3288 ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); 3289 if (lp == null) { 3290 lp = generateDefaultLayoutParams(); 3291 holder.itemView.setLayoutParams(lp); 3292 } else if (!checkLayoutParams(lp)) { 3293 lp = generateLayoutParams(lp); 3294 holder.itemView.setLayoutParams(lp); 3295 } 3296 ((LayoutParams) lp).mViewHolder = holder; 3297 3298 return holder.itemView; 3299 } 3300 3301 private void invalidateDisplayListInt(ViewHolder holder) { 3302 if (holder.itemView instanceof ViewGroup) { 3303 invalidateDisplayListInt((ViewGroup) holder.itemView, false); 3304 } 3305 } 3306 3307 private void invalidateDisplayListInt(ViewGroup viewGroup, boolean invalidateThis) { 3308 for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) { 3309 final View view = viewGroup.getChildAt(i); 3310 if (view instanceof ViewGroup) { 3311 invalidateDisplayListInt((ViewGroup) view, true); 3312 } 3313 } 3314 if (!invalidateThis) { 3315 return; 3316 } 3317 // we need to force it to become invisible 3318 if (viewGroup.getVisibility() == View.INVISIBLE) { 3319 viewGroup.setVisibility(View.VISIBLE); 3320 viewGroup.setVisibility(View.INVISIBLE); 3321 } else { 3322 final int visibility = viewGroup.getVisibility(); 3323 viewGroup.setVisibility(View.INVISIBLE); 3324 viewGroup.setVisibility(visibility); 3325 } 3326 } 3327 3328 /** 3329 * Recycle a detached view. The specified view will be added to a pool of views 3330 * for later rebinding and reuse. 3331 * 3332 * <p>A view must be fully detached before it may be recycled. If the View is scrapped, 3333 * it will be removed from scrap list.</p> 3334 * 3335 * @param view Removed view for recycling 3336 * @see LayoutManager#removeAndRecycleView(View, Recycler) 3337 */ 3338 public void recycleView(View view) { 3339 // This public recycle method tries to make view recycle-able since layout manager 3340 // intended to recycle this view (e.g. even if it is in scrap or change cache) 3341 ViewHolder holder = getChildViewHolderInt(view); 3342 if (holder.isScrap()) { 3343 holder.unScrap(); 3344 } else if (holder.wasReturnedFromScrap()){ 3345 holder.clearReturnedFromScrapFlag(); 3346 } 3347 recycleViewHolderInternal(holder); 3348 } 3349 3350 /** 3351 * Internally, use this method instead of {@link #recycleView(android.view.View)} to 3352 * catch potential bugs. 3353 * @param view 3354 */ 3355 void recycleViewInternal(View view) { 3356 recycleViewHolderInternal(getChildViewHolderInt(view)); 3357 } 3358 3359 void recycleAndClearCachedViews() { 3360 final int count = mCachedViews.size(); 3361 for (int i = count - 1; i >= 0; i--) { 3362 tryToRecycleCachedViewAt(i); 3363 } 3364 mCachedViews.clear(); 3365 } 3366 3367 /** 3368 * Tries to recyle a cached view and removes the view from the list if and only if it 3369 * is recycled. 3370 * 3371 * @param cachedViewIndex The index of the view in cached views list 3372 * @return True if item is recycled 3373 */ 3374 boolean tryToRecycleCachedViewAt(int cachedViewIndex) { 3375 if (DEBUG) { 3376 Log.d(TAG, "Recycling cached view at index " + cachedViewIndex); 3377 } 3378 ViewHolder viewHolder = mCachedViews.get(cachedViewIndex); 3379 if (DEBUG) { 3380 Log.d(TAG, "CachedViewHolder to be recycled(if recycleable): " + viewHolder); 3381 } 3382 if (viewHolder.isRecyclable()) { 3383 getRecycledViewPool().putRecycledView(viewHolder); 3384 dispatchViewRecycled(viewHolder); 3385 mCachedViews.remove(cachedViewIndex); 3386 return true; 3387 } 3388 return false; 3389 } 3390 3391 /** 3392 * internal implementation checks if view is scrapped or attached and throws an exception 3393 * if so. 3394 * Public version un-scraps before calling recycle. 3395 */ 3396 void recycleViewHolderInternal(ViewHolder holder) { 3397 if (holder.isScrap() || holder.itemView.getParent() != null) { 3398 throw new IllegalArgumentException( 3399 "Scrapped or attached views may not be recycled. isScrap:" 3400 + holder.isScrap() + " isAttached:" 3401 + (holder.itemView.getParent() != null)); 3402 } 3403 3404 if (holder.shouldIgnore()) { 3405 throw new IllegalArgumentException("Trying to recycle an ignored view holder. You" 3406 + " should first call stopIgnoringView(view) before calling recycle."); 3407 } 3408 if (holder.isRecyclable()) { 3409 boolean cached = false; 3410 if (!holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved()) && 3411 !holder.isChanged()) { 3412 // Retire oldest cached views first 3413 if (mCachedViews.size() == mViewCacheMax && !mCachedViews.isEmpty()) { 3414 for (int i = 0; i < mCachedViews.size(); i++) { 3415 if (tryToRecycleCachedViewAt(i)) { 3416 break; 3417 } 3418 } 3419 } 3420 if (mCachedViews.size() < mViewCacheMax) { 3421 mCachedViews.add(holder); 3422 cached = true; 3423 } 3424 } 3425 if (!cached) { 3426 getRecycledViewPool().putRecycledView(holder); 3427 dispatchViewRecycled(holder); 3428 } 3429 } else if (DEBUG) { 3430 Log.d(TAG, "trying to recycle a non-recycleable holder. Hopefully, it will " 3431 + "re-visit here. We are stil removing it from animation lists"); 3432 } 3433 // even if the holder is not removed, we still call this method so that it is removed 3434 // from view holder lists. 3435 mState.onViewRecycled(holder); 3436 } 3437 3438 /** 3439 * Used as a fast path for unscrapping and recycling a view during a bulk operation. 3440 * The caller must call {@link #clearScrap()} when it's done to update the recycler's 3441 * internal bookkeeping. 3442 */ 3443 void quickRecycleScrapView(View view) { 3444 final ViewHolder holder = getChildViewHolderInt(view); 3445 holder.mScrapContainer = null; 3446 holder.clearReturnedFromScrapFlag(); 3447 recycleViewHolderInternal(holder); 3448 } 3449 3450 /** 3451 * Mark an attached view as scrap. 3452 * 3453 * <p>"Scrap" views are still attached to their parent RecyclerView but are eligible 3454 * for rebinding and reuse. Requests for a view for a given position may return a 3455 * reused or rebound scrap view instance.</p> 3456 * 3457 * @param view View to scrap 3458 */ 3459 void scrapView(View view) { 3460 final ViewHolder holder = getChildViewHolderInt(view); 3461 holder.setScrapContainer(this); 3462 if (!holder.isChanged() || !supportsChangeAnimations()) { 3463 if (holder.isInvalid() && !holder.isRemoved() && !mAdapter.hasStableIds()) { 3464 throw new IllegalArgumentException("Called scrap view with an invalid view." 3465 + " Invalid views cannot be reused from scrap, they should rebound from" 3466 + " recycler pool."); 3467 } 3468 mAttachedScrap.add(holder); 3469 } else { 3470 if (mChangedScrap == null) { 3471 mChangedScrap = new ArrayList<ViewHolder>(); 3472 } 3473 mChangedScrap.add(holder); 3474 } 3475 } 3476 3477 /** 3478 * Remove a previously scrapped view from the pool of eligible scrap. 3479 * 3480 * <p>This view will no longer be eligible for reuse until re-scrapped or 3481 * until it is explicitly removed and recycled.</p> 3482 */ 3483 void unscrapView(ViewHolder holder) { 3484 if (!holder.isChanged() || !supportsChangeAnimations() || mChangedScrap == null) { 3485 mAttachedScrap.remove(holder); 3486 } else { 3487 mChangedScrap.remove(holder); 3488 } 3489 holder.mScrapContainer = null; 3490 holder.clearReturnedFromScrapFlag(); 3491 } 3492 3493 int getScrapCount() { 3494 return mAttachedScrap.size(); 3495 } 3496 3497 View getScrapViewAt(int index) { 3498 return mAttachedScrap.get(index).itemView; 3499 } 3500 3501 void clearScrap() { 3502 mAttachedScrap.clear(); 3503 } 3504 3505 ViewHolder getChangedScrapViewForPosition(int position) { 3506 // If pre-layout, check the changed scrap for an exact match. 3507 final int changedScrapSize; 3508 if (mChangedScrap == null || (changedScrapSize = mChangedScrap.size()) == 0) { 3509 return null; 3510 } 3511 // find by position 3512 for (int i = 0; i < changedScrapSize; i++) { 3513 final ViewHolder holder = mChangedScrap.get(i); 3514 if (!holder.wasReturnedFromScrap() && holder.getPosition() == position) { 3515 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 3516 return holder; 3517 } 3518 } 3519 // find by id 3520 if (mAdapter.hasStableIds()) { 3521 final int offsetPosition = mAdapterHelper.findPositionOffset(position); 3522 if (offsetPosition > 0 && offsetPosition < mAdapter.getItemCount()) { 3523 final long id = mAdapter.getItemId(offsetPosition); 3524 for (int i = 0; i < changedScrapSize; i++) { 3525 final ViewHolder holder = mChangedScrap.get(i); 3526 if (!holder.wasReturnedFromScrap() && holder.getItemId() == id) { 3527 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 3528 return holder; 3529 } 3530 } 3531 } 3532 } 3533 return null; 3534 } 3535 3536 /** 3537 * Returns a scrap view for the position. If type is not INVALID_TYPE, it also checks if 3538 * ViewHolder's type matches the provided type. 3539 * 3540 * @param position Item position 3541 * @param type View type 3542 * @param dryRun Does a dry run, finds the ViewHolder but does not remove 3543 * @return a ViewHolder that can be re-used for this position. 3544 */ 3545 ViewHolder getScrapViewForPosition(int position, int type, boolean dryRun) { 3546 final int scrapCount = mAttachedScrap.size(); 3547 3548 // Try first for an exact, non-invalid match from scrap. 3549 for (int i = 0; i < scrapCount; i++) { 3550 final ViewHolder holder = mAttachedScrap.get(i); 3551 if (!holder.wasReturnedFromScrap() && holder.getPosition() == position 3552 && !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) { 3553 if (type != INVALID_TYPE && holder.getItemViewType() != type) { 3554 Log.e(TAG, "Scrap view for position " + position + " isn't dirty but has" + 3555 " wrong view type! (found " + holder.getItemViewType() + 3556 " but expected " + type + ")"); 3557 break; 3558 } 3559 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 3560 return holder; 3561 } 3562 } 3563 3564 if (!dryRun) { 3565 View view = mChildHelper.findHiddenNonRemovedView(position, type); 3566 if (view != null) { 3567 // ending the animation should cause it to get recycled before we reuse it 3568 mItemAnimator.endAnimation(getChildViewHolder(view)); 3569 } 3570 } 3571 3572 // Search in our first-level recycled view cache. 3573 final int cacheSize = mCachedViews.size(); 3574 for (int i = 0; i < cacheSize; i++) { 3575 final ViewHolder holder = mCachedViews.get(i); 3576 // invalid view holders may be in cache if adapter has stable ids as they can be 3577 // retrieved via getScrapViewForId 3578 if (!holder.isInvalid() && holder.getPosition() == position) { 3579 if (!dryRun) { 3580 mCachedViews.remove(i); 3581 } 3582 if (DEBUG) { 3583 Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type + 3584 ") found match in cache: " + holder); 3585 } 3586 return holder; 3587 } 3588 } 3589 return null; 3590 } 3591 3592 ViewHolder getScrapViewForId(long id, int type, boolean dryRun) { 3593 // Look in our attached views first 3594 final int count = mAttachedScrap.size(); 3595 for (int i = count - 1; i >= 0; i--) { 3596 final ViewHolder holder = mAttachedScrap.get(i); 3597 if (holder.getItemId() == id && !holder.wasReturnedFromScrap()) { 3598 if (type == holder.getItemViewType()) { 3599 holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP); 3600 if (holder.isRemoved()) { 3601 // this might be valid in two cases: 3602 // > item is removed but we are in pre-layout pass 3603 // >> do nothing. return as is. make sure we don't rebind 3604 // > item is removed then added to another position and we are in 3605 // post layout. 3606 // >> remove removed and invalid flags, add update flag to rebind 3607 // because item was invisible to us and we don't know what happened in 3608 // between. 3609 if (!mState.isPreLayout()) { 3610 holder.setFlags(ViewHolder.FLAG_UPDATE, ViewHolder.FLAG_UPDATE | 3611 ViewHolder.FLAG_INVALID | ViewHolder.FLAG_REMOVED); 3612 } 3613 } 3614 return holder; 3615 } else if (!dryRun) { 3616 // Recycle this scrap. Type mismatch. 3617 mAttachedScrap.remove(i); 3618 removeDetachedView(holder.itemView, false); 3619 quickRecycleScrapView(holder.itemView); 3620 } 3621 } 3622 } 3623 3624 // Search the first-level cache 3625 final int cacheSize = mCachedViews.size(); 3626 for (int i = cacheSize - 1; i >= 0; i--) { 3627 final ViewHolder holder = mCachedViews.get(i); 3628 if (holder.getItemId() == id) { 3629 if (type == holder.getItemViewType()) { 3630 if (!dryRun) { 3631 mCachedViews.remove(i); 3632 } 3633 return holder; 3634 } else if (!dryRun) { 3635 tryToRecycleCachedViewAt(i); 3636 } 3637 } 3638 } 3639 return null; 3640 } 3641 3642 void dispatchViewRecycled(ViewHolder holder) { 3643 if (mRecyclerListener != null) { 3644 mRecyclerListener.onViewRecycled(holder); 3645 } 3646 if (mAdapter != null) { 3647 mAdapter.onViewRecycled(holder); 3648 } 3649 if (mState != null) { 3650 mState.onViewRecycled(holder); 3651 } 3652 if (DEBUG) Log.d(TAG, "dispatchViewRecycled: " + holder); 3653 } 3654 3655 void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter, 3656 boolean compatibleWithPrevious) { 3657 clear(); 3658 getRecycledViewPool().onAdapterChanged(oldAdapter, newAdapter, compatibleWithPrevious); 3659 } 3660 3661 void offsetPositionRecordsForMove(int from, int to) { 3662 final int start, end, inBetweenOffset; 3663 if (from < to) { 3664 start = from; 3665 end = to; 3666 inBetweenOffset = -1; 3667 } else { 3668 start = to; 3669 end = from; 3670 inBetweenOffset = 1; 3671 } 3672 final int cachedCount = mCachedViews.size(); 3673 for (int i = 0; i < cachedCount; i++) { 3674 final ViewHolder holder = mCachedViews.get(i); 3675 if (holder == null || holder.mPosition < start || holder.mPosition > end) { 3676 continue; 3677 } 3678 if (holder.mPosition == from) { 3679 holder.offsetPosition(to - from, false); 3680 } else { 3681 holder.offsetPosition(inBetweenOffset, false); 3682 } 3683 if (DEBUG) { 3684 Log.d(TAG, "offsetPositionRecordsForMove cached child " + i + " holder " + 3685 holder); 3686 } 3687 } 3688 } 3689 3690 void offsetPositionRecordsForInsert(int insertedAt, int count) { 3691 final int cachedCount = mCachedViews.size(); 3692 for (int i = 0; i < cachedCount; i++) { 3693 final ViewHolder holder = mCachedViews.get(i); 3694 if (holder != null && holder.getPosition() >= insertedAt) { 3695 if (DEBUG) { 3696 Log.d(TAG, "offsetPositionRecordsForInsert cached " + i + " holder " + 3697 holder + " now at position " + (holder.mPosition + count)); 3698 } 3699 holder.offsetPosition(count, true); 3700 } 3701 } 3702 } 3703 3704 /** 3705 * @param removedFrom Remove start index 3706 * @param count Remove count 3707 * @param applyToPreLayout If true, changes will affect ViewHolder's pre-layout position, if 3708 * false, they'll be applied before the second layout pass 3709 */ 3710 void offsetPositionRecordsForRemove(int removedFrom, int count, boolean applyToPreLayout) { 3711 final int removedEnd = removedFrom + count; 3712 final int cachedCount = mCachedViews.size(); 3713 for (int i = cachedCount - 1; i >= 0; i--) { 3714 final ViewHolder holder = mCachedViews.get(i); 3715 if (holder != null) { 3716 if (holder.getPosition() >= removedEnd) { 3717 if (DEBUG) { 3718 Log.d(TAG, "offsetPositionRecordsForRemove cached " + i + 3719 " holder " + holder + " now at position " + 3720 (holder.mPosition - count)); 3721 } 3722 holder.offsetPosition(-count, applyToPreLayout); 3723 } else if (holder.getPosition() >= removedFrom) { 3724 // Item for this view was removed. Dump it from the cache. 3725 if (!tryToRecycleCachedViewAt(i)) { 3726 // if we cannot recycle it, at least invalidate so that we won't return 3727 // it by position. 3728 holder.addFlags(ViewHolder.FLAG_INVALID); 3729 if (DEBUG) { 3730 Log.d(TAG, "offsetPositionRecordsForRemove cached " + i + 3731 " holder " + holder + " now flagged as invalid because it " 3732 + "could not be recycled"); 3733 } 3734 } else if (DEBUG) { 3735 Log.d(TAG, "offsetPositionRecordsForRemove cached " + i + 3736 " holder " + holder + " now placed in pool"); 3737 } 3738 } 3739 } 3740 } 3741 } 3742 3743 void setViewCacheExtension(ViewCacheExtension extension) { 3744 mViewCacheExtension = extension; 3745 } 3746 3747 void setRecycledViewPool(RecycledViewPool pool) { 3748 if (mRecyclerPool != null) { 3749 mRecyclerPool.detach(); 3750 } 3751 mRecyclerPool = pool; 3752 if (pool != null) { 3753 mRecyclerPool.attach(getAdapter()); 3754 } 3755 } 3756 3757 RecycledViewPool getRecycledViewPool() { 3758 if (mRecyclerPool == null) { 3759 mRecyclerPool = new RecycledViewPool(); 3760 } 3761 return mRecyclerPool; 3762 } 3763 3764 void viewRangeUpdate(int positionStart, int itemCount) { 3765 final int positionEnd = positionStart + itemCount; 3766 final int cachedCount = mCachedViews.size(); 3767 for (int i = 0; i < cachedCount; i++) { 3768 final ViewHolder holder = mCachedViews.get(i); 3769 if (holder == null) { 3770 continue; 3771 } 3772 3773 final int pos = holder.getPosition(); 3774 if (pos >= positionStart && pos < positionEnd) { 3775 holder.addFlags(ViewHolder.FLAG_UPDATE); 3776 if (supportsChangeAnimations()) { 3777 holder.addFlags(ViewHolder.FLAG_CHANGED); 3778 } 3779 } 3780 } 3781 } 3782 3783 void markKnownViewsInvalid() { 3784 if (mAdapter != null && mAdapter.hasStableIds()) { 3785 final int cachedCount = mCachedViews.size(); 3786 for (int i = 0; i < cachedCount; i++) { 3787 final ViewHolder holder = mCachedViews.get(i); 3788 if (holder != null) { 3789 holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID); 3790 } 3791 } 3792 } else { 3793 // we cannot re-use cached views in this case. Recycle the ones we can and flag 3794 // the remaining as invalid so that they can be recycled later on (when their 3795 // animations end.) 3796 for (int i = mCachedViews.size() - 1; i >= 0; i--) { 3797 if (!tryToRecycleCachedViewAt(i)) { 3798 final ViewHolder holder = mCachedViews.get(i); 3799 holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID); 3800 } 3801 } 3802 } 3803 3804 } 3805 3806 void clearOldPositions() { 3807 final int cachedCount = mCachedViews.size(); 3808 for (int i = 0; i < cachedCount; i++) { 3809 final ViewHolder holder = mCachedViews.get(i); 3810 holder.clearOldPosition(); 3811 } 3812 } 3813 3814 void markItemDecorInsetsDirty() { 3815 final int cachedCount = mCachedViews.size(); 3816 for (int i = 0; i < cachedCount; i++) { 3817 final ViewHolder holder = mCachedViews.get(i); 3818 LayoutParams layoutParams = (LayoutParams) holder.itemView.getLayoutParams(); 3819 if (layoutParams != null) { 3820 layoutParams.mInsetsDirty = true; 3821 } 3822 } 3823 } 3824 } 3825 3826 /** 3827 * ViewCacheExtension is a helper class to provide an additional layer of view caching that can 3828 * ben controlled by the developer. 3829 * <p> 3830 * When {@link Recycler#getViewForPosition(int)} is called, Recycler checks attached scrap and 3831 * first level cache to find a matching View. If it cannot find a suitable View, Recycler will 3832 * call the {@link #getViewForPositionAndType(Recycler, int, int)} before checking 3833 * {@link RecycledViewPool}. 3834 * <p> 3835 * Note that, Recycler never sends Views to this method to be cached. It is developers 3836 * responsibility to decide whether they want to keep their Views in this custom cache or let 3837 * the default recycling policy handle it. 3838 */ 3839 public abstract static class ViewCacheExtension { 3840 3841 /** 3842 * Returns a View that can be binded to the given Adapter position. 3843 * <p> 3844 * This method should <b>not</b> create a new View. Instead, it is expected to return 3845 * an already created View that can be re-used for the given type and position. 3846 * If the View is marked as ignored, it should first call 3847 * {@link LayoutManager#stopIgnoringView(View)} before returning the View. 3848 * <p> 3849 * RecyclerView will re-bind the returned View to the position if necessary. 3850 * 3851 * @param recycler The Recycler that can be used to bind the View 3852 * @param position The adapter position 3853 * @param type The type of the View, defined by adapter 3854 * @return A View that is bound to the given position or NULL if there is no View to re-use 3855 * @see LayoutManager#ignoreView(View) 3856 */ 3857 abstract public View getViewForPositionAndType(Recycler recycler, int position, int type); 3858 } 3859 3860 /** 3861 * Base class for an Adapter 3862 * 3863 * <p>Adapters provide a binding from an app-specific data set to views that are displayed 3864 * within a {@link RecyclerView}.</p> 3865 */ 3866 public static abstract class Adapter<VH extends ViewHolder> { 3867 private final AdapterDataObservable mObservable = new AdapterDataObservable(); 3868 private boolean mHasStableIds = false; 3869 3870 public abstract VH onCreateViewHolder(ViewGroup parent, int viewType); 3871 public abstract void onBindViewHolder(VH holder, int position); 3872 3873 public final VH createViewHolder(ViewGroup parent, int viewType) { 3874 final VH holder = onCreateViewHolder(parent, viewType); 3875 holder.mItemViewType = viewType; 3876 return holder; 3877 } 3878 3879 public final void bindViewHolder(VH holder, int position) { 3880 holder.mPosition = position; 3881 if (hasStableIds()) { 3882 holder.mItemId = getItemId(position); 3883 } 3884 onBindViewHolder(holder, position); 3885 holder.setFlags(ViewHolder.FLAG_BOUND, 3886 ViewHolder.FLAG_BOUND | ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID); 3887 } 3888 3889 /** 3890 * Return the view type of the item at <code>position</code> for the purposes 3891 * of view recycling. 3892 * 3893 * <p>The default implementation of this method returns 0, making the assumption of 3894 * a single view type for the adapter. Unlike ListView adapters, types need not 3895 * be contiguous. Consider using id resources to uniquely identify item view types. 3896 * 3897 * @param position position to query 3898 * @return integer value identifying the type of the view needed to represent the item at 3899 * <code>position</code>. Type codes need not be contiguous. 3900 */ 3901 public int getItemViewType(int position) { 3902 return 0; 3903 } 3904 3905 public void setHasStableIds(boolean hasStableIds) { 3906 if (hasObservers()) { 3907 throw new IllegalStateException("Cannot change whether this adapter has " + 3908 "stable IDs while the adapter has registered observers."); 3909 } 3910 mHasStableIds = hasStableIds; 3911 } 3912 3913 /** 3914 * Return the stable ID for the item at <code>position</code>. If {@link #hasStableIds()} 3915 * would return false this method should return {@link #NO_ID}. The default implementation 3916 * of this method returns {@link #NO_ID}. 3917 * 3918 * @param position Adapter position to query 3919 * @return the stable ID of the item at position 3920 */ 3921 public long getItemId(int position) { 3922 return NO_ID; 3923 } 3924 3925 public abstract int getItemCount(); 3926 3927 /** 3928 * Returns true if this adapter publishes a unique <code>long</code> value that can 3929 * act as a key for the item at a given position in the data set. If that item is relocated 3930 * in the data set, the ID returned for that item should be the same. 3931 * 3932 * @return true if this adapter's items have stable IDs 3933 */ 3934 public final boolean hasStableIds() { 3935 return mHasStableIds; 3936 } 3937 3938 /** 3939 * Called when a view created by this adapter has been recycled. 3940 * 3941 * <p>A view is recycled when a {@link LayoutManager} decides that it no longer 3942 * needs to be attached to its parent {@link RecyclerView}. This can be because it has 3943 * fallen out of visibility or a set of cached views represented by views still 3944 * attached to the parent RecyclerView. If an item view has large or expensive data 3945 * bound to it such as large bitmaps, this may be a good place to release those 3946 * resources.</p> 3947 * 3948 * @param holder The ViewHolder for the view being recycled 3949 */ 3950 public void onViewRecycled(VH holder) { 3951 } 3952 3953 /** 3954 * Called when a view created by this adapter has been attached to a window. 3955 * 3956 * <p>This can be used as a reasonable signal that the view is about to be seen 3957 * by the user. If the adapter previously freed any resources in 3958 * {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow} 3959 * those resources should be restored here.</p> 3960 * 3961 * @param holder Holder of the view being attached 3962 */ 3963 public void onViewAttachedToWindow(VH holder) { 3964 } 3965 3966 /** 3967 * Called when a view created by this adapter has been detached from its window. 3968 * 3969 * <p>Becoming detached from the window is not necessarily a permanent condition; 3970 * the consumer of an Adapter's views may choose to cache views offscreen while they 3971 * are not visible, attaching an detaching them as appropriate.</p> 3972 * 3973 * @param holder Holder of the view being detached 3974 */ 3975 public void onViewDetachedFromWindow(VH holder) { 3976 } 3977 3978 /** 3979 * Returns true if one or more observers are attached to this adapter. 3980 * @return true if this adapter has observers 3981 */ 3982 public final boolean hasObservers() { 3983 return mObservable.hasObservers(); 3984 } 3985 3986 /** 3987 * Register a new observer to listen for data changes. 3988 * 3989 * <p>The adapter may publish a variety of events describing specific changes. 3990 * Not all adapters may support all change types and some may fall back to a generic 3991 * {@link android.support.v7.widget.RecyclerView.AdapterDataObserver#onChanged() 3992 * "something changed"} event if more specific data is not available.</p> 3993 * 3994 * <p>Components registering observers with an adapter are responsible for 3995 * {@link #unregisterAdapterDataObserver(android.support.v7.widget.RecyclerView.AdapterDataObserver) 3996 * unregistering} those observers when finished.</p> 3997 * 3998 * @param observer Observer to register 3999 * 4000 * @see #unregisterAdapterDataObserver(android.support.v7.widget.RecyclerView.AdapterDataObserver) 4001 */ 4002 public void registerAdapterDataObserver(AdapterDataObserver observer) { 4003 mObservable.registerObserver(observer); 4004 } 4005 4006 /** 4007 * Unregister an observer currently listening for data changes. 4008 * 4009 * <p>The unregistered observer will no longer receive events about changes 4010 * to the adapter.</p> 4011 * 4012 * @param observer Observer to unregister 4013 * 4014 * @see #registerAdapterDataObserver(android.support.v7.widget.RecyclerView.AdapterDataObserver) 4015 */ 4016 public void unregisterAdapterDataObserver(AdapterDataObserver observer) { 4017 mObservable.unregisterObserver(observer); 4018 } 4019 4020 /** 4021 * Notify any registered observers that the data set has changed. 4022 * 4023 * <p>There are two different classes of data change events, item changes and structural 4024 * changes. Item changes are when a single item has its data updated but no positional 4025 * changes have occurred. Structural changes are when items are inserted, removed or moved 4026 * within the data set.</p> 4027 * 4028 * <p>This event does not specify what about the data set has changed, forcing 4029 * any observers to assume that all existing items and structure may no longer be valid. 4030 * LayoutManagers will be forced to fully rebind and relayout all visible views.</p> 4031 * 4032 * <p><code>RecyclerView</code> will attempt to synthesize visible structural change events 4033 * for adapters that report that they have {@link #hasStableIds() stable IDs} when 4034 * this method is used. This can help for the purposes of animation and visual 4035 * object persistence but individual item views will still need to be rebound 4036 * and relaid out.</p> 4037 * 4038 * <p>If you are writing an adapter it will always be more efficient to use the more 4039 * specific change events if you can. Rely on <code>notifyDataSetChanged()</code> 4040 * as a last resort.</p> 4041 * 4042 * @see #notifyItemChanged(int) 4043 * @see #notifyItemInserted(int) 4044 * @see #notifyItemRemoved(int) 4045 * @see #notifyItemRangeChanged(int, int) 4046 * @see #notifyItemRangeInserted(int, int) 4047 * @see #notifyItemRangeRemoved(int, int) 4048 */ 4049 public final void notifyDataSetChanged() { 4050 mObservable.notifyChanged(); 4051 } 4052 4053 /** 4054 * Notify any registered observers that the item at <code>position</code> has changed. 4055 * 4056 * <p>This is an item change event, not a structural change event. It indicates that any 4057 * reflection of the data at <code>position</code> is out of date and should be updated. 4058 * The item at <code>position</code> retains the same identity.</p> 4059 * 4060 * @param position Position of the item that has changed 4061 * 4062 * @see #notifyItemRangeChanged(int, int) 4063 */ 4064 public final void notifyItemChanged(int position) { 4065 mObservable.notifyItemRangeChanged(position, 1); 4066 } 4067 4068 /** 4069 * Notify any registered observers that the <code>itemCount</code> items starting at 4070 * position <code>positionStart</code> have changed. 4071 * 4072 * <p>This is an item change event, not a structural change event. It indicates that 4073 * any reflection of the data in the given position range is out of date and should 4074 * be updated. The items in the given range retain the same identity.</p> 4075 * 4076 * @param positionStart Position of the first item that has changed 4077 * @param itemCount Number of items that have changed 4078 * 4079 * @see #notifyItemChanged(int) 4080 */ 4081 public final void notifyItemRangeChanged(int positionStart, int itemCount) { 4082 mObservable.notifyItemRangeChanged(positionStart, itemCount); 4083 } 4084 4085 /** 4086 * Notify any registered observers that the item reflected at <code>position</code> 4087 * has been newly inserted. The item previously at <code>position</code> is now at 4088 * position <code>position + 1</code>. 4089 * 4090 * <p>This is a structural change event. Representations of other existing items in the 4091 * data set are still considered up to date and will not be rebound, though their 4092 * positions may be altered.</p> 4093 * 4094 * @param position Position of the newly inserted item in the data set 4095 * 4096 * @see #notifyItemRangeInserted(int, int) 4097 */ 4098 public final void notifyItemInserted(int position) { 4099 mObservable.notifyItemRangeInserted(position, 1); 4100 } 4101 4102 /** 4103 * Notify any registered observers that the item reflected at <code>fromPosition</code> 4104 * has been moved to <code>toPosition</code>. 4105 * 4106 * <p>This is a structural change event. Representations of other existing items in the 4107 * data set are still considered up to date and will not be rebound, though their 4108 * positions may be altered.</p> 4109 * 4110 * @param fromPosition Previous position of the item. 4111 * @param toPosition New position of the item. 4112 */ 4113 public final void notifyItemMoved(int fromPosition, int toPosition) { 4114 mObservable.notifyItemMoved(fromPosition, toPosition); 4115 } 4116 4117 /** 4118 * Notify any registered observers that the currently reflected <code>itemCount</code> 4119 * items starting at <code>positionStart</code> have been newly inserted. The items 4120 * previously located at <code>positionStart</code> and beyond can now be found starting 4121 * at position <code>positionStart + itemCount</code>. 4122 * 4123 * <p>This is a structural change event. Representations of other existing items in the 4124 * data set are still considered up to date and will not be rebound, though their positions 4125 * may be altered.</p> 4126 * 4127 * @param positionStart Position of the first item that was inserted 4128 * @param itemCount Number of items inserted 4129 * 4130 * @see #notifyItemInserted(int) 4131 */ 4132 public final void notifyItemRangeInserted(int positionStart, int itemCount) { 4133 mObservable.notifyItemRangeInserted(positionStart, itemCount); 4134 } 4135 4136 /** 4137 * Notify any registered observers that the item previously located at <code>position</code> 4138 * has been removed from the data set. The items previously located at and after 4139 * <code>position</code> may now be found at <code>oldPosition - 1</code>. 4140 * 4141 * <p>This is a structural change event. Representations of other existing items in the 4142 * data set are still considered up to date and will not be rebound, though their positions 4143 * may be altered.</p> 4144 * 4145 * @param position Position of the item that has now been removed 4146 * 4147 * @see #notifyItemRangeRemoved(int, int) 4148 */ 4149 public final void notifyItemRemoved(int position) { 4150 mObservable.notifyItemRangeRemoved(position, 1); 4151 } 4152 4153 /** 4154 * Notify any registered observers that the <code>itemCount</code> items previously 4155 * located at <code>positionStart</code> have been removed from the data set. The items 4156 * previously located at and after <code>positionStart + itemCount</code> may now be found 4157 * at <code>oldPosition - itemCount</code>. 4158 * 4159 * <p>This is a structural change event. Representations of other existing items in the data 4160 * set are still considered up to date and will not be rebound, though their positions 4161 * may be altered.</p> 4162 * 4163 * @param positionStart Previous position of the first item that was removed 4164 * @param itemCount Number of items removed from the data set 4165 */ 4166 public final void notifyItemRangeRemoved(int positionStart, int itemCount) { 4167 mObservable.notifyItemRangeRemoved(positionStart, itemCount); 4168 } 4169 } 4170 4171 /** 4172 * A <code>LayoutManager</code> is responsible for measuring and positioning item views 4173 * within a <code>RecyclerView</code> as well as determining the policy for when to recycle 4174 * item views that are no longer visible to the user. By changing the <code>LayoutManager</code> 4175 * a <code>RecyclerView</code> can be used to implement a standard vertically scrolling list, 4176 * a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock 4177 * layout managers are provided for general use. 4178 */ 4179 public static abstract class LayoutManager { 4180 ChildHelper mChildHelper; 4181 RecyclerView mRecyclerView; 4182 4183 @Nullable 4184 SmoothScroller mSmoothScroller; 4185 4186 private boolean mRequestedSimpleAnimations = false; 4187 4188 void setRecyclerView(RecyclerView recyclerView) { 4189 if (recyclerView == null) { 4190 mRecyclerView = null; 4191 mChildHelper = null; 4192 } else { 4193 mRecyclerView = recyclerView; 4194 mChildHelper = recyclerView.mChildHelper; 4195 } 4196 4197 } 4198 4199 /** 4200 * Calls {@code RecyclerView#requestLayout} on the underlying RecyclerView 4201 */ 4202 public void requestLayout() { 4203 if(mRecyclerView != null) { 4204 mRecyclerView.requestLayout(); 4205 } 4206 } 4207 4208 /** 4209 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 4210 * {@link IllegalStateException} if it <b>is not</b>. 4211 * 4212 * @param message The message for the exception. Can be null. 4213 * @see #assertNotInLayoutOrScroll(String) 4214 */ 4215 public void assertInLayoutOrScroll(String message) { 4216 if (mRecyclerView != null) { 4217 mRecyclerView.assertInLayoutOrScroll(message); 4218 } 4219 } 4220 4221 /** 4222 * Checks if RecyclerView is in the middle of a layout or scroll and throws an 4223 * {@link IllegalStateException} if it <b>is</b>. 4224 * 4225 * @param message The message for the exception. Can be null. 4226 * @see #assertInLayoutOrScroll(String) 4227 */ 4228 public void assertNotInLayoutOrScroll(String message) { 4229 if (mRecyclerView != null) { 4230 mRecyclerView.assertNotInLayoutOrScroll(message); 4231 } 4232 } 4233 4234 /** 4235 * Returns whether this LayoutManager supports automatic item animations. 4236 * A LayoutManager wishing to support item animations should obey certain 4237 * rules as outlined in {@link #onLayoutChildren(Recycler, State)}. 4238 * The default return value is <code>false</code>, so subclasses of LayoutManager 4239 * will not get predictive item animations by default. 4240 * 4241 * <p>Whether item animations are enabled in a RecyclerView is determined both 4242 * by the return value from this method and the 4243 * {@link RecyclerView#setItemAnimator(ItemAnimator) ItemAnimator} set on the 4244 * RecyclerView itself. If the RecyclerView has a non-null ItemAnimator but this 4245 * method returns false, then simple item animations will be enabled, in which 4246 * views that are moving onto or off of the screen are simply faded in/out. If 4247 * the RecyclerView has a non-null ItemAnimator and this method returns true, 4248 * then there will be two calls to {@link #onLayoutChildren(Recycler, State)} to 4249 * setup up the information needed to more intelligently predict where appearing 4250 * and disappearing views should be animated from/to.</p> 4251 * 4252 * @return true if predictive item animations should be enabled, false otherwise 4253 */ 4254 public boolean supportsPredictiveItemAnimations() { 4255 return false; 4256 } 4257 4258 /** 4259 * Called when this LayoutManager is both attached to a RecyclerView and that RecyclerView 4260 * is attached to a window. 4261 * 4262 * <p>Subclass implementations should always call through to the superclass implementation. 4263 * </p> 4264 * 4265 * @param view The RecyclerView this LayoutManager is bound to 4266 */ 4267 public void onAttachedToWindow(RecyclerView view) { 4268 } 4269 4270 /** 4271 * @deprecated 4272 * override {@link #onDetachedFromWindow(RecyclerView, Recycler)} 4273 */ 4274 @Deprecated 4275 public void onDetachedFromWindow(RecyclerView view) { 4276 4277 } 4278 4279 /** 4280 * Called when this LayoutManager is detached from its parent RecyclerView or when 4281 * its parent RecyclerView is detached from its window. 4282 * 4283 * <p>Subclass implementations should always call through to the superclass implementation. 4284 * </p> 4285 * 4286 * @param view The RecyclerView this LayoutManager is bound to 4287 * @param recycler The recycler to use if you prefer to recycle your children instead of 4288 * keeping them around. 4289 */ 4290 public void onDetachedFromWindow(RecyclerView view, Recycler recycler) { 4291 onDetachedFromWindow(view); 4292 } 4293 4294 /** 4295 * Check if the RecyclerView is configured to clip child views to its padding. 4296 * 4297 * @return true if this RecyclerView clips children to its padding, false otherwise 4298 */ 4299 public boolean getClipToPadding() { 4300 return mRecyclerView != null && mRecyclerView.mClipToPadding; 4301 } 4302 4303 /** 4304 * Lay out all relevant child views from the given adapter. 4305 * 4306 * The LayoutManager is in charge of the behavior of item animations. By default, 4307 * RecyclerView has a non-null {@link #getItemAnimator() ItemAnimator}, and simple 4308 * item animations are enabled. This means that add/remove operations on the 4309 * adapter will result in animations to add new or appearing items, removed or 4310 * disappearing items, and moved items. If a LayoutManager returns false from 4311 * {@link #supportsPredictiveItemAnimations()}, which is the default, and runs a 4312 * normal layout operation during {@link #onLayoutChildren(Recycler, State)}, the 4313 * RecyclerView will have enough information to run those animations in a simple 4314 * way. For example, the default ItemAnimator, {@link DefaultItemAnimator}, will 4315 * simple fade views in and out, whether they are actuall added/removed or whether 4316 * they are moved on or off the screen due to other add/remove operations. 4317 * 4318 * <p>A LayoutManager wanting a better item animation experience, where items can be 4319 * animated onto and off of the screen according to where the items exist when they 4320 * are not on screen, then the LayoutManager should return true from 4321 * {@link #supportsPredictiveItemAnimations()} and add additional logic to 4322 * {@link #onLayoutChildren(Recycler, State)}. Supporting predictive animations 4323 * means that {@link #onLayoutChildren(Recycler, State)} will be called twice; 4324 * once as a "pre" layout step to determine where items would have been prior to 4325 * a real layout, and again to do the "real" layout. In the pre-layout phase, 4326 * items will remember their pre-layout positions to allow them to be laid out 4327 * appropriately. Also, {@link LayoutParams#isItemRemoved() removed} items will 4328 * be returned from the scrap to help determine correct placement of other items. 4329 * These removed items should not be added to the child list, but should be used 4330 * to help calculate correct positioning of other views, including views that 4331 * were not previously onscreen (referred to as APPEARING views), but whose 4332 * pre-layout offscreen position can be determined given the extra 4333 * information about the pre-layout removed views.</p> 4334 * 4335 * <p>The second layout pass is the real layout in which only non-removed views 4336 * will be used. The only additional requirement during this pass is, if 4337 * {@link #supportsPredictiveItemAnimations()} returns true, to note which 4338 * views exist in the child list prior to layout and which are not there after 4339 * layout (referred to as DISAPPEARING views), and to position/layout those views 4340 * appropriately, without regard to the actual bounds of the RecyclerView. This allows 4341 * the animation system to know the location to which to animate these disappearing 4342 * views.</p> 4343 * 4344 * <p>The default LayoutManager implementations for RecyclerView handle all of these 4345 * requirements for animations already. Clients of RecyclerView can either use one 4346 * of these layout managers directly or look at their implementations of 4347 * onLayoutChildren() to see how they account for the APPEARING and 4348 * DISAPPEARING views.</p> 4349 * 4350 * @param recycler Recycler to use for fetching potentially cached views for a 4351 * position 4352 * @param state Transient state of RecyclerView 4353 */ 4354 public void onLayoutChildren(Recycler recycler, State state) { 4355 Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) "); 4356 } 4357 4358 /** 4359 * Create a default <code>LayoutParams</code> object for a child of the RecyclerView. 4360 * 4361 * <p>LayoutManagers will often want to use a custom <code>LayoutParams</code> type 4362 * to store extra information specific to the layout. Client code should subclass 4363 * {@link RecyclerView.LayoutParams} for this purpose.</p> 4364 * 4365 * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type 4366 * you must also override 4367 * {@link #checkLayoutParams(LayoutParams)}, 4368 * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and 4369 * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p> 4370 * 4371 * @return A new LayoutParams for a child view 4372 */ 4373 public abstract LayoutParams generateDefaultLayoutParams(); 4374 4375 /** 4376 * Determines the validity of the supplied LayoutParams object. 4377 * 4378 * <p>This should check to make sure that the object is of the correct type 4379 * and all values are within acceptable ranges. The default implementation 4380 * returns <code>true</code> for non-null params.</p> 4381 * 4382 * @param lp LayoutParams object to check 4383 * @return true if this LayoutParams object is valid, false otherwise 4384 */ 4385 public boolean checkLayoutParams(LayoutParams lp) { 4386 return lp != null; 4387 } 4388 4389 /** 4390 * Create a LayoutParams object suitable for this LayoutManager, copying relevant 4391 * values from the supplied LayoutParams object if possible. 4392 * 4393 * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type 4394 * you must also override 4395 * {@link #checkLayoutParams(LayoutParams)}, 4396 * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and 4397 * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p> 4398 * 4399 * @param lp Source LayoutParams object to copy values from 4400 * @return a new LayoutParams object 4401 */ 4402 public LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) { 4403 if (lp instanceof LayoutParams) { 4404 return new LayoutParams((LayoutParams) lp); 4405 } else if (lp instanceof MarginLayoutParams) { 4406 return new LayoutParams((MarginLayoutParams) lp); 4407 } else { 4408 return new LayoutParams(lp); 4409 } 4410 } 4411 4412 /** 4413 * Create a LayoutParams object suitable for this LayoutManager from 4414 * an inflated layout resource. 4415 * 4416 * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type 4417 * you must also override 4418 * {@link #checkLayoutParams(LayoutParams)}, 4419 * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and 4420 * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p> 4421 * 4422 * @param c Context for obtaining styled attributes 4423 * @param attrs AttributeSet describing the supplied arguments 4424 * @return a new LayoutParams object 4425 */ 4426 public LayoutParams generateLayoutParams(Context c, AttributeSet attrs) { 4427 return new LayoutParams(c, attrs); 4428 } 4429 4430 /** 4431 * Scroll horizontally by dx pixels in screen coordinates and return the distance traveled. 4432 * The default implementation does nothing and returns 0. 4433 * 4434 * @param dx distance to scroll by in pixels. X increases as scroll position 4435 * approaches the right. 4436 * @param recycler Recycler to use for fetching potentially cached views for a 4437 * position 4438 * @param state Transient state of RecyclerView 4439 * @return The actual distance scrolled. The return value will be negative if dx was 4440 * negative and scrolling proceeeded in that direction. 4441 * <code>Math.abs(result)</code> may be less than dx if a boundary was reached. 4442 */ 4443 public int scrollHorizontallyBy(int dx, Recycler recycler, State state) { 4444 return 0; 4445 } 4446 4447 /** 4448 * Scroll vertically by dy pixels in screen coordinates and return the distance traveled. 4449 * The default implementation does nothing and returns 0. 4450 * 4451 * @param dy distance to scroll in pixels. Y increases as scroll position 4452 * approaches the bottom. 4453 * @param recycler Recycler to use for fetching potentially cached views for a 4454 * position 4455 * @param state Transient state of RecyclerView 4456 * @return The actual distance scrolled. The return value will be negative if dy was 4457 * negative and scrolling proceeeded in that direction. 4458 * <code>Math.abs(result)</code> may be less than dy if a boundary was reached. 4459 */ 4460 public int scrollVerticallyBy(int dy, Recycler recycler, State state) { 4461 return 0; 4462 } 4463 4464 /** 4465 * Query if horizontal scrolling is currently supported. The default implementation 4466 * returns false. 4467 * 4468 * @return True if this LayoutManager can scroll the current contents horizontally 4469 */ 4470 public boolean canScrollHorizontally() { 4471 return false; 4472 } 4473 4474 /** 4475 * Query if vertical scrolling is currently supported. The default implementation 4476 * returns false. 4477 * 4478 * @return True if this LayoutManager can scroll the current contents vertically 4479 */ 4480 public boolean canScrollVertically() { 4481 return false; 4482 } 4483 4484 /** 4485 * Scroll to the specified adapter position. 4486 * 4487 * Actual position of the item on the screen depends on the LayoutManager implementation. 4488 * @param position Scroll to this adapter position. 4489 */ 4490 public void scrollToPosition(int position) { 4491 if (DEBUG) { 4492 Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract"); 4493 } 4494 } 4495 4496 /** 4497 * <p>Smooth scroll to the specified adapter position.</p> 4498 * <p>To support smooth scrolling, override this method, create your {@link SmoothScroller} 4499 * instance and call {@link #startSmoothScroll(SmoothScroller)}. 4500 * </p> 4501 * @param recyclerView The RecyclerView to which this layout manager is attached 4502 * @param state Current State of RecyclerView 4503 * @param position Scroll to this adapter position. 4504 */ 4505 public void smoothScrollToPosition(RecyclerView recyclerView, State state, 4506 int position) { 4507 Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling"); 4508 } 4509 4510 /** 4511 * <p>Starts a smooth scroll using the provided SmoothScroller.</p> 4512 * <p>Calling this method will cancel any previous smooth scroll request.</p> 4513 * @param smoothScroller Unstance which defines how smooth scroll should be animated 4514 */ 4515 public void startSmoothScroll(SmoothScroller smoothScroller) { 4516 if (mSmoothScroller != null && smoothScroller != mSmoothScroller 4517 && mSmoothScroller.isRunning()) { 4518 mSmoothScroller.stop(); 4519 } 4520 mSmoothScroller = smoothScroller; 4521 mSmoothScroller.start(mRecyclerView, this); 4522 } 4523 4524 /** 4525 * @return true if RecycylerView is currently in the state of smooth scrolling. 4526 */ 4527 public boolean isSmoothScrolling() { 4528 return mSmoothScroller != null && mSmoothScroller.isRunning(); 4529 } 4530 4531 4532 /** 4533 * Returns the resolved layout direction for this RecyclerView. 4534 * 4535 * @return {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL} if the layout 4536 * direction is RTL or returns 4537 * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} if the layout direction 4538 * is not RTL. 4539 */ 4540 public int getLayoutDirection() { 4541 return ViewCompat.getLayoutDirection(mRecyclerView); 4542 } 4543 4544 /** 4545 * Ends all animations on the view created by the {@link ItemAnimator}. 4546 * 4547 * @param view The View for which the animations should be ended. 4548 * @see RecyclerView.ItemAnimator#endAnimations() 4549 */ 4550 public void endAnimation(View view) { 4551 if (mRecyclerView.mItemAnimator != null) { 4552 mRecyclerView.mItemAnimator.endAnimation(getChildViewHolderInt(view)); 4553 } 4554 } 4555 4556 /** 4557 * To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view 4558 * to the layout that is known to be going away, either because it has been 4559 * {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the 4560 * visible portion of the container but is being laid out in order to inform RecyclerView 4561 * in how to animate the item out of view. 4562 * <p> 4563 * Views added via this method are going to be invisible to LayoutManager after the 4564 * dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)} 4565 * or won't be included in {@link #getChildCount()} method. 4566 * 4567 * @param child View to add and then remove with animation. 4568 */ 4569 public void addDisappearingView(View child) { 4570 addDisappearingView(child, -1); 4571 } 4572 4573 /** 4574 * To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view 4575 * to the layout that is known to be going away, either because it has been 4576 * {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the 4577 * visible portion of the container but is being laid out in order to inform RecyclerView 4578 * in how to animate the item out of view. 4579 * <p> 4580 * Views added via this method are going to be invisible to LayoutManager after the 4581 * dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)} 4582 * or won't be included in {@link #getChildCount()} method. 4583 * 4584 * @param child View to add and then remove with animation. 4585 * @param index Index of the view. 4586 */ 4587 public void addDisappearingView(View child, int index) { 4588 addViewInt(child, index, true); 4589 } 4590 4591 /** 4592 * Add a view to the currently attached RecyclerView if needed. LayoutManagers should 4593 * use this method to add views obtained from a {@link Recycler} using 4594 * {@link Recycler#getViewForPosition(int)}. 4595 * 4596 * @param child View to add 4597 */ 4598 public void addView(View child) { 4599 addView(child, -1); 4600 } 4601 4602 /** 4603 * Add a view to the currently attached RecyclerView if needed. LayoutManagers should 4604 * use this method to add views obtained from a {@link Recycler} using 4605 * {@link Recycler#getViewForPosition(int)}. 4606 * 4607 * @param child View to add 4608 * @param index Index to add child at 4609 */ 4610 public void addView(View child, int index) { 4611 addViewInt(child, index, false); 4612 } 4613 4614 private void addViewInt(View child, int index, boolean disappearing) { 4615 final ViewHolder holder = getChildViewHolderInt(child); 4616 if (disappearing || holder.isRemoved()) { 4617 // these views will be hidden at the end of the layout pass. 4618 mRecyclerView.mDisappearingViewsInLayoutPass.add(child); 4619 } else { 4620 // This may look like unnecessary but may happen if layout manager supports 4621 // predictive layouts and adapter removed then re-added the same item. 4622 // In this case, added version will be visible in the post layout (because add is 4623 // deferred) but RV will still bind it to the same View. 4624 // So if a View re-appears in post layout pass, remove it from disappearing list. 4625 mRecyclerView.mDisappearingViewsInLayoutPass.remove(child); 4626 } 4627 4628 if (holder.wasReturnedFromScrap() || holder.isScrap()) { 4629 if (holder.isScrap()) { 4630 holder.unScrap(); 4631 } else { 4632 holder.clearReturnedFromScrapFlag(); 4633 } 4634 mChildHelper.attachViewToParent(child, index, child.getLayoutParams(), false); 4635 if (DISPATCH_TEMP_DETACH) { 4636 ViewCompat.dispatchFinishTemporaryDetach(child); 4637 } 4638 } else if (child.getParent() == mRecyclerView) { // it was not a scrap but a valid child 4639 // ensure in correct position 4640 int currentIndex = mChildHelper.indexOfChild(child); 4641 if (index == -1) { 4642 index = mChildHelper.getChildCount(); 4643 } 4644 if (currentIndex == -1) { 4645 throw new IllegalStateException("Added View has RecyclerView as parent but" 4646 + " view is not a real child. Unfiltered index:" 4647 + mRecyclerView.indexOfChild(child)); 4648 } 4649 if (currentIndex != index) { 4650 mRecyclerView.mLayout.moveView(currentIndex, index); 4651 } 4652 } else { 4653 mChildHelper.addView(child, index, false); 4654 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 4655 lp.mInsetsDirty = true; 4656 final Adapter adapter = mRecyclerView.getAdapter(); 4657 if (adapter != null) { 4658 adapter.onViewAttachedToWindow(getChildViewHolderInt(child)); 4659 } 4660 mRecyclerView.onChildAttachedToWindow(child); 4661 if (mSmoothScroller != null && mSmoothScroller.isRunning()) { 4662 mSmoothScroller.onChildAttachedToWindow(child); 4663 } 4664 } 4665 } 4666 4667 /** 4668 * Remove a view from the currently attached RecyclerView if needed. LayoutManagers should 4669 * use this method to completely remove a child view that is no longer needed. 4670 * LayoutManagers should strongly consider recycling removed views using 4671 * {@link Recycler#recycleView(android.view.View)}. 4672 * 4673 * @param child View to remove 4674 */ 4675 public void removeView(View child) { 4676 final Adapter adapter = mRecyclerView.getAdapter(); 4677 if (adapter != null) { 4678 adapter.onViewDetachedFromWindow(getChildViewHolderInt(child)); 4679 } 4680 mRecyclerView.onChildDetachedFromWindow(child); 4681 mChildHelper.removeView(child); 4682 } 4683 4684 /** 4685 * Remove a view from the currently attached RecyclerView if needed. LayoutManagers should 4686 * use this method to completely remove a child view that is no longer needed. 4687 * LayoutManagers should strongly consider recycling removed views using 4688 * {@link Recycler#recycleView(android.view.View)}. 4689 * 4690 * @param index Index of the child view to remove 4691 */ 4692 public void removeViewAt(int index) { 4693 final View child = getChildAt(index); 4694 if (child != null) { 4695 final Adapter adapter = mRecyclerView.getAdapter(); 4696 if (adapter != null) { 4697 adapter.onViewDetachedFromWindow(getChildViewHolderInt(child)); 4698 } 4699 mRecyclerView.onChildDetachedFromWindow(child); 4700 mChildHelper.removeViewAt(index); 4701 } 4702 } 4703 4704 /** 4705 * Remove all views from the currently attached RecyclerView. This will not recycle 4706 * any of the affected views; the LayoutManager is responsible for doing so if desired. 4707 */ 4708 public void removeAllViews() { 4709 final Adapter adapter = mRecyclerView.getAdapter(); 4710 // Only remove non-animating views 4711 final int childCount = getChildCount(); 4712 4713 for (int i = 0; i < childCount; i++) { 4714 final View child = getChildAt(i); 4715 if (adapter != null) { 4716 adapter.onViewDetachedFromWindow(getChildViewHolderInt(child)); 4717 } 4718 mRecyclerView.onChildDetachedFromWindow(child); 4719 } 4720 4721 for (int i = childCount - 1; i >= 0; i--) { 4722 mChildHelper.removeViewAt(i); 4723 } 4724 } 4725 4726 /** 4727 * Returns the adapter position of the item represented by the given View. 4728 * 4729 * @param view The view to query 4730 * @return The adapter position of the item which is rendered by this View. 4731 */ 4732 public int getPosition(View view) { 4733 return ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewPosition(); 4734 } 4735 4736 /** 4737 * Returns the View type defined by the adapter. 4738 * 4739 * @param view The view to query 4740 * @return The type of the view assigned by the adapter. 4741 */ 4742 public int getItemViewType(View view) { 4743 return getChildViewHolderInt(view).getItemViewType(); 4744 } 4745 4746 /** 4747 * <p>Finds the view which represents the given adapter position.</p> 4748 * <p>This method traverses each child since it has no information about child order. 4749 * Override this method to improve performance if your LayoutManager keeps data about 4750 * child views.</p> 4751 * 4752 * @param position Position of the item in adapter 4753 * @return The child view that represents the given position or null if the position is not 4754 * visible 4755 */ 4756 public View findViewByPosition(int position) { 4757 final int childCount = getChildCount(); 4758 for (int i = 0; i < childCount; i++) { 4759 View child = getChildAt(i); 4760 ViewHolder vh = getChildViewHolderInt(child); 4761 if (vh == null) { 4762 continue; 4763 } 4764 if (vh.getPosition() == position && 4765 (mRecyclerView.mState.isPreLayout() || !vh.isRemoved())) { 4766 return child; 4767 } 4768 } 4769 return null; 4770 } 4771 4772 /** 4773 * Temporarily detach a child view. 4774 * 4775 * <p>LayoutManagers may want to perform a lightweight detach operation to rearrange 4776 * views currently attached to the RecyclerView. Generally LayoutManager implementations 4777 * will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} 4778 * so that the detached view may be rebound and reused.</p> 4779 * 4780 * <p>If a LayoutManager uses this method to detach a view, it <em>must</em> 4781 * {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach} 4782 * or {@link #removeDetachedView(android.view.View) fully remove} the detached view 4783 * before the LayoutManager entry point method called by RecyclerView returns.</p> 4784 * 4785 * @param child Child to detach 4786 */ 4787 public void detachView(View child) { 4788 if (DISPATCH_TEMP_DETACH) { 4789 ViewCompat.dispatchStartTemporaryDetach(child); 4790 } 4791 mRecyclerView.detachViewFromParent(child); 4792 } 4793 4794 /** 4795 * Temporarily detach a child view. 4796 * 4797 * <p>LayoutManagers may want to perform a lightweight detach operation to rearrange 4798 * views currently attached to the RecyclerView. Generally LayoutManager implementations 4799 * will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} 4800 * so that the detached view may be rebound and reused.</p> 4801 * 4802 * <p>If a LayoutManager uses this method to detach a view, it <em>must</em> 4803 * {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach} 4804 * or {@link #removeDetachedView(android.view.View) fully remove} the detached view 4805 * before the LayoutManager entry point method called by RecyclerView returns.</p> 4806 * 4807 * @param index Index of the child to detach 4808 */ 4809 public void detachViewAt(int index) { 4810 if (DISPATCH_TEMP_DETACH) { 4811 ViewCompat.dispatchStartTemporaryDetach(getChildAt(index)); 4812 } 4813 mChildHelper.detachViewFromParent(index); 4814 } 4815 4816 /** 4817 * Reattach a previously {@link #detachView(android.view.View) detached} view. 4818 * This method should not be used to reattach views that were previously 4819 * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}. 4820 * 4821 * @param child Child to reattach 4822 * @param index Intended child index for child 4823 * @param lp LayoutParams for child 4824 */ 4825 public void attachView(View child, int index, LayoutParams lp) { 4826 ViewHolder vh = getChildViewHolderInt(child); 4827 if (vh.isRemoved()) { 4828 mRecyclerView.mDisappearingViewsInLayoutPass.add(child); 4829 } else { 4830 mRecyclerView.mDisappearingViewsInLayoutPass.remove(child); 4831 } 4832 mChildHelper.attachViewToParent(child, index, lp, vh.isRemoved()); 4833 if (DISPATCH_TEMP_DETACH) { 4834 ViewCompat.dispatchFinishTemporaryDetach(child); 4835 } 4836 } 4837 4838 /** 4839 * Reattach a previously {@link #detachView(android.view.View) detached} view. 4840 * This method should not be used to reattach views that were previously 4841 * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}. 4842 * 4843 * @param child Child to reattach 4844 * @param index Intended child index for child 4845 */ 4846 public void attachView(View child, int index) { 4847 attachView(child, index, (LayoutParams) child.getLayoutParams()); 4848 } 4849 4850 /** 4851 * Reattach a previously {@link #detachView(android.view.View) detached} view. 4852 * This method should not be used to reattach views that were previously 4853 * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)} scrapped}. 4854 * 4855 * @param child Child to reattach 4856 */ 4857 public void attachView(View child) { 4858 attachView(child, -1); 4859 } 4860 4861 /** 4862 * Finish removing a view that was previously temporarily 4863 * {@link #detachView(android.view.View) detached}. 4864 * 4865 * @param child Detached child to remove 4866 */ 4867 public void removeDetachedView(View child) { 4868 mRecyclerView.removeDetachedView(child, false); 4869 } 4870 4871 /** 4872 * Moves a View from one position to another. 4873 * 4874 * @param fromIndex The View's initial index 4875 * @param toIndex The View's target index 4876 */ 4877 public void moveView(int fromIndex, int toIndex) { 4878 View view = getChildAt(fromIndex); 4879 if (view == null) { 4880 throw new IllegalArgumentException("Cannot move a child from non-existing index:" 4881 + fromIndex); 4882 } 4883 detachViewAt(fromIndex); 4884 attachView(view, toIndex); 4885 } 4886 4887 /** 4888 * Detach a child view and add it to a {@link Recycler Recycler's} scrap heap. 4889 * 4890 * <p>Scrapping a view allows it to be rebound and reused to show updated or 4891 * different data.</p> 4892 * 4893 * @param child Child to detach and scrap 4894 * @param recycler Recycler to deposit the new scrap view into 4895 */ 4896 public void detachAndScrapView(View child, Recycler recycler) { 4897 int index = mChildHelper.indexOfChild(child); 4898 scrapOrRecycleView(recycler, index, child); 4899 } 4900 4901 /** 4902 * Detach a child view and add it to a {@link Recycler Recycler's} scrap heap. 4903 * 4904 * <p>Scrapping a view allows it to be rebound and reused to show updated or 4905 * different data.</p> 4906 * 4907 * @param index Index of child to detach and scrap 4908 * @param recycler Recycler to deposit the new scrap view into 4909 */ 4910 public void detachAndScrapViewAt(int index, Recycler recycler) { 4911 final View child = getChildAt(index); 4912 scrapOrRecycleView(recycler, index, child); 4913 } 4914 4915 /** 4916 * Remove a child view and recycle it using the given Recycler. 4917 * 4918 * @param child Child to remove and recycle 4919 * @param recycler Recycler to use to recycle child 4920 */ 4921 public void removeAndRecycleView(View child, Recycler recycler) { 4922 removeView(child); 4923 recycler.recycleView(child); 4924 } 4925 4926 /** 4927 * Remove a child view and recycle it using the given Recycler. 4928 * 4929 * @param index Index of child to remove and recycle 4930 * @param recycler Recycler to use to recycle child 4931 */ 4932 public void removeAndRecycleViewAt(int index, Recycler recycler) { 4933 final View view = getChildAt(index); 4934 removeViewAt(index); 4935 recycler.recycleView(view); 4936 } 4937 4938 /** 4939 * Return the current number of child views attached to the parent RecyclerView. 4940 * This does not include child views that were temporarily detached and/or scrapped. 4941 * 4942 * @return Number of attached children 4943 */ 4944 public int getChildCount() { 4945 return mChildHelper != null ? mChildHelper.getChildCount() : 0; 4946 } 4947 4948 /** 4949 * Return the child view at the given index 4950 * @param index Index of child to return 4951 * @return Child view at index 4952 */ 4953 public View getChildAt(int index) { 4954 return mChildHelper != null ? mChildHelper.getChildAt(index) : null; 4955 } 4956 4957 /** 4958 * Return the width of the parent RecyclerView 4959 * 4960 * @return Width in pixels 4961 */ 4962 public int getWidth() { 4963 return mRecyclerView != null ? mRecyclerView.getWidth() : 0; 4964 } 4965 4966 /** 4967 * Return the height of the parent RecyclerView 4968 * 4969 * @return Height in pixels 4970 */ 4971 public int getHeight() { 4972 return mRecyclerView != null ? mRecyclerView.getHeight() : 0; 4973 } 4974 4975 /** 4976 * Return the left padding of the parent RecyclerView 4977 * 4978 * @return Padding in pixels 4979 */ 4980 public int getPaddingLeft() { 4981 return mRecyclerView != null ? mRecyclerView.getPaddingLeft() : 0; 4982 } 4983 4984 /** 4985 * Return the top padding of the parent RecyclerView 4986 * 4987 * @return Padding in pixels 4988 */ 4989 public int getPaddingTop() { 4990 return mRecyclerView != null ? mRecyclerView.getPaddingTop() : 0; 4991 } 4992 4993 /** 4994 * Return the right padding of the parent RecyclerView 4995 * 4996 * @return Padding in pixels 4997 */ 4998 public int getPaddingRight() { 4999 return mRecyclerView != null ? mRecyclerView.getPaddingRight() : 0; 5000 } 5001 5002 /** 5003 * Return the bottom padding of the parent RecyclerView 5004 * 5005 * @return Padding in pixels 5006 */ 5007 public int getPaddingBottom() { 5008 return mRecyclerView != null ? mRecyclerView.getPaddingBottom() : 0; 5009 } 5010 5011 /** 5012 * Return the start padding of the parent RecyclerView 5013 * 5014 * @return Padding in pixels 5015 */ 5016 public int getPaddingStart() { 5017 return mRecyclerView != null ? ViewCompat.getPaddingStart(mRecyclerView) : 0; 5018 } 5019 5020 /** 5021 * Return the end padding of the parent RecyclerView 5022 * 5023 * @return Padding in pixels 5024 */ 5025 public int getPaddingEnd() { 5026 return mRecyclerView != null ? ViewCompat.getPaddingEnd(mRecyclerView) : 0; 5027 } 5028 5029 /** 5030 * Returns true if the RecyclerView this LayoutManager is bound to has focus. 5031 * 5032 * @return True if the RecyclerView has focus, false otherwise. 5033 * @see View#isFocused() 5034 */ 5035 public boolean isFocused() { 5036 return mRecyclerView != null && mRecyclerView.isFocused(); 5037 } 5038 5039 /** 5040 * Returns true if the RecyclerView this LayoutManager is bound to has or contains focus. 5041 * 5042 * @return true if the RecyclerView has or contains focus 5043 * @see View#hasFocus() 5044 */ 5045 public boolean hasFocus() { 5046 return mRecyclerView != null && mRecyclerView.hasFocus(); 5047 } 5048 5049 /** 5050 * Returns the item View which has or contains focus. 5051 * 5052 * @return A direct child of RecyclerView which has focus or contains the focused child. 5053 */ 5054 public View findItemWhichHasFocus() { 5055 if (mRecyclerView == null) { 5056 return null; 5057 } 5058 View focused = mRecyclerView.findFocus(); 5059 if (focused != null && focused.getParent() == mRecyclerView) { 5060 return focused; 5061 } 5062 return null; 5063 } 5064 5065 /** 5066 * Returns the number of items in the adapter bound to the parent RecyclerView. 5067 * <p> 5068 * Note that this number is not necessarily equal to {@link State#getItemCount()}. In 5069 * methods where State is available, you should use {@link State#getItemCount()} instead. 5070 * For more details, check the documentation for {@link State#getItemCount()}. 5071 * 5072 * @return The number of items in the bound adapter 5073 * @see State#getItemCount() 5074 */ 5075 public int getItemCount() { 5076 final Adapter a = mRecyclerView != null ? mRecyclerView.getAdapter() : null; 5077 return a != null ? a.getItemCount() : 0; 5078 } 5079 5080 /** 5081 * Offset all child views attached to the parent RecyclerView by dx pixels along 5082 * the horizontal axis. 5083 * 5084 * @param dx Pixels to offset by 5085 */ 5086 public void offsetChildrenHorizontal(int dx) { 5087 if (mRecyclerView != null) { 5088 mRecyclerView.offsetChildrenHorizontal(dx); 5089 } 5090 } 5091 5092 /** 5093 * Offset all child views attached to the parent RecyclerView by dy pixels along 5094 * the vertical axis. 5095 * 5096 * @param dy Pixels to offset by 5097 */ 5098 public void offsetChildrenVertical(int dy) { 5099 if (mRecyclerView != null) { 5100 mRecyclerView.offsetChildrenVertical(dy); 5101 } 5102 } 5103 5104 /** 5105 * Flags a view so that it will not be scrapped or recycled. 5106 * <p> 5107 * Scope of ignoring a child is strictly restricted to scrapping and recyling. Methods like 5108 * {@link #removeAndRecycleAllViews(Recycler)} will ignore the child whereas 5109 * {@link #removeAllViews()} or {@link #offsetChildrenHorizontal(int)} will not ignore the 5110 * child. 5111 * <p> 5112 * Before this child can be recycled again, you have to call 5113 * {@link #stopIgnoringView(View)}. 5114 * 5115 * @param view View to ignore. 5116 * @see #stopIgnoringView(View) 5117 */ 5118 public void ignoreView(View view) { 5119 if (view.getParent() != mRecyclerView || mRecyclerView.indexOfChild(view) == -1) { 5120 // checking this because calling this method on a recycled or detached view may 5121 // cause loss of state. 5122 throw new IllegalArgumentException("View should be fully attached to be ignored"); 5123 } 5124 final ViewHolder vh = getChildViewHolderInt(view); 5125 vh.addFlags(ViewHolder.FLAG_IGNORE); 5126 mRecyclerView.mState.onViewIgnored(vh); 5127 } 5128 5129 /** 5130 * View can be scrapped and recycled again. 5131 * <p> 5132 * Note that calling this method removes all information in the view holder. 5133 * 5134 * @param view View to ignore. 5135 */ 5136 public void stopIgnoringView(View view) { 5137 final ViewHolder vh = getChildViewHolderInt(view); 5138 vh.stopIgnoring(); 5139 vh.resetInternal(); 5140 vh.addFlags(ViewHolder.FLAG_INVALID); 5141 } 5142 5143 /** 5144 * Temporarily detach and scrap all currently attached child views. Views will be scrapped 5145 * into the given Recycler. The Recycler may prefer to reuse scrap views before 5146 * other views that were previously recycled. 5147 * 5148 * @param recycler Recycler to scrap views into 5149 */ 5150 public void detachAndScrapAttachedViews(Recycler recycler) { 5151 final int childCount = getChildCount(); 5152 for (int i = childCount - 1; i >= 0; i--) { 5153 final View v = getChildAt(i); 5154 scrapOrRecycleView(recycler, i, v); 5155 } 5156 } 5157 5158 private void scrapOrRecycleView(Recycler recycler, int index, View view) { 5159 final ViewHolder viewHolder = getChildViewHolderInt(view); 5160 if (viewHolder.shouldIgnore()) { 5161 if (DEBUG) { 5162 Log.d(TAG, "ignoring view " + viewHolder); 5163 } 5164 return; 5165 } 5166 if (viewHolder.isInvalid() && !viewHolder.isRemoved() && !viewHolder.isChanged() && 5167 !mRecyclerView.mAdapter.hasStableIds()) { 5168 removeViewAt(index); 5169 recycler.recycleViewHolderInternal(viewHolder); 5170 } else { 5171 detachViewAt(index); 5172 recycler.scrapView(view); 5173 } 5174 } 5175 5176 /** 5177 * Recycles the scrapped views. 5178 * <p> 5179 * When a view is detached and removed, it does not trigger a ViewGroup invalidate. This is 5180 * the expected behavior if scrapped views are used for animations. Otherwise, we need to 5181 * call remove and invalidate RecyclerView to ensure UI update. 5182 * 5183 * @param recycler Recycler 5184 * @param remove Whether scrapped views should be removed from ViewGroup or not. This 5185 * method will invalidate RecyclerView if it removes any scrapped child. 5186 */ 5187 void removeAndRecycleScrapInt(Recycler recycler, boolean remove) { 5188 final int scrapCount = recycler.getScrapCount(); 5189 for (int i = 0; i < scrapCount; i++) { 5190 final View scrap = recycler.getScrapViewAt(i); 5191 if (getChildViewHolderInt(scrap).shouldIgnore()) { 5192 continue; 5193 } 5194 if (remove) { 5195 mRecyclerView.removeDetachedView(scrap, false); 5196 } 5197 recycler.quickRecycleScrapView(scrap); 5198 } 5199 recycler.clearScrap(); 5200 if (remove && scrapCount > 0) { 5201 mRecyclerView.invalidate(); 5202 } 5203 } 5204 5205 5206 /** 5207 * Measure a child view using standard measurement policy, taking the padding 5208 * of the parent RecyclerView and any added item decorations into account. 5209 * 5210 * <p>If the RecyclerView can be scrolled in either dimension the caller may 5211 * pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p> 5212 * 5213 * @param child Child view to measure 5214 * @param widthUsed Width in pixels currently consumed by other views, if relevant 5215 * @param heightUsed Height in pixels currently consumed by other views, if relevant 5216 */ 5217 public void measureChild(View child, int widthUsed, int heightUsed) { 5218 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 5219 5220 final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child); 5221 widthUsed += insets.left + insets.right; 5222 heightUsed += insets.top + insets.bottom; 5223 5224 final int widthSpec = getChildMeasureSpec(getWidth(), 5225 getPaddingLeft() + getPaddingRight() + widthUsed, lp.width, 5226 canScrollHorizontally()); 5227 final int heightSpec = getChildMeasureSpec(getHeight(), 5228 getPaddingTop() + getPaddingBottom() + heightUsed, lp.height, 5229 canScrollVertically()); 5230 child.measure(widthSpec, heightSpec); 5231 } 5232 5233 /** 5234 * Measure a child view using standard measurement policy, taking the padding 5235 * of the parent RecyclerView, any added item decorations and the child margins 5236 * into account. 5237 * 5238 * <p>If the RecyclerView can be scrolled in either dimension the caller may 5239 * pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p> 5240 * 5241 * @param child Child view to measure 5242 * @param widthUsed Width in pixels currently consumed by other views, if relevant 5243 * @param heightUsed Height in pixels currently consumed by other views, if relevant 5244 */ 5245 public void measureChildWithMargins(View child, int widthUsed, int heightUsed) { 5246 final LayoutParams lp = (LayoutParams) child.getLayoutParams(); 5247 5248 final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child); 5249 widthUsed += insets.left + insets.right; 5250 heightUsed += insets.top + insets.bottom; 5251 5252 final int widthSpec = getChildMeasureSpec(getWidth(), 5253 getPaddingLeft() + getPaddingRight() + 5254 lp.leftMargin + lp.rightMargin + widthUsed, lp.width, 5255 canScrollHorizontally()); 5256 final int heightSpec = getChildMeasureSpec(getHeight(), 5257 getPaddingTop() + getPaddingBottom() + 5258 lp.topMargin + lp.bottomMargin + heightUsed, lp.height, 5259 canScrollVertically()); 5260 child.measure(widthSpec, heightSpec); 5261 } 5262 5263 /** 5264 * Calculate a MeasureSpec value for measuring a child view in one dimension. 5265 * 5266 * @param parentSize Size of the parent view where the child will be placed 5267 * @param padding Total space currently consumed by other elements of parent 5268 * @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT. 5269 * Generally obtained from the child view's LayoutParams 5270 * @param canScroll true if the parent RecyclerView can scroll in this dimension 5271 * 5272 * @return a MeasureSpec value for the child view 5273 */ 5274 public static int getChildMeasureSpec(int parentSize, int padding, int childDimension, 5275 boolean canScroll) { 5276 int size = Math.max(0, parentSize - padding); 5277 int resultSize = 0; 5278 int resultMode = 0; 5279 5280 if (canScroll) { 5281 if (childDimension >= 0) { 5282 resultSize = childDimension; 5283 resultMode = MeasureSpec.EXACTLY; 5284 } else { 5285 // MATCH_PARENT can't be applied since we can scroll in this dimension, wrap 5286 // instead using UNSPECIFIED. 5287 resultSize = 0; 5288 resultMode = MeasureSpec.UNSPECIFIED; 5289 } 5290 } else { 5291 if (childDimension >= 0) { 5292 resultSize = childDimension; 5293 resultMode = MeasureSpec.EXACTLY; 5294 } else if (childDimension == LayoutParams.FILL_PARENT) { 5295 resultSize = size; 5296 resultMode = MeasureSpec.EXACTLY; 5297 } else if (childDimension == LayoutParams.WRAP_CONTENT) { 5298 resultSize = size; 5299 resultMode = MeasureSpec.AT_MOST; 5300 } 5301 } 5302 return MeasureSpec.makeMeasureSpec(resultSize, resultMode); 5303 } 5304 5305 /** 5306 * Returns the measured width of the given child, plus the additional size of 5307 * any insets applied by {@link ItemDecoration ItemDecorations}. 5308 * 5309 * @param child Child view to query 5310 * @return child's measured width plus <code>ItemDecoration</code> insets 5311 * 5312 * @see View#getMeasuredWidth() 5313 */ 5314 public int getDecoratedMeasuredWidth(View child) { 5315 final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets; 5316 return child.getMeasuredWidth() + insets.left + insets.right; 5317 } 5318 5319 /** 5320 * Returns the measured height of the given child, plus the additional size of 5321 * any insets applied by {@link ItemDecoration ItemDecorations}. 5322 * 5323 * @param child Child view to query 5324 * @return child's measured height plus <code>ItemDecoration</code> insets 5325 * 5326 * @see View#getMeasuredHeight() 5327 */ 5328 public int getDecoratedMeasuredHeight(View child) { 5329 final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets; 5330 return child.getMeasuredHeight() + insets.top + insets.bottom; 5331 } 5332 5333 /** 5334 * Lay out the given child view within the RecyclerView using coordinates that 5335 * include any current {@link ItemDecoration ItemDecorations}. 5336 * 5337 * <p>LayoutManagers should prefer working in sizes and coordinates that include 5338 * item decoration insets whenever possible. This allows the LayoutManager to effectively 5339 * ignore decoration insets within measurement and layout code. See the following 5340 * methods:</p> 5341 * <ul> 5342 * <li>{@link #measureChild(View, int, int)}</li> 5343 * <li>{@link #measureChildWithMargins(View, int, int)}</li> 5344 * <li>{@link #getDecoratedLeft(View)}</li> 5345 * <li>{@link #getDecoratedTop(View)}</li> 5346 * <li>{@link #getDecoratedRight(View)}</li> 5347 * <li>{@link #getDecoratedBottom(View)}</li> 5348 * <li>{@link #getDecoratedMeasuredWidth(View)}</li> 5349 * <li>{@link #getDecoratedMeasuredHeight(View)}</li> 5350 * </ul> 5351 * 5352 * @param child Child to lay out 5353 * @param left Left edge, with item decoration insets included 5354 * @param top Top edge, with item decoration insets included 5355 * @param right Right edge, with item decoration insets included 5356 * @param bottom Bottom edge, with item decoration insets included 5357 * 5358 * @see View#layout(int, int, int, int) 5359 */ 5360 public void layoutDecorated(View child, int left, int top, int right, int bottom) { 5361 final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets; 5362 child.layout(left + insets.left, top + insets.top, right - insets.right, 5363 bottom - insets.bottom); 5364 } 5365 5366 /** 5367 * Returns the left edge of the given child view within its parent, offset by any applied 5368 * {@link ItemDecoration ItemDecorations}. 5369 * 5370 * @param child Child to query 5371 * @return Child left edge with offsets applied 5372 * @see #getLeftDecorationWidth(View) 5373 */ 5374 public int getDecoratedLeft(View child) { 5375 return child.getLeft() - getLeftDecorationWidth(child); 5376 } 5377 5378 /** 5379 * Returns the top edge of the given child view within its parent, offset by any applied 5380 * {@link ItemDecoration ItemDecorations}. 5381 * 5382 * @param child Child to query 5383 * @return Child top edge with offsets applied 5384 * @see #getTopDecorationHeight(View) 5385 */ 5386 public int getDecoratedTop(View child) { 5387 return child.getTop() - getTopDecorationHeight(child); 5388 } 5389 5390 /** 5391 * Returns the right edge of the given child view within its parent, offset by any applied 5392 * {@link ItemDecoration ItemDecorations}. 5393 * 5394 * @param child Child to query 5395 * @return Child right edge with offsets applied 5396 * @see #getRightDecorationWidth(View) 5397 */ 5398 public int getDecoratedRight(View child) { 5399 return child.getRight() + getRightDecorationWidth(child); 5400 } 5401 5402 /** 5403 * Returns the bottom edge of the given child view within its parent, offset by any applied 5404 * {@link ItemDecoration ItemDecorations}. 5405 * 5406 * @param child Child to query 5407 * @return Child bottom edge with offsets applied 5408 * @see #getBottomDecorationHeight(View) 5409 */ 5410 public int getDecoratedBottom(View child) { 5411 return child.getBottom() + getBottomDecorationHeight(child); 5412 } 5413 5414 /** 5415 * Returns the total height of item decorations applied to child's top. 5416 * <p> 5417 * Note that this value is not updated until the View is measured. 5418 * 5419 * @param child Child to query 5420 * @return The total height of item decorations applied to the child's top. 5421 * @see #getDecoratedTop(View) 5422 */ 5423 public int getTopDecorationHeight(View child) { 5424 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.top; 5425 } 5426 5427 /** 5428 * Returns the total height of item decorations applied to child's bottom. 5429 * <p> 5430 * Note that this value is not updated until the View is measured. 5431 * 5432 * @param child Child to query 5433 * @return The total height of item decorations applied to the child's bottom. 5434 * @see #getDecoratedBottom(View) 5435 */ 5436 public int getBottomDecorationHeight(View child) { 5437 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.bottom; 5438 } 5439 5440 /** 5441 * Returns the total width of item decorations applied to child's left. 5442 * <p> 5443 * Note that this value is not updated until the View is measured. 5444 * 5445 * @param child Child to query 5446 * @return The total width of item decorations applied to the child's left. 5447 * @see #getDecoratedLeft(View) 5448 */ 5449 public int getLeftDecorationWidth(View child) { 5450 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.left; 5451 } 5452 5453 /** 5454 * Returns the total width of item decorations applied to child's right. 5455 * <p> 5456 * Note that this value is not updated until the View is measured. 5457 * 5458 * @param child Child to query 5459 * @return The total width of item decorations applied to the child's right. 5460 * @see #getDecoratedRight(View) 5461 */ 5462 public int getRightDecorationWidth(View child) { 5463 return ((LayoutParams) child.getLayoutParams()).mDecorInsets.right; 5464 } 5465 5466 /** 5467 * Called when searching for a focusable view in the given direction has failed 5468 * for the current content of the RecyclerView. 5469 * 5470 * <p>This is the LayoutManager's opportunity to populate views in the given direction 5471 * to fulfill the request if it can. The LayoutManager should attach and return 5472 * the view to be focused. The default implementation returns null.</p> 5473 * 5474 * @param focused The currently focused view 5475 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5476 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, 5477 * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} 5478 * or 0 for not applicable 5479 * @param recycler The recycler to use for obtaining views for currently offscreen items 5480 * @param state Transient state of RecyclerView 5481 * @return The chosen view to be focused 5482 */ 5483 public View onFocusSearchFailed(View focused, int direction, Recycler recycler, 5484 State state) { 5485 return null; 5486 } 5487 5488 /** 5489 * This method gives a LayoutManager an opportunity to intercept the initial focus search 5490 * before the default behavior of {@link FocusFinder} is used. If this method returns 5491 * null FocusFinder will attempt to find a focusable child view. If it fails 5492 * then {@link #onFocusSearchFailed(View, int, RecyclerView.Recycler, RecyclerView.State)} 5493 * will be called to give the LayoutManager an opportunity to add new views for items 5494 * that did not have attached views representing them. The LayoutManager should not add 5495 * or remove views from this method. 5496 * 5497 * @param focused The currently focused view 5498 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5499 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, 5500 * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} 5501 * @return A descendant view to focus or null to fall back to default behavior. 5502 * The default implementation returns null. 5503 */ 5504 public View onInterceptFocusSearch(View focused, int direction) { 5505 return null; 5506 } 5507 5508 /** 5509 * Called when a child of the RecyclerView wants a particular rectangle to be positioned 5510 * onto the screen. See {@link ViewParent#requestChildRectangleOnScreen(android.view.View, 5511 * android.graphics.Rect, boolean)} for more details. 5512 * 5513 * <p>The base implementation will attempt to perform a standard programmatic scroll 5514 * to bring the given rect into view, within the padded area of the RecyclerView.</p> 5515 * 5516 * @param child The direct child making the request. 5517 * @param rect The rectangle in the child's coordinates the child 5518 * wishes to be on the screen. 5519 * @param immediate True to forbid animated or delayed scrolling, 5520 * false otherwise 5521 * @return Whether the group scrolled to handle the operation 5522 */ 5523 public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect, 5524 boolean immediate) { 5525 final int parentLeft = getPaddingLeft(); 5526 final int parentTop = getPaddingTop(); 5527 final int parentRight = getWidth() - getPaddingRight(); 5528 final int parentBottom = getHeight() - getPaddingBottom(); 5529 final int childLeft = child.getLeft() + rect.left; 5530 final int childTop = child.getTop() + rect.top; 5531 final int childRight = childLeft + rect.right; 5532 final int childBottom = childTop + rect.bottom; 5533 5534 final int offScreenLeft = Math.min(0, childLeft - parentLeft); 5535 final int offScreenTop = Math.min(0, childTop - parentTop); 5536 final int offScreenRight = Math.max(0, childRight - parentRight); 5537 final int offScreenBottom = Math.max(0, childBottom - parentBottom); 5538 5539 // Favor the "start" layout direction over the end when bringing one side or the other 5540 // of a large rect into view. 5541 final int dx; 5542 if (ViewCompat.getLayoutDirection(parent) == ViewCompat.LAYOUT_DIRECTION_RTL) { 5543 dx = offScreenRight != 0 ? offScreenRight : offScreenLeft; 5544 } else { 5545 dx = offScreenLeft != 0 ? offScreenLeft : offScreenRight; 5546 } 5547 5548 // Favor bringing the top into view over the bottom 5549 final int dy = offScreenTop != 0 ? offScreenTop : offScreenBottom; 5550 5551 if (dx != 0 || dy != 0) { 5552 if (immediate) { 5553 parent.scrollBy(dx, dy); 5554 } else { 5555 parent.smoothScrollBy(dx, dy); 5556 } 5557 return true; 5558 } 5559 return false; 5560 } 5561 5562 /** 5563 * @deprecated Use {@link #onRequestChildFocus(RecyclerView, State, View, View)} 5564 */ 5565 @Deprecated 5566 public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) { 5567 return false; 5568 } 5569 5570 /** 5571 * Called when a descendant view of the RecyclerView requests focus. 5572 * 5573 * <p>A LayoutManager wishing to keep focused views aligned in a specific 5574 * portion of the view may implement that behavior in an override of this method.</p> 5575 * 5576 * <p>If the LayoutManager executes different behavior that should override the default 5577 * behavior of scrolling the focused child on screen instead of running alongside it, 5578 * this method should return true.</p> 5579 * 5580 * @param parent The RecyclerView hosting this LayoutManager 5581 * @param state Current state of RecyclerView 5582 * @param child Direct child of the RecyclerView containing the newly focused view 5583 * @param focused The newly focused view. This may be the same view as child or it may be 5584 * null 5585 * @return true if the default scroll behavior should be suppressed 5586 */ 5587 public boolean onRequestChildFocus(RecyclerView parent, State state, View child, 5588 View focused) { 5589 return onRequestChildFocus(parent, child, focused); 5590 } 5591 5592 /** 5593 * Called if the RecyclerView this LayoutManager is bound to has a different adapter set. 5594 * The LayoutManager may use this opportunity to clear caches and configure state such 5595 * that it can relayout appropriately with the new data and potentially new view types. 5596 * 5597 * <p>The default implementation removes all currently attached views.</p> 5598 * 5599 * @param oldAdapter The previous adapter instance. Will be null if there was previously no 5600 * adapter. 5601 * @param newAdapter The new adapter instance. Might be null if 5602 * {@link #setAdapter(RecyclerView.Adapter)} is called with {@code null}. 5603 */ 5604 public void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) { 5605 } 5606 5607 /** 5608 * Called to populate focusable views within the RecyclerView. 5609 * 5610 * <p>The LayoutManager implementation should return <code>true</code> if the default 5611 * behavior of {@link ViewGroup#addFocusables(java.util.ArrayList, int)} should be 5612 * suppressed.</p> 5613 * 5614 * <p>The default implementation returns <code>false</code> to trigger RecyclerView 5615 * to fall back to the default ViewGroup behavior.</p> 5616 * 5617 * @param recyclerView The RecyclerView hosting this LayoutManager 5618 * @param views List of output views. This method should add valid focusable views 5619 * to this list. 5620 * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN}, 5621 * {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT}, 5622 * {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD} 5623 * @param focusableMode The type of focusables to be added. 5624 * 5625 * @return true to suppress the default behavior, false to add default focusables after 5626 * this method returns. 5627 * 5628 * @see #FOCUSABLES_ALL 5629 * @see #FOCUSABLES_TOUCH_MODE 5630 */ 5631 public boolean onAddFocusables(RecyclerView recyclerView, ArrayList<View> views, 5632 int direction, int focusableMode) { 5633 return false; 5634 } 5635 5636 /** 5637 * Called when {@link Adapter#notifyDataSetChanged()} is triggered instead of giving 5638 * detailed information on what has actually changed. 5639 * 5640 * @param recyclerView 5641 */ 5642 public void onItemsChanged(RecyclerView recyclerView) { 5643 } 5644 5645 /** 5646 * Called when items have been added to the adapter. The LayoutManager may choose to 5647 * requestLayout if the inserted items would require refreshing the currently visible set 5648 * of child views. (e.g. currently empty space would be filled by appended items, etc.) 5649 * 5650 * @param recyclerView 5651 * @param positionStart 5652 * @param itemCount 5653 */ 5654 public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) { 5655 } 5656 5657 /** 5658 * Called when items have been removed from the adapter. 5659 * 5660 * @param recyclerView 5661 * @param positionStart 5662 * @param itemCount 5663 */ 5664 public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) { 5665 } 5666 5667 /** 5668 * Called when items have been changed in the adapter. 5669 * 5670 * @param recyclerView 5671 * @param positionStart 5672 * @param itemCount 5673 */ 5674 public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) { 5675 } 5676 5677 /** 5678 * Called when an item is moved withing the adapter. 5679 * <p> 5680 * Note that, an item may also change position in response to another ADD/REMOVE/MOVE 5681 * operation. This callback is only called if and only if {@link Adapter#notifyItemMoved} 5682 * is called. 5683 * 5684 * @param recyclerView 5685 * @param from 5686 * @param to 5687 * @param itemCount 5688 */ 5689 public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) { 5690 5691 } 5692 5693 5694 /** 5695 * <p>Override this method if you want to support scroll bars.</p> 5696 * 5697 * <p>Read {@link RecyclerView#computeHorizontalScrollExtent()} for details.</p> 5698 * 5699 * <p>Default implementation returns 0.</p> 5700 * 5701 * @param state Current state of RecyclerView 5702 * @return The horizontal extent of the scrollbar's thumb 5703 * @see RecyclerView#computeHorizontalScrollExtent() 5704 */ 5705 public int computeHorizontalScrollExtent(State state) { 5706 return 0; 5707 } 5708 5709 /** 5710 * <p>Override this method if you want to support scroll bars.</p> 5711 * 5712 * <p>Read {@link RecyclerView#computeHorizontalScrollOffset()} for details.</p> 5713 * 5714 * <p>Default implementation returns 0.</p> 5715 * 5716 * @param state Current State of RecyclerView where you can find total item count 5717 * @return The horizontal offset of the scrollbar's thumb 5718 * @see RecyclerView#computeHorizontalScrollOffset() 5719 */ 5720 public int computeHorizontalScrollOffset(State state) { 5721 return 0; 5722 } 5723 5724 /** 5725 * <p>Override this method if you want to support scroll bars.</p> 5726 * 5727 * <p>Read {@link RecyclerView#computeHorizontalScrollRange()} for details.</p> 5728 * 5729 * <p>Default implementation returns 0.</p> 5730 * 5731 * @param state Current State of RecyclerView where you can find total item count 5732 * @return The total horizontal range represented by the vertical scrollbar 5733 * @see RecyclerView#computeHorizontalScrollRange() 5734 */ 5735 public int computeHorizontalScrollRange(State state) { 5736 return 0; 5737 } 5738 5739 /** 5740 * <p>Override this method if you want to support scroll bars.</p> 5741 * 5742 * <p>Read {@link RecyclerView#computeVerticalScrollExtent()} for details.</p> 5743 * 5744 * <p>Default implementation returns 0.</p> 5745 * 5746 * @param state Current state of RecyclerView 5747 * @return The vertical extent of the scrollbar's thumb 5748 * @see RecyclerView#computeVerticalScrollExtent() 5749 */ 5750 public int computeVerticalScrollExtent(State state) { 5751 return 0; 5752 } 5753 5754 /** 5755 * <p>Override this method if you want to support scroll bars.</p> 5756 * 5757 * <p>Read {@link RecyclerView#computeVerticalScrollOffset()} for details.</p> 5758 * 5759 * <p>Default implementation returns 0.</p> 5760 * 5761 * @param state Current State of RecyclerView where you can find total item count 5762 * @return The vertical offset of the scrollbar's thumb 5763 * @see RecyclerView#computeVerticalScrollOffset() 5764 */ 5765 public int computeVerticalScrollOffset(State state) { 5766 return 0; 5767 } 5768 5769 /** 5770 * <p>Override this method if you want to support scroll bars.</p> 5771 * 5772 * <p>Read {@link RecyclerView#computeVerticalScrollRange()} for details.</p> 5773 * 5774 * <p>Default implementation returns 0.</p> 5775 * 5776 * @param state Current State of RecyclerView where you can find total item count 5777 * @return The total vertical range represented by the vertical scrollbar 5778 * @see RecyclerView#computeVerticalScrollRange() 5779 */ 5780 public int computeVerticalScrollRange(State state) { 5781 return 0; 5782 } 5783 5784 /** 5785 * Measure the attached RecyclerView. Implementations must call 5786 * {@link #setMeasuredDimension(int, int)} before returning. 5787 * 5788 * <p>The default implementation will handle EXACTLY measurements and respect 5789 * the minimum width and height properties of the host RecyclerView if measured 5790 * as UNSPECIFIED. AT_MOST measurements will be treated as EXACTLY and the RecyclerView 5791 * will consume all available space.</p> 5792 * 5793 * @param recycler Recycler 5794 * @param state Transient state of RecyclerView 5795 * @param widthSpec Width {@link android.view.View.MeasureSpec} 5796 * @param heightSpec Height {@link android.view.View.MeasureSpec} 5797 */ 5798 public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) { 5799 final int widthMode = MeasureSpec.getMode(widthSpec); 5800 final int heightMode = MeasureSpec.getMode(heightSpec); 5801 final int widthSize = MeasureSpec.getSize(widthSpec); 5802 final int heightSize = MeasureSpec.getSize(heightSpec); 5803 5804 int width = 0; 5805 int height = 0; 5806 5807 switch (widthMode) { 5808 case MeasureSpec.EXACTLY: 5809 case MeasureSpec.AT_MOST: 5810 width = widthSize; 5811 break; 5812 case MeasureSpec.UNSPECIFIED: 5813 default: 5814 width = getMinimumWidth(); 5815 break; 5816 } 5817 5818 switch (heightMode) { 5819 case MeasureSpec.EXACTLY: 5820 case MeasureSpec.AT_MOST: 5821 height = heightSize; 5822 break; 5823 case MeasureSpec.UNSPECIFIED: 5824 default: 5825 height = getMinimumHeight(); 5826 break; 5827 } 5828 5829 setMeasuredDimension(width, height); 5830 } 5831 5832 /** 5833 * {@link View#setMeasuredDimension(int, int) Set the measured dimensions} of the 5834 * host RecyclerView. 5835 * 5836 * @param widthSize Measured width 5837 * @param heightSize Measured height 5838 */ 5839 public void setMeasuredDimension(int widthSize, int heightSize) { 5840 mRecyclerView.setMeasuredDimension(widthSize, heightSize); 5841 } 5842 5843 /** 5844 * @return The host RecyclerView's {@link View#getMinimumWidth()} 5845 */ 5846 public int getMinimumWidth() { 5847 return ViewCompat.getMinimumWidth(mRecyclerView); 5848 } 5849 5850 /** 5851 * @return The host RecyclerView's {@link View#getMinimumHeight()} 5852 */ 5853 public int getMinimumHeight() { 5854 return ViewCompat.getMinimumHeight(mRecyclerView); 5855 } 5856 /** 5857 * <p>Called when the LayoutManager should save its state. This is a good time to save your 5858 * scroll position, configuration and anything else that may be required to restore the same 5859 * layout state if the LayoutManager is recreated.</p> 5860 * <p>RecyclerView does NOT verify if the LayoutManager has changed between state save and 5861 * restore. This will let you share information between your LayoutManagers but it is also 5862 * your responsibility to make sure they use the same parcelable class.</p> 5863 * 5864 * @return Necessary information for LayoutManager to be able to restore its state 5865 */ 5866 public Parcelable onSaveInstanceState() { 5867 return null; 5868 } 5869 5870 5871 public void onRestoreInstanceState(Parcelable state) { 5872 5873 } 5874 5875 void stopSmoothScroller() { 5876 if (mSmoothScroller != null) { 5877 mSmoothScroller.stop(); 5878 } 5879 } 5880 5881 private void onSmoothScrollerStopped(SmoothScroller smoothScroller) { 5882 if (mSmoothScroller == smoothScroller) { 5883 mSmoothScroller = null; 5884 } 5885 } 5886 5887 /** 5888 * RecyclerView calls this method to notify LayoutManager that scroll state has changed. 5889 * 5890 * @param state The new scroll state for RecyclerView 5891 */ 5892 public void onScrollStateChanged(int state) { 5893 } 5894 5895 /** 5896 * Removes all views and recycles them using the given recycler. 5897 * <p> 5898 * If you want to clean cached views as well, you should call {@link Recycler#clear()} too. 5899 * <p> 5900 * If a View is marked as "ignored", it is not removed nor recycled. 5901 * 5902 * @param recycler Recycler to use to recycle children 5903 * @see #removeAndRecycleView(View, Recycler) 5904 * @see #removeAndRecycleViewAt(int, Recycler) 5905 * @see #ignoreView(View) 5906 */ 5907 public void removeAndRecycleAllViews(Recycler recycler) { 5908 for (int i = getChildCount() - 1; i >= 0; i--) { 5909 final View view = getChildAt(i); 5910 if (!getChildViewHolderInt(view).shouldIgnore()) { 5911 removeAndRecycleViewAt(i, recycler); 5912 } 5913 } 5914 } 5915 5916 /** 5917 * A LayoutManager can call this method to force RecyclerView to run simple animations in 5918 * the next layout pass, even if there is not any trigger to do so. (e.g. adapter data 5919 * change). 5920 * <p> 5921 * Note that, calling this method will not guarantee that RecyclerView will run animations 5922 * at all. For example, if there is not any {@link ItemAnimator} set, RecyclerView will 5923 * not run any animations but will still clear this flag after the layout is complete. 5924 * 5925 */ 5926 public void requestSimpleAnimationsInNextLayout() { 5927 mRequestedSimpleAnimations = true; 5928 } 5929 } 5930 5931 /** 5932 * An ItemDecoration allows the application to add a special drawing and layout offset 5933 * to specific item views from the adapter's data set. This can be useful for drawing dividers 5934 * between items, highlights, visual grouping boundaries and more. 5935 * 5936 * <p>All ItemDecorations are drawn in the order they were added, before the item 5937 * views (in {@link ItemDecoration#onDraw(Canvas, RecyclerView, RecyclerView.State) onDraw()} 5938 * and after the items (in {@link ItemDecoration#onDrawOver(Canvas, RecyclerView, 5939 * RecyclerView.State)}.</p> 5940 */ 5941 public static abstract class ItemDecoration { 5942 /** 5943 * Draw any appropriate decorations into the Canvas supplied to the RecyclerView. 5944 * Any content drawn by this method will be drawn before the item views are drawn, 5945 * and will thus appear underneath the views. 5946 * 5947 * @param c Canvas to draw into 5948 * @param parent RecyclerView this ItemDecoration is drawing into 5949 * @param state The current state of RecyclerView 5950 */ 5951 public void onDraw(Canvas c, RecyclerView parent, State state) { 5952 onDraw(c, parent); 5953 } 5954 5955 /** 5956 * @deprecated 5957 * Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)} 5958 */ 5959 @Deprecated 5960 public void onDraw(Canvas c, RecyclerView parent) { 5961 } 5962 5963 /** 5964 * Draw any appropriate decorations into the Canvas supplied to the RecyclerView. 5965 * Any content drawn by this method will be drawn after the item views are drawn 5966 * and will thus appear over the views. 5967 * 5968 * @param c Canvas to draw into 5969 * @param parent RecyclerView this ItemDecoration is drawing into 5970 * @param state The current state of RecyclerView. 5971 */ 5972 public void onDrawOver(Canvas c, RecyclerView parent, State state) { 5973 onDrawOver(c, parent); 5974 } 5975 5976 /** 5977 * @deprecated 5978 * Override {@link #onDrawOver(Canvas, RecyclerView, RecyclerView.State)} 5979 */ 5980 @Deprecated 5981 public void onDrawOver(Canvas c, RecyclerView parent) { 5982 } 5983 5984 5985 /** 5986 * @deprecated 5987 * Use {@link #getItemOffsets(Rect, View, RecyclerView, State)} 5988 */ 5989 @Deprecated 5990 public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { 5991 outRect.set(0, 0, 0, 0); 5992 } 5993 5994 /** 5995 * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies 5996 * the number of pixels that the item view should be inset by, similar to padding or margin. 5997 * The default implementation sets the bounds of outRect to 0 and returns. 5998 * 5999 * <p>If this ItemDecoration does not affect the positioning of item views it should set 6000 * all four fields of <code>outRect</code> (left, top, right, bottom) to zero 6001 * before returning.</p> 6002 * 6003 * @param outRect Rect to receive the output. 6004 * @param view The child view to decorate 6005 * @param parent RecyclerView this ItemDecoration is decorating 6006 * @param state The current state of RecyclerView. 6007 */ 6008 public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) { 6009 getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewPosition(), 6010 parent); 6011 } 6012 } 6013 6014 /** 6015 * An OnItemTouchListener allows the application to intercept touch events in progress at the 6016 * view hierarchy level of the RecyclerView before those touch events are considered for 6017 * RecyclerView's own scrolling behavior. 6018 * 6019 * <p>This can be useful for applications that wish to implement various forms of gestural 6020 * manipulation of item views within the RecyclerView. OnItemTouchListeners may intercept 6021 * a touch interaction already in progress even if the RecyclerView is already handling that 6022 * gesture stream itself for the purposes of scrolling.</p> 6023 */ 6024 public interface OnItemTouchListener { 6025 /** 6026 * Silently observe and/or take over touch events sent to the RecyclerView 6027 * before they are handled by either the RecyclerView itself or its child views. 6028 * 6029 * <p>The onInterceptTouchEvent methods of each attached OnItemTouchListener will be run 6030 * in the order in which each listener was added, before any other touch processing 6031 * by the RecyclerView itself or child views occurs.</p> 6032 * 6033 * @param e MotionEvent describing the touch event. All coordinates are in 6034 * the RecyclerView's coordinate system. 6035 * @return true if this OnItemTouchListener wishes to begin intercepting touch events, false 6036 * to continue with the current behavior and continue observing future events in 6037 * the gesture. 6038 */ 6039 public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e); 6040 6041 /** 6042 * Process a touch event as part of a gesture that was claimed by returning true from 6043 * a previous call to {@link #onInterceptTouchEvent}. 6044 * 6045 * @param e MotionEvent describing the touch event. All coordinates are in 6046 * the RecyclerView's coordinate system. 6047 */ 6048 public void onTouchEvent(RecyclerView rv, MotionEvent e); 6049 } 6050 6051 /** 6052 * An OnScrollListener can be set on a RecyclerView to receive messages 6053 * when a scrolling event has occurred on that RecyclerView. 6054 * 6055 * @see RecyclerView#setOnScrollListener(OnScrollListener) 6056 */ 6057 abstract static public class OnScrollListener { 6058 /** 6059 * Callback method to be invoked when RecyclerView's scroll state changes. 6060 * 6061 * @param recyclerView The RecyclerView whose scroll state has changed. 6062 * @param newState The updated scroll state. One of {@link #SCROLL_STATE_IDLE}, 6063 * {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}. 6064 */ 6065 public void onScrollStateChanged(RecyclerView recyclerView, int newState){} 6066 6067 /** 6068 * Callback method to be invoked when the RecyclerView has been scrolled. This will be 6069 * called after the scroll has completed. 6070 * 6071 * @param recyclerView The RecyclerView which scrolled. 6072 * @param dx The amount of horizontal scroll. 6073 * @param dy The amount of vertical scroll. 6074 */ 6075 public void onScrolled(RecyclerView recyclerView, int dx, int dy){} 6076 } 6077 6078 /** 6079 * A RecyclerListener can be set on a RecyclerView to receive messages whenever 6080 * a view is recycled. 6081 * 6082 * @see RecyclerView#setRecyclerListener(RecyclerListener) 6083 */ 6084 public interface RecyclerListener { 6085 6086 /** 6087 * This method is called whenever the view in the ViewHolder is recycled. 6088 * 6089 * @param holder The ViewHolder containing the view that was recycled 6090 */ 6091 public void onViewRecycled(ViewHolder holder); 6092 } 6093 6094 /** 6095 * A ViewHolder describes an item view and metadata about its place within the RecyclerView. 6096 * 6097 * <p>{@link Adapter} implementations should subclass ViewHolder and add fields for caching 6098 * potentially expensive {@link View#findViewById(int)} results.</p> 6099 * 6100 * <p>While {@link LayoutParams} belong to the {@link LayoutManager}, 6101 * {@link ViewHolder ViewHolders} belong to the adapter. Adapters should feel free to use 6102 * their own custom ViewHolder implementations to store data that makes binding view contents 6103 * easier. Implementations should assume that individual item views will hold strong references 6104 * to <code>ViewHolder</code> objects and that <code>RecyclerView</code> instances may hold 6105 * strong references to extra off-screen item views for caching purposes</p> 6106 */ 6107 public static abstract class ViewHolder { 6108 public final View itemView; 6109 int mPosition = NO_POSITION; 6110 int mOldPosition = NO_POSITION; 6111 long mItemId = NO_ID; 6112 int mItemViewType = INVALID_TYPE; 6113 int mPreLayoutPosition = NO_POSITION; 6114 6115 // The item that this holder is shadowing during an item change event/animation 6116 ViewHolder mShadowedHolder = null; 6117 // The item that is shadowing this holder during an item change event/animation 6118 ViewHolder mShadowingHolder = null; 6119 6120 /** 6121 * This ViewHolder has been bound to a position; mPosition, mItemId and mItemViewType 6122 * are all valid. 6123 */ 6124 static final int FLAG_BOUND = 1 << 0; 6125 6126 /** 6127 * The data this ViewHolder's view reflects is stale and needs to be rebound 6128 * by the adapter. mPosition and mItemId are consistent. 6129 */ 6130 static final int FLAG_UPDATE = 1 << 1; 6131 6132 /** 6133 * This ViewHolder's data is invalid. The identity implied by mPosition and mItemId 6134 * are not to be trusted and may no longer match the item view type. 6135 * This ViewHolder must be fully rebound to different data. 6136 */ 6137 static final int FLAG_INVALID = 1 << 2; 6138 6139 /** 6140 * This ViewHolder points at data that represents an item previously removed from the 6141 * data set. Its view may still be used for things like outgoing animations. 6142 */ 6143 static final int FLAG_REMOVED = 1 << 3; 6144 6145 /** 6146 * This ViewHolder should not be recycled. This flag is set via setIsRecyclable() 6147 * and is intended to keep views around during animations. 6148 */ 6149 static final int FLAG_NOT_RECYCLABLE = 1 << 4; 6150 6151 /** 6152 * This ViewHolder is returned from scrap which means we are expecting an addView call 6153 * for this itemView. When returned from scrap, ViewHolder stays in the scrap list until 6154 * the end of the layout pass and then recycled by RecyclerView if it is not added back to 6155 * the RecyclerView. 6156 */ 6157 static final int FLAG_RETURNED_FROM_SCRAP = 1 << 5; 6158 6159 /** 6160 * This ViewHolder's contents have changed. This flag is used as an indication that 6161 * change animations may be used, if supported by the ItemAnimator. 6162 */ 6163 static final int FLAG_CHANGED = 1 << 6; 6164 6165 /** 6166 * This ViewHolder is fully managed by the LayoutManager. We do not scrap, recycle or remove 6167 * it unless LayoutManager is replaced. 6168 * It is still fully visible to the LayoutManager. 6169 */ 6170 static final int FLAG_IGNORE = 1 << 7; 6171 6172 private int mFlags; 6173 6174 private int mIsRecyclableCount = 0; 6175 6176 // If non-null, view is currently considered scrap and may be reused for other data by the 6177 // scrap container. 6178 private Recycler mScrapContainer = null; 6179 6180 public ViewHolder(View itemView) { 6181 if (itemView == null) { 6182 throw new IllegalArgumentException("itemView may not be null"); 6183 } 6184 this.itemView = itemView; 6185 } 6186 6187 void offsetPosition(int offset, boolean applyToPreLayout) { 6188 if (mOldPosition == NO_POSITION) { 6189 mOldPosition = mPosition; 6190 } 6191 if (mPreLayoutPosition == NO_POSITION) { 6192 mPreLayoutPosition = mPosition; 6193 } 6194 if (applyToPreLayout) { 6195 mPreLayoutPosition += offset; 6196 } 6197 mPosition += offset; 6198 if (itemView.getLayoutParams() != null) { 6199 ((LayoutParams) itemView.getLayoutParams()).mInsetsDirty = true; 6200 } 6201 } 6202 6203 void clearOldPosition() { 6204 mOldPosition = NO_POSITION; 6205 mPreLayoutPosition = NO_POSITION; 6206 } 6207 6208 void saveOldPosition() { 6209 if (mOldPosition == NO_POSITION) { 6210 mOldPosition = mPosition; 6211 } 6212 } 6213 6214 boolean shouldIgnore() { 6215 return (mFlags & FLAG_IGNORE) != 0; 6216 } 6217 6218 public final int getPosition() { 6219 return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition; 6220 } 6221 6222 /** 6223 * When LayoutManager supports animations, RecyclerView tracks 3 positions for ViewHolders 6224 * to perform animations. 6225 * <p> 6226 * If a ViewHolder was laid out in the previous onLayout call, old position will keep its 6227 * adapter index in the previous layout. 6228 * 6229 * @return The previous adapter index of the Item represented by this ViewHolder or 6230 * {@link #NO_POSITION} if old position does not exists or cleared (pre-layout is 6231 * complete). 6232 */ 6233 public final int getOldPosition() { 6234 return mOldPosition; 6235 } 6236 6237 /** 6238 * Returns The itemId represented by this ViewHolder. 6239 * 6240 * @return The the item's id if adapter has stable ids, {@link RecyclerView#NO_ID} 6241 * otherwise 6242 */ 6243 public final long getItemId() { 6244 return mItemId; 6245 } 6246 6247 /** 6248 * @return The view type of this ViewHolder. 6249 */ 6250 public final int getItemViewType() { 6251 return mItemViewType; 6252 } 6253 6254 boolean isScrap() { 6255 return mScrapContainer != null; 6256 } 6257 6258 void unScrap() { 6259 mScrapContainer.unscrapView(this); 6260 } 6261 6262 boolean wasReturnedFromScrap() { 6263 return (mFlags & FLAG_RETURNED_FROM_SCRAP) != 0; 6264 } 6265 6266 void clearReturnedFromScrapFlag() { 6267 mFlags = mFlags & ~FLAG_RETURNED_FROM_SCRAP; 6268 } 6269 6270 void stopIgnoring() { 6271 mFlags = mFlags & ~FLAG_IGNORE; 6272 } 6273 6274 void setScrapContainer(Recycler recycler) { 6275 mScrapContainer = recycler; 6276 } 6277 6278 boolean isInvalid() { 6279 return (mFlags & FLAG_INVALID) != 0; 6280 } 6281 6282 boolean needsUpdate() { 6283 return (mFlags & FLAG_UPDATE) != 0; 6284 } 6285 6286 boolean isChanged() { 6287 return (mFlags & FLAG_CHANGED) != 0; 6288 } 6289 6290 boolean isBound() { 6291 return (mFlags & FLAG_BOUND) != 0; 6292 } 6293 6294 boolean isRemoved() { 6295 return (mFlags & FLAG_REMOVED) != 0; 6296 } 6297 6298 void setFlags(int flags, int mask) { 6299 mFlags = (mFlags & ~mask) | (flags & mask); 6300 } 6301 6302 void addFlags(int flags) { 6303 mFlags |= flags; 6304 } 6305 6306 void resetInternal() { 6307 mFlags = 0; 6308 mPosition = NO_POSITION; 6309 mOldPosition = NO_POSITION; 6310 mItemId = NO_ID; 6311 mPreLayoutPosition = NO_POSITION; 6312 mIsRecyclableCount = 0; 6313 mShadowedHolder = null; 6314 mShadowingHolder = null; 6315 } 6316 6317 @Override 6318 public String toString() { 6319 final StringBuilder sb = new StringBuilder("ViewHolder{" + 6320 Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId + 6321 ", oldPos=" + mOldPosition + ", pLpos:" + mPreLayoutPosition); 6322 if (isScrap()) sb.append(" scrap"); 6323 if (isInvalid()) sb.append(" invalid"); 6324 if (!isBound()) sb.append(" unbound"); 6325 if (needsUpdate()) sb.append(" update"); 6326 if (isRemoved()) sb.append(" removed"); 6327 if (shouldIgnore()) sb.append(" ignored"); 6328 if (isChanged()) sb.append(" changed"); 6329 if (!isRecyclable()) sb.append(" not recyclable(" + mIsRecyclableCount + ")"); 6330 if (itemView.getParent() == null) sb.append(" no parent"); 6331 sb.append("}"); 6332 return sb.toString(); 6333 } 6334 6335 /** 6336 * Informs the recycler whether this item can be recycled. Views which are not 6337 * recyclable will not be reused for other items until setIsRecyclable() is 6338 * later set to true. Calls to setIsRecyclable() should always be paired (one 6339 * call to setIsRecyclabe(false) should always be matched with a later call to 6340 * setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally 6341 * reference-counted. 6342 * 6343 * @param recyclable Whether this item is available to be recycled. Default value 6344 * is true. 6345 */ 6346 public final void setIsRecyclable(boolean recyclable) { 6347 mIsRecyclableCount = recyclable ? mIsRecyclableCount - 1 : mIsRecyclableCount + 1; 6348 if (mIsRecyclableCount < 0) { 6349 mIsRecyclableCount = 0; 6350 Log.e(VIEW_LOG_TAG, "isRecyclable decremented below 0: " + 6351 "unmatched pair of setIsRecyable() calls"); 6352 } else if (!recyclable && mIsRecyclableCount == 1) { 6353 mFlags |= FLAG_NOT_RECYCLABLE; 6354 } else if (recyclable && mIsRecyclableCount == 0) { 6355 mFlags &= ~FLAG_NOT_RECYCLABLE; 6356 } 6357 if (DEBUG) { 6358 Log.d(TAG, "setIsRecyclable val:" + recyclable + ":" + this); 6359 } 6360 } 6361 6362 /** 6363 * @see {@link #setIsRecyclable(boolean)} 6364 * 6365 * @return true if this item is available to be recycled, false otherwise. 6366 */ 6367 public final boolean isRecyclable() { 6368 return (mFlags & FLAG_NOT_RECYCLABLE) == 0 && 6369 !ViewCompat.hasTransientState(itemView); 6370 } 6371 } 6372 6373 /** 6374 * {@link android.view.ViewGroup.MarginLayoutParams LayoutParams} subclass for children of 6375 * {@link RecyclerView}. Custom {@link LayoutManager layout managers} are encouraged 6376 * to create their own subclass of this <code>LayoutParams</code> class 6377 * to store any additional required per-child view metadata about the layout. 6378 */ 6379 public static class LayoutParams extends android.view.ViewGroup.MarginLayoutParams { 6380 ViewHolder mViewHolder; 6381 final Rect mDecorInsets = new Rect(); 6382 boolean mInsetsDirty = true; 6383 6384 public LayoutParams(Context c, AttributeSet attrs) { 6385 super(c, attrs); 6386 } 6387 6388 public LayoutParams(int width, int height) { 6389 super(width, height); 6390 } 6391 6392 public LayoutParams(MarginLayoutParams source) { 6393 super(source); 6394 } 6395 6396 public LayoutParams(ViewGroup.LayoutParams source) { 6397 super(source); 6398 } 6399 6400 public LayoutParams(LayoutParams source) { 6401 super((ViewGroup.LayoutParams) source); 6402 } 6403 6404 /** 6405 * Returns true if the view this LayoutParams is attached to needs to have its content 6406 * updated from the corresponding adapter. 6407 * 6408 * @return true if the view should have its content updated 6409 */ 6410 public boolean viewNeedsUpdate() { 6411 return mViewHolder.needsUpdate(); 6412 } 6413 6414 /** 6415 * Returns true if the view this LayoutParams is attached to is now representing 6416 * potentially invalid data. A LayoutManager should scrap/recycle it. 6417 * 6418 * @return true if the view is invalid 6419 */ 6420 public boolean isViewInvalid() { 6421 return mViewHolder.isInvalid(); 6422 } 6423 6424 /** 6425 * Returns true if the adapter data item corresponding to the view this LayoutParams 6426 * is attached to has been removed from the data set. A LayoutManager may choose to 6427 * treat it differently in order to animate its outgoing or disappearing state. 6428 * 6429 * @return true if the item the view corresponds to was removed from the data set 6430 */ 6431 public boolean isItemRemoved() { 6432 return mViewHolder.isRemoved(); 6433 } 6434 6435 /** 6436 * Returns true if the adapter data item corresponding to the view this LayoutParams 6437 * is attached to has been changed in the data set. A LayoutManager may choose to 6438 * treat it differently in order to animate its changing state. 6439 * 6440 * @return true if the item the view corresponds to was changed in the data set 6441 */ 6442 public boolean isItemChanged() { 6443 return mViewHolder.isChanged(); 6444 } 6445 6446 /** 6447 * Returns the position that the view this LayoutParams is attached to corresponds to. 6448 * 6449 * @return the adapter position this view was bound from 6450 */ 6451 public int getViewPosition() { 6452 return mViewHolder.getPosition(); 6453 } 6454 } 6455 6456 /** 6457 * Observer base class for watching changes to an {@link Adapter}. 6458 * See {@link Adapter#registerAdapterDataObserver(AdapterDataObserver)}. 6459 */ 6460 public static abstract class AdapterDataObserver { 6461 public void onChanged() { 6462 // Do nothing 6463 } 6464 6465 public void onItemRangeChanged(int positionStart, int itemCount) { 6466 // do nothing 6467 } 6468 6469 public void onItemRangeInserted(int positionStart, int itemCount) { 6470 // do nothing 6471 } 6472 6473 public void onItemRangeRemoved(int positionStart, int itemCount) { 6474 // do nothing 6475 } 6476 6477 public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) { 6478 // do nothing 6479 } 6480 } 6481 6482 /** 6483 * <p>Base class for smooth scrolling. Handles basic tracking of the target view position and 6484 * provides methods to trigger a programmatic scroll.</p> 6485 * 6486 * @see LinearSmoothScroller 6487 */ 6488 public static abstract class SmoothScroller { 6489 6490 private int mTargetPosition = RecyclerView.NO_POSITION; 6491 6492 private RecyclerView mRecyclerView; 6493 6494 private LayoutManager mLayoutManager; 6495 6496 private boolean mPendingInitialRun; 6497 6498 private boolean mRunning; 6499 6500 private View mTargetView; 6501 6502 private final Action mRecyclingAction; 6503 6504 public SmoothScroller() { 6505 mRecyclingAction = new Action(0, 0); 6506 } 6507 6508 /** 6509 * Starts a smooth scroll for the given target position. 6510 * <p>In each animation step, {@link RecyclerView} will check 6511 * for the target view and call either 6512 * {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or 6513 * {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)} until 6514 * SmoothScroller is stopped.</p> 6515 * 6516 * <p>Note that if RecyclerView finds the target view, it will automatically stop the 6517 * SmoothScroller. This <b>does not</b> mean that scroll will stop, it only means it will 6518 * stop calling SmoothScroller in each animation step.</p> 6519 */ 6520 void start(RecyclerView recyclerView, LayoutManager layoutManager) { 6521 mRecyclerView = recyclerView; 6522 mLayoutManager = layoutManager; 6523 if (mTargetPosition == RecyclerView.NO_POSITION) { 6524 throw new IllegalArgumentException("Invalid target position"); 6525 } 6526 mRecyclerView.mState.mTargetPosition = mTargetPosition; 6527 mRunning = true; 6528 mPendingInitialRun = true; 6529 mTargetView = findViewByPosition(getTargetPosition()); 6530 onStart(); 6531 mRecyclerView.mViewFlinger.postOnAnimation(); 6532 } 6533 6534 public void setTargetPosition(int targetPosition) { 6535 mTargetPosition = targetPosition; 6536 } 6537 6538 /** 6539 * @return The LayoutManager to which this SmoothScroller is attached 6540 */ 6541 public LayoutManager getLayoutManager() { 6542 return mLayoutManager; 6543 } 6544 6545 /** 6546 * Stops running the SmoothScroller in each animation callback. Note that this does not 6547 * cancel any existing {@link Action} updated by 6548 * {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or 6549 * {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)}. 6550 */ 6551 final protected void stop() { 6552 if (!mRunning) { 6553 return; 6554 } 6555 onStop(); 6556 mRecyclerView.mState.mTargetPosition = RecyclerView.NO_POSITION; 6557 mTargetView = null; 6558 mTargetPosition = RecyclerView.NO_POSITION; 6559 mPendingInitialRun = false; 6560 mRunning = false; 6561 // trigger a cleanup 6562 mLayoutManager.onSmoothScrollerStopped(this); 6563 // clear references to avoid any potential leak by a custom smooth scroller 6564 mLayoutManager = null; 6565 mRecyclerView = null; 6566 } 6567 6568 /** 6569 * Returns true if SmoothScroller has been started but has not received the first 6570 * animation 6571 * callback yet. 6572 * 6573 * @return True if this SmoothScroller is waiting to start 6574 */ 6575 public boolean isPendingInitialRun() { 6576 return mPendingInitialRun; 6577 } 6578 6579 6580 /** 6581 * @return True if SmoothScroller is currently active 6582 */ 6583 public boolean isRunning() { 6584 return mRunning; 6585 } 6586 6587 /** 6588 * Returns the adapter position of the target item 6589 * 6590 * @return Adapter position of the target item or 6591 * {@link RecyclerView#NO_POSITION} if no target view is set. 6592 */ 6593 public int getTargetPosition() { 6594 return mTargetPosition; 6595 } 6596 6597 private void onAnimation(int dx, int dy) { 6598 if (!mRunning || mTargetPosition == RecyclerView.NO_POSITION) { 6599 stop(); 6600 } 6601 mPendingInitialRun = false; 6602 if (mTargetView != null) { 6603 // verify target position 6604 if (getChildPosition(mTargetView) == mTargetPosition) { 6605 onTargetFound(mTargetView, mRecyclerView.mState, mRecyclingAction); 6606 mRecyclingAction.runIfNecessary(mRecyclerView); 6607 stop(); 6608 } else { 6609 Log.e(TAG, "Passed over target position while smooth scrolling."); 6610 mTargetView = null; 6611 } 6612 } 6613 if (mRunning) { 6614 onSeekTargetStep(dx, dy, mRecyclerView.mState, mRecyclingAction); 6615 mRecyclingAction.runIfNecessary(mRecyclerView); 6616 } 6617 } 6618 6619 /** 6620 * @see RecyclerView#getChildPosition(android.view.View) 6621 */ 6622 public int getChildPosition(View view) { 6623 return mRecyclerView.getChildPosition(view); 6624 } 6625 6626 /** 6627 * @see RecyclerView.LayoutManager#getChildCount() 6628 */ 6629 public int getChildCount() { 6630 return mRecyclerView.mLayout.getChildCount(); 6631 } 6632 6633 /** 6634 * @see RecyclerView.LayoutManager#findViewByPosition(int) 6635 */ 6636 public View findViewByPosition(int position) { 6637 return mRecyclerView.mLayout.findViewByPosition(position); 6638 } 6639 6640 /** 6641 * @see RecyclerView#scrollToPosition(int) 6642 */ 6643 public void instantScrollToPosition(int position) { 6644 mRecyclerView.scrollToPosition(position); 6645 } 6646 6647 protected void onChildAttachedToWindow(View child) { 6648 if (getChildPosition(child) == getTargetPosition()) { 6649 mTargetView = child; 6650 if (DEBUG) { 6651 Log.d(TAG, "smooth scroll target view has been attached"); 6652 } 6653 } 6654 } 6655 6656 /** 6657 * Normalizes the vector. 6658 * @param scrollVector The vector that points to the target scroll position 6659 */ 6660 protected void normalize(PointF scrollVector) { 6661 final double magnitute = Math.sqrt(scrollVector.x * scrollVector.x + scrollVector.y * 6662 scrollVector.y); 6663 scrollVector.x /= magnitute; 6664 scrollVector.y /= magnitute; 6665 } 6666 6667 /** 6668 * Called when smooth scroll is started. This might be a good time to do setup. 6669 */ 6670 abstract protected void onStart(); 6671 6672 /** 6673 * Called when smooth scroller is stopped. This is a good place to cleanup your state etc. 6674 * @see #stop() 6675 */ 6676 abstract protected void onStop(); 6677 6678 /** 6679 * <p>RecyclerView will call this method each time it scrolls until it can find the target 6680 * position in the layout.</p> 6681 * <p>SmoothScroller should check dx, dy and if scroll should be changed, update the 6682 * provided {@link Action} to define the next scroll.</p> 6683 * 6684 * @param dx Last scroll amount horizontally 6685 * @param dy Last scroll amount verticaully 6686 * @param state Transient state of RecyclerView 6687 * @param action If you want to trigger a new smooth scroll and cancel the previous one, 6688 * update this object. 6689 */ 6690 abstract protected void onSeekTargetStep(int dx, int dy, State state, Action action); 6691 6692 /** 6693 * Called when the target position is laid out. This is the last callback SmoothScroller 6694 * will receive and it should update the provided {@link Action} to define the scroll 6695 * details towards the target view. 6696 * @param targetView The view element which render the target position. 6697 * @param state Transient state of RecyclerView 6698 * @param action Action instance that you should update to define final scroll action 6699 * towards the targetView 6700 * @return An {@link Action} to finalize the smooth scrolling 6701 */ 6702 abstract protected void onTargetFound(View targetView, State state, Action action); 6703 6704 /** 6705 * Holds information about a smooth scroll request by a {@link SmoothScroller}. 6706 */ 6707 public static class Action { 6708 6709 public static final int UNDEFINED_DURATION = Integer.MIN_VALUE; 6710 6711 private int mDx; 6712 6713 private int mDy; 6714 6715 private int mDuration; 6716 6717 private Interpolator mInterpolator; 6718 6719 private boolean changed = false; 6720 6721 // we track this variable to inform custom implementer if they are updating the action 6722 // in every animation callback 6723 private int consecutiveUpdates = 0; 6724 6725 /** 6726 * @param dx Pixels to scroll horizontally 6727 * @param dy Pixels to scroll vertically 6728 */ 6729 public Action(int dx, int dy) { 6730 this(dx, dy, UNDEFINED_DURATION, null); 6731 } 6732 6733 /** 6734 * @param dx Pixels to scroll horizontally 6735 * @param dy Pixels to scroll vertically 6736 * @param duration Duration of the animation in milliseconds 6737 */ 6738 public Action(int dx, int dy, int duration) { 6739 this(dx, dy, duration, null); 6740 } 6741 6742 /** 6743 * @param dx Pixels to scroll horizontally 6744 * @param dy Pixels to scroll vertically 6745 * @param duration Duration of the animation in milliseconds 6746 * @param interpolator Interpolator to be used when calculating scroll position in each 6747 * animation step 6748 */ 6749 public Action(int dx, int dy, int duration, Interpolator interpolator) { 6750 mDx = dx; 6751 mDy = dy; 6752 mDuration = duration; 6753 mInterpolator = interpolator; 6754 } 6755 private void runIfNecessary(RecyclerView recyclerView) { 6756 if (changed) { 6757 validate(); 6758 if (mInterpolator == null) { 6759 if (mDuration == UNDEFINED_DURATION) { 6760 recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy); 6761 } else { 6762 recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration); 6763 } 6764 } else { 6765 recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration, mInterpolator); 6766 } 6767 consecutiveUpdates ++; 6768 if (consecutiveUpdates > 10) { 6769 // A new action is being set in every animation step. This looks like a bad 6770 // implementation. Inform developer. 6771 Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure" 6772 + " you are not changing it unless necessary"); 6773 } 6774 changed = false; 6775 } else { 6776 consecutiveUpdates = 0; 6777 } 6778 } 6779 6780 private void validate() { 6781 if (mInterpolator != null && mDuration < 1) { 6782 throw new IllegalStateException("If you provide an interpolator, you must" 6783 + " set a positive duration"); 6784 } else if (mDuration < 1) { 6785 throw new IllegalStateException("Scroll duration must be a positive number"); 6786 } 6787 } 6788 6789 public int getDx() { 6790 return mDx; 6791 } 6792 6793 public void setDx(int dx) { 6794 changed = true; 6795 mDx = dx; 6796 } 6797 6798 public int getDy() { 6799 return mDy; 6800 } 6801 6802 public void setDy(int dy) { 6803 changed = true; 6804 mDy = dy; 6805 } 6806 6807 public int getDuration() { 6808 return mDuration; 6809 } 6810 6811 public void setDuration(int duration) { 6812 changed = true; 6813 mDuration = duration; 6814 } 6815 6816 public Interpolator getInterpolator() { 6817 return mInterpolator; 6818 } 6819 6820 /** 6821 * Sets the interpolator to calculate scroll steps 6822 * @param interpolator The interpolator to use. If you specify an interpolator, you must 6823 * also set the duration. 6824 * @see #setDuration(int) 6825 */ 6826 public void setInterpolator(Interpolator interpolator) { 6827 changed = true; 6828 mInterpolator = interpolator; 6829 } 6830 6831 /** 6832 * Updates the action with given parameters. 6833 * @param dx Pixels to scroll horizontally 6834 * @param dy Pixels to scroll vertically 6835 * @param duration Duration of the animation in milliseconds 6836 * @param interpolator Interpolator to be used when calculating scroll position in each 6837 * animation step 6838 */ 6839 public void update(int dx, int dy, int duration, Interpolator interpolator) { 6840 mDx = dx; 6841 mDy = dy; 6842 mDuration = duration; 6843 mInterpolator = interpolator; 6844 changed = true; 6845 } 6846 } 6847 } 6848 6849 static class AdapterDataObservable extends Observable<AdapterDataObserver> { 6850 public boolean hasObservers() { 6851 return !mObservers.isEmpty(); 6852 } 6853 6854 public void notifyChanged() { 6855 // since onChanged() is implemented by the app, it could do anything, including 6856 // removing itself from {@link mObservers} - and that could cause problems if 6857 // an iterator is used on the ArrayList {@link mObservers}. 6858 // to avoid such problems, just march thru the list in the reverse order. 6859 for (int i = mObservers.size() - 1; i >= 0; i--) { 6860 mObservers.get(i).onChanged(); 6861 } 6862 } 6863 6864 public void notifyItemRangeChanged(int positionStart, int itemCount) { 6865 // since onItemRangeChanged() is implemented by the app, it could do anything, including 6866 // removing itself from {@link mObservers} - and that could cause problems if 6867 // an iterator is used on the ArrayList {@link mObservers}. 6868 // to avoid such problems, just march thru the list in the reverse order. 6869 for (int i = mObservers.size() - 1; i >= 0; i--) { 6870 mObservers.get(i).onItemRangeChanged(positionStart, itemCount); 6871 } 6872 } 6873 6874 public void notifyItemRangeInserted(int positionStart, int itemCount) { 6875 // since onItemRangeInserted() is implemented by the app, it could do anything, 6876 // including removing itself from {@link mObservers} - and that could cause problems if 6877 // an iterator is used on the ArrayList {@link mObservers}. 6878 // to avoid such problems, just march thru the list in the reverse order. 6879 for (int i = mObservers.size() - 1; i >= 0; i--) { 6880 mObservers.get(i).onItemRangeInserted(positionStart, itemCount); 6881 } 6882 } 6883 6884 public void notifyItemRangeRemoved(int positionStart, int itemCount) { 6885 // since onItemRangeRemoved() is implemented by the app, it could do anything, including 6886 // removing itself from {@link mObservers} - and that could cause problems if 6887 // an iterator is used on the ArrayList {@link mObservers}. 6888 // to avoid such problems, just march thru the list in the reverse order. 6889 for (int i = mObservers.size() - 1; i >= 0; i--) { 6890 mObservers.get(i).onItemRangeRemoved(positionStart, itemCount); 6891 } 6892 } 6893 6894 public void notifyItemMoved(int fromPosition, int toPosition) { 6895 for (int i = mObservers.size() - 1; i >= 0; i--) { 6896 mObservers.get(i).onItemRangeMoved(fromPosition, toPosition, 1); 6897 } 6898 } 6899 } 6900 6901 static class SavedState extends android.view.View.BaseSavedState { 6902 6903 Parcelable mLayoutState; 6904 6905 /** 6906 * called by CREATOR 6907 */ 6908 SavedState(Parcel in) { 6909 super(in); 6910 mLayoutState = in.readParcelable(LayoutManager.class.getClassLoader()); 6911 } 6912 6913 /** 6914 * Called by onSaveInstanceState 6915 */ 6916 SavedState(Parcelable superState) { 6917 super(superState); 6918 } 6919 6920 @Override 6921 public void writeToParcel(Parcel dest, int flags) { 6922 super.writeToParcel(dest, flags); 6923 dest.writeParcelable(mLayoutState, 0); 6924 } 6925 6926 private void copyFrom(SavedState other) { 6927 mLayoutState = other.mLayoutState; 6928 } 6929 6930 public static final Parcelable.Creator<SavedState> CREATOR 6931 = new Parcelable.Creator<SavedState>() { 6932 @Override 6933 public SavedState createFromParcel(Parcel in) { 6934 return new SavedState(in); 6935 } 6936 6937 @Override 6938 public SavedState[] newArray(int size) { 6939 return new SavedState[size]; 6940 } 6941 }; 6942 } 6943 /** 6944 * <p>Contains useful information about the current RecyclerView state like target scroll 6945 * position or view focus. State object can also keep arbitrary data, identified by resource 6946 * ids.</p> 6947 * <p>Often times, RecyclerView components will need to pass information between each other. 6948 * To provide a well defined data bus between components, RecyclerView passes the same State 6949 * object to component callbacks and these components can use it to exchange data.</p> 6950 * <p>If you implement custom components, you can use State's put/get/remove methods to pass 6951 * data between your components without needing to manage their lifecycles.</p> 6952 */ 6953 public static class State { 6954 6955 private int mTargetPosition = RecyclerView.NO_POSITION; 6956 ArrayMap<ViewHolder, ItemHolderInfo> mPreLayoutHolderMap = 6957 new ArrayMap<ViewHolder, ItemHolderInfo>(); 6958 ArrayMap<ViewHolder, ItemHolderInfo> mPostLayoutHolderMap = 6959 new ArrayMap<ViewHolder, ItemHolderInfo>(); 6960 // nullable 6961 ArrayMap<Long, ViewHolder> mOldChangedHolders = new ArrayMap<Long, ViewHolder>(); 6962 6963 private SparseArray<Object> mData; 6964 6965 /** 6966 * Number of items adapter has. 6967 */ 6968 private int mItemCount = 0; 6969 6970 /** 6971 * Number of items adapter had in the previous layout. 6972 */ 6973 private int mPreviousLayoutItemCount = 0; 6974 6975 /** 6976 * Number of items that were NOT laid out but has been deleted from the adapter after the 6977 * previous layout. 6978 */ 6979 private int mDeletedInvisibleItemCountSincePreviousLayout = 0; 6980 6981 private boolean mStructureChanged = false; 6982 6983 private boolean mInPreLayout = false; 6984 6985 private boolean mRunSimpleAnimations = false; 6986 6987 private boolean mRunPredictiveAnimations = false; 6988 6989 State reset() { 6990 mTargetPosition = RecyclerView.NO_POSITION; 6991 if (mData != null) { 6992 mData.clear(); 6993 } 6994 mItemCount = 0; 6995 mStructureChanged = false; 6996 return this; 6997 } 6998 6999 public boolean isPreLayout() { 7000 return mInPreLayout; 7001 } 7002 7003 /** 7004 * Returns whether RecyclerView will run predictive animations in this layout pass 7005 * or not. 7006 * 7007 * @return true if RecyclerView is calculating predictive animations to be run at the end 7008 * of the layout pass. 7009 */ 7010 public boolean willRunPredictiveAnimations() { 7011 return mRunPredictiveAnimations; 7012 } 7013 7014 /** 7015 * Returns whether RecyclerView will run simple animations in this layout pass 7016 * or not. 7017 * 7018 * @return true if RecyclerView is calculating simple animations to be run at the end of 7019 * the layout pass. 7020 */ 7021 public boolean willRunSimpleAnimations() { 7022 return mRunSimpleAnimations; 7023 } 7024 7025 /** 7026 * Removes the mapping from the specified id, if there was any. 7027 * @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* to 7028 * preserve cross functionality and avoid conflicts. 7029 */ 7030 public void remove(int resourceId) { 7031 if (mData == null) { 7032 return; 7033 } 7034 mData.remove(resourceId); 7035 } 7036 7037 /** 7038 * Gets the Object mapped from the specified id, or <code>null</code> 7039 * if no such data exists. 7040 * 7041 * @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* 7042 * to 7043 * preserve cross functionality and avoid conflicts. 7044 */ 7045 public <T> T get(int resourceId) { 7046 if (mData == null) { 7047 return null; 7048 } 7049 return (T) mData.get(resourceId); 7050 } 7051 7052 /** 7053 * Adds a mapping from the specified id to the specified value, replacing the previous 7054 * mapping from the specified key if there was one. 7055 * 7056 * @param resourceId Id of the resource you want to add. It is suggested to use R.id.* to 7057 * preserve cross functionality and avoid conflicts. 7058 * @param data The data you want to associate with the resourceId. 7059 */ 7060 public void put(int resourceId, Object data) { 7061 if (mData == null) { 7062 mData = new SparseArray<Object>(); 7063 } 7064 mData.put(resourceId, data); 7065 } 7066 7067 /** 7068 * If scroll is triggered to make a certain item visible, this value will return the 7069 * adapter index of that item. 7070 * @return Adapter index of the target item or 7071 * {@link RecyclerView#NO_POSITION} if there is no target 7072 * position. 7073 */ 7074 public int getTargetScrollPosition() { 7075 return mTargetPosition; 7076 } 7077 7078 /** 7079 * Returns if current scroll has a target position. 7080 * @return true if scroll is being triggered to make a certain position visible 7081 * @see #getTargetScrollPosition() 7082 */ 7083 public boolean hasTargetScrollPosition() { 7084 return mTargetPosition != RecyclerView.NO_POSITION; 7085 } 7086 7087 /** 7088 * @return true if the structure of the data set has changed since the last call to 7089 * onLayoutChildren, false otherwise 7090 */ 7091 public boolean didStructureChange() { 7092 return mStructureChanged; 7093 } 7094 7095 /** 7096 * Returns the total number of items that can be laid out. Note that this number is not 7097 * necessarily equal to the number of items in the adapter, so you should always use this 7098 * number for your position calculations and never access the adapter directly. 7099 * <p> 7100 * RecyclerView listens for Adapter's notify events and calculates the effects of adapter 7101 * data changes on existing Views. These calculations are used to decide which animations 7102 * should be run. 7103 * <p> 7104 * To support predictive animations, RecyclerView may rewrite or reorder Adapter changes to 7105 * present the correct state to LayoutManager in pre-layout pass. 7106 * <p> 7107 * For example, a newly added item is not included in pre-layout item count because 7108 * pre-layout reflects the contents of the adapter before the item is added. Behind the 7109 * scenes, RecyclerView offsets {@link Recycler#getViewForPosition(int)} calls such that 7110 * LayoutManager does not know about the new item's existence in pre-layout. The item will 7111 * be available in second layout pass and will be included in the item count. Similar 7112 * adjustments are made for moved and removed items as well. 7113 * <p> 7114 * You can get the adapter's item count via {@link LayoutManager#getItemCount()} method. 7115 * 7116 * @return The number of items currently available 7117 * @see LayoutManager#getItemCount() 7118 */ 7119 public int getItemCount() { 7120 return mInPreLayout ? 7121 (mPreviousLayoutItemCount - mDeletedInvisibleItemCountSincePreviousLayout) : 7122 mItemCount; 7123 } 7124 7125 public void onViewRecycled(ViewHolder holder) { 7126 mPreLayoutHolderMap.remove(holder); 7127 mPostLayoutHolderMap.remove(holder); 7128 if (mOldChangedHolders != null) { 7129 removeFrom(mOldChangedHolders, holder); 7130 } 7131 // holder cannot be in new list. 7132 } 7133 7134 public void onViewIgnored(ViewHolder holder) { 7135 onViewRecycled(holder); 7136 } 7137 7138 private void removeFrom(ArrayMap<Long, ViewHolder> holderMap, ViewHolder holder) { 7139 for (int i = holderMap.size() - 1; i >= 0; i --) { 7140 if (holder == holderMap.valueAt(i)) { 7141 holderMap.removeAt(i); 7142 return; 7143 } 7144 } 7145 } 7146 7147 @Override 7148 public String toString() { 7149 return "State{" + 7150 "mTargetPosition=" + mTargetPosition + 7151 ", mPreLayoutHolderMap=" + mPreLayoutHolderMap + 7152 ", mPostLayoutHolderMap=" + mPostLayoutHolderMap + 7153 ", mData=" + mData + 7154 ", mItemCount=" + mItemCount + 7155 ", mPreviousLayoutItemCount=" + mPreviousLayoutItemCount + 7156 ", mDeletedInvisibleItemCountSincePreviousLayout=" 7157 + mDeletedInvisibleItemCountSincePreviousLayout + 7158 ", mStructureChanged=" + mStructureChanged + 7159 ", mInPreLayout=" + mInPreLayout + 7160 ", mRunSimpleAnimations=" + mRunSimpleAnimations + 7161 ", mRunPredictiveAnimations=" + mRunPredictiveAnimations + 7162 '}'; 7163 } 7164 } 7165 7166 /** 7167 * Internal listener that manages items after animations finish. This is how items are 7168 * retained (not recycled) during animations, but allowed to be recycled afterwards. 7169 * It depends on the contract with the ItemAnimator to call the appropriate dispatch*Finished() 7170 * method on the animator's listener when it is done animating any item. 7171 */ 7172 private class ItemAnimatorRestoreListener implements ItemAnimator.ItemAnimatorListener { 7173 7174 @Override 7175 public void onRemoveFinished(ViewHolder item) { 7176 item.setIsRecyclable(true); 7177 removeAnimatingView(item.itemView); 7178 removeDetachedView(item.itemView, false); 7179 } 7180 7181 @Override 7182 public void onAddFinished(ViewHolder item) { 7183 item.setIsRecyclable(true); 7184 if (item.isRecyclable()) { 7185 removeAnimatingView(item.itemView); 7186 } 7187 } 7188 7189 @Override 7190 public void onMoveFinished(ViewHolder item) { 7191 item.setIsRecyclable(true); 7192 if (item.isRecyclable()) { 7193 removeAnimatingView(item.itemView); 7194 } 7195 } 7196 7197 @Override 7198 public void onChangeFinished(ViewHolder item) { 7199 item.setIsRecyclable(true); 7200 /** 7201 * We check both shadowed and shadowing because a ViewHolder may get both roles at the 7202 * same time. 7203 * 7204 * Assume this flow: 7205 * item X is represented by VH_1. Then itemX changes, so we create VH_2 . 7206 * RV sets the following and calls item animator: 7207 * VH_1.shadowed = VH_2; 7208 * VH_1.mChanged = true; 7209 * VH_2.shadowing =VH_1; 7210 * 7211 * Then, before the first change finishes, item changes again so we create VH_3. 7212 * RV sets the following and calls item animator: 7213 * VH_2.shadowed = VH_3 7214 * VH_2.mChanged = true 7215 * VH_3.shadowing = VH_2 7216 * 7217 * Because VH_2 already has an animation, it will be cancelled. At this point VH_2 has 7218 * both shadowing and shadowed fields set. Shadowing information is obsolete now 7219 * because the first animation where VH_2 is newViewHolder is not valid anymore. 7220 * We ended up in this case because VH_2 played both roles. On the other hand, 7221 * we DO NOT want to clear its changed flag. 7222 * 7223 * If second change was simply reverting first change, we would find VH_1 in 7224 * {@link Recycler#getScrapViewForPosition(int, int, boolean)} and recycle it before 7225 * re-using 7226 */ 7227 if (item.mShadowedHolder != null && item.mShadowingHolder == null) { // old vh 7228 item.mShadowedHolder = null; 7229 item.setFlags(~ViewHolder.FLAG_CHANGED, item.mFlags); 7230 } 7231 // always null this because an OldViewHolder can never become NewViewHolder w/o being 7232 // recycled. 7233 item.mShadowingHolder = null; 7234 if (item.isRecyclable()) { 7235 removeAnimatingView(item.itemView); 7236 } 7237 } 7238 }; 7239 7240 /** 7241 * This class defines the animations that take place on items as changes are made 7242 * to the adapter. 7243 * 7244 * Subclasses of ItemAnimator can be used to implement custom animations for actions on 7245 * ViewHolder items. The RecyclerView will manage retaining these items while they 7246 * are being animated, but implementors must call the appropriate "Starting" 7247 * ({@link #dispatchRemoveStarting(ViewHolder)}, {@link #dispatchMoveStarting(ViewHolder)}, 7248 * {@link #dispatchChangeStarting(ViewHolder, boolean)}, or 7249 * {@link #dispatchAddStarting(ViewHolder)}) 7250 * and "Finished" ({@link #dispatchRemoveFinished(ViewHolder)}, 7251 * {@link #dispatchMoveFinished(ViewHolder)}, 7252 * {@link #dispatchChangeFinished(ViewHolder, boolean)}, 7253 * or {@link #dispatchAddFinished(ViewHolder)}) methods when each item animation is 7254 * being started and ended. 7255 * 7256 * <p>By default, RecyclerView uses {@link DefaultItemAnimator}</p> 7257 * 7258 * @see #setItemAnimator(ItemAnimator) 7259 */ 7260 public static abstract class ItemAnimator { 7261 7262 private ItemAnimatorListener mListener = null; 7263 private ArrayList<ItemAnimatorFinishedListener> mFinishedListeners = 7264 new ArrayList<ItemAnimatorFinishedListener>(); 7265 7266 private long mAddDuration = 120; 7267 private long mRemoveDuration = 120; 7268 private long mMoveDuration = 250; 7269 private long mChangeDuration = 250; 7270 7271 private boolean mSupportsChangeAnimations = false; 7272 7273 /** 7274 * Gets the current duration for which all move animations will run. 7275 * 7276 * @return The current move duration 7277 */ 7278 public long getMoveDuration() { 7279 return mMoveDuration; 7280 } 7281 7282 /** 7283 * Sets the duration for which all move animations will run. 7284 * 7285 * @param moveDuration The move duration 7286 */ 7287 public void setMoveDuration(long moveDuration) { 7288 mMoveDuration = moveDuration; 7289 } 7290 7291 /** 7292 * Gets the current duration for which all add animations will run. 7293 * 7294 * @return The current add duration 7295 */ 7296 public long getAddDuration() { 7297 return mAddDuration; 7298 } 7299 7300 /** 7301 * Sets the duration for which all add animations will run. 7302 * 7303 * @param addDuration The add duration 7304 */ 7305 public void setAddDuration(long addDuration) { 7306 mAddDuration = addDuration; 7307 } 7308 7309 /** 7310 * Gets the current duration for which all remove animations will run. 7311 * 7312 * @return The current remove duration 7313 */ 7314 public long getRemoveDuration() { 7315 return mRemoveDuration; 7316 } 7317 7318 /** 7319 * Sets the duration for which all remove animations will run. 7320 * 7321 * @param removeDuration The remove duration 7322 */ 7323 public void setRemoveDuration(long removeDuration) { 7324 mRemoveDuration = removeDuration; 7325 } 7326 7327 /** 7328 * Gets the current duration for which all change animations will run. 7329 * 7330 * @return The current change duration 7331 */ 7332 public long getChangeDuration() { 7333 return mChangeDuration; 7334 } 7335 7336 /** 7337 * Sets the duration for which all change animations will run. 7338 * 7339 * @param changeDuration The change duration 7340 */ 7341 public void setChangeDuration(long changeDuration) { 7342 mChangeDuration = changeDuration; 7343 } 7344 7345 /** 7346 * Returns whether this ItemAnimator supports animations of change events. 7347 * 7348 * @return true if change animations are supported, false otherwise 7349 */ 7350 public boolean getSupportsChangeAnimations() { 7351 return mSupportsChangeAnimations; 7352 } 7353 7354 /** 7355 * Sets whether this ItemAnimator supports animations of item change events. 7356 * By default, ItemAnimator only supports animations when items are added or removed. 7357 * By setting this property to true, actions on the data set which change the 7358 * contents of items may also be animated. What those animations are is left 7359 * up to the discretion of the ItemAnimator subclass, in its 7360 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} implementation. 7361 * The value of this property is false by default. 7362 * 7363 * @see Adapter#notifyItemChanged(int) 7364 * @see Adapter#notifyItemRangeChanged(int, int) 7365 * 7366 * @param supportsChangeAnimations true if change animations are supported by 7367 * this ItemAnimator, false otherwise. If the property is false, the ItemAnimator 7368 * will not receive a call to 7369 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} when changes occur. 7370 */ 7371 public void setSupportsChangeAnimations(boolean supportsChangeAnimations) { 7372 mSupportsChangeAnimations = supportsChangeAnimations; 7373 } 7374 7375 /** 7376 * Internal only: 7377 * Sets the listener that must be called when the animator is finished 7378 * animating the item (or immediately if no animation happens). This is set 7379 * internally and is not intended to be set by external code. 7380 * 7381 * @param listener The listener that must be called. 7382 */ 7383 void setListener(ItemAnimatorListener listener) { 7384 mListener = listener; 7385 } 7386 7387 /** 7388 * Called when there are pending animations waiting to be started. This state 7389 * is governed by the return values from {@link #animateAdd(ViewHolder) animateAdd()}, 7390 * {@link #animateMove(ViewHolder, int, int, int, int) animateMove()}, and 7391 * {@link #animateRemove(ViewHolder) animateRemove()}, which inform the 7392 * RecyclerView that the ItemAnimator wants to be called later to start the 7393 * associated animations. runPendingAnimations() will be scheduled to be run 7394 * on the next frame. 7395 */ 7396 abstract public void runPendingAnimations(); 7397 7398 /** 7399 * Called when an item is removed from the RecyclerView. Implementors can choose 7400 * whether and how to animate that change, but must always call 7401 * {@link #dispatchRemoveFinished(ViewHolder)} when done, either 7402 * immediately (if no animation will occur) or after the animation actually finishes. 7403 * The return value indicates whether an animation has been set up and whether the 7404 * ItemAnimator's {@link #runPendingAnimations()} method should be called at the 7405 * next opportunity. This mechanism allows ItemAnimator to set up individual animations 7406 * as separate calls to {@link #animateAdd(ViewHolder) animateAdd()}, 7407 * {@link #animateMove(ViewHolder, int, int, int, int) animateMove()}, 7408 * {@link #animateRemove(ViewHolder) animateRemove()}, and 7409 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one, 7410 * then start the animations together in the later call to {@link #runPendingAnimations()}. 7411 * 7412 * <p>This method may also be called for disappearing items which continue to exist in the 7413 * RecyclerView, but for which the system does not have enough information to animate 7414 * them out of view. In that case, the default animation for removing items is run 7415 * on those items as well.</p> 7416 * 7417 * @param holder The item that is being removed. 7418 * @return true if a later call to {@link #runPendingAnimations()} is requested, 7419 * false otherwise. 7420 */ 7421 abstract public boolean animateRemove(ViewHolder holder); 7422 7423 /** 7424 * Called when an item is added to the RecyclerView. Implementors can choose 7425 * whether and how to animate that change, but must always call 7426 * {@link #dispatchAddFinished(ViewHolder)} when done, either 7427 * immediately (if no animation will occur) or after the animation actually finishes. 7428 * The return value indicates whether an animation has been set up and whether the 7429 * ItemAnimator's {@link #runPendingAnimations()} method should be called at the 7430 * next opportunity. This mechanism allows ItemAnimator to set up individual animations 7431 * as separate calls to {@link #animateAdd(ViewHolder) animateAdd()}, 7432 * {@link #animateMove(ViewHolder, int, int, int, int) animateMove()}, 7433 * {@link #animateRemove(ViewHolder) animateRemove()}, and 7434 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one, 7435 * then start the animations together in the later call to {@link #runPendingAnimations()}. 7436 * 7437 * <p>This method may also be called for appearing items which were already in the 7438 * RecyclerView, but for which the system does not have enough information to animate 7439 * them into view. In that case, the default animation for adding items is run 7440 * on those items as well.</p> 7441 * 7442 * @param holder The item that is being added. 7443 * @return true if a later call to {@link #runPendingAnimations()} is requested, 7444 * false otherwise. 7445 */ 7446 abstract public boolean animateAdd(ViewHolder holder); 7447 7448 /** 7449 * Called when an item is moved in the RecyclerView. Implementors can choose 7450 * whether and how to animate that change, but must always call 7451 * {@link #dispatchMoveFinished(ViewHolder)} when done, either 7452 * immediately (if no animation will occur) or after the animation actually finishes. 7453 * The return value indicates whether an animation has been set up and whether the 7454 * ItemAnimator's {@link #runPendingAnimations()} method should be called at the 7455 * next opportunity. This mechanism allows ItemAnimator to set up individual animations 7456 * as separate calls to {@link #animateAdd(ViewHolder) animateAdd()}, 7457 * {@link #animateMove(ViewHolder, int, int, int, int) animateMove()}, 7458 * {@link #animateRemove(ViewHolder) animateRemove()}, and 7459 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one, 7460 * then start the animations together in the later call to {@link #runPendingAnimations()}. 7461 * 7462 * @param holder The item that is being moved. 7463 * @return true if a later call to {@link #runPendingAnimations()} is requested, 7464 * false otherwise. 7465 */ 7466 abstract public boolean animateMove(ViewHolder holder, int fromX, int fromY, 7467 int toX, int toY); 7468 7469 /** 7470 * Called when an item is changed in the RecyclerView, as indicated by a call to 7471 * {@link Adapter#notifyItemChanged(int)} or 7472 * {@link Adapter#notifyItemRangeChanged(int, int)}. 7473 * <p> 7474 * Implementers can choose whether and how to animate changes, but must always call 7475 * {@link #dispatchChangeFinished(ViewHolder, boolean)} for each non-null ViewHolder, 7476 * either immediately (if no animation will occur) or after the animation actually finishes. 7477 * The return value indicates whether an animation has been set up and whether the 7478 * ItemAnimator's {@link #runPendingAnimations()} method should be called at the 7479 * next opportunity. This mechanism allows ItemAnimator to set up individual animations 7480 * as separate calls to {@link #animateAdd(ViewHolder) animateAdd()}, 7481 * {@link #animateMove(ViewHolder, int, int, int, int) animateMove()}, 7482 * {@link #animateRemove(ViewHolder) animateRemove()}, and 7483 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)} come in one by one, 7484 * then start the animations together in the later call to {@link #runPendingAnimations()}. 7485 * 7486 * @param oldHolder The original item that changed. 7487 * @param newHolder The new item that was created with the changed content. Might be null 7488 * @param fromLeft Left of the old view holder 7489 * @param fromTop Top of the old view holder 7490 * @param toLeft Left of the new view holder 7491 * @param toTop Top of the new view holder 7492 * @return true if a later call to {@link #runPendingAnimations()} is requested, 7493 * false otherwise. 7494 */ 7495 abstract public boolean animateChange(ViewHolder oldHolder, 7496 ViewHolder newHolder, int fromLeft, int fromTop, int toLeft, int toTop); 7497 7498 7499 /** 7500 * Method to be called by subclasses when a remove animation is done. 7501 * 7502 * @param item The item which has been removed 7503 */ 7504 public final void dispatchRemoveFinished(ViewHolder item) { 7505 onRemoveFinished(item); 7506 if (mListener != null) { 7507 mListener.onRemoveFinished(item); 7508 } 7509 } 7510 7511 /** 7512 * Method to be called by subclasses when a move animation is done. 7513 * 7514 * @param item The item which has been moved 7515 */ 7516 public final void dispatchMoveFinished(ViewHolder item) { 7517 onMoveFinished(item); 7518 if (mListener != null) { 7519 mListener.onMoveFinished(item); 7520 } 7521 } 7522 7523 /** 7524 * Method to be called by subclasses when an add animation is done. 7525 * 7526 * @param item The item which has been added 7527 */ 7528 public final void dispatchAddFinished(ViewHolder item) { 7529 onAddFinished(item); 7530 if (mListener != null) { 7531 mListener.onAddFinished(item); 7532 } 7533 } 7534 7535 /** 7536 * @deprecated 7537 * Use {@link #dispatchChangeFinished(ViewHolder, boolean)} 7538 */ 7539 @Deprecated 7540 public final void dispatchChangeFinished(ViewHolder item) { 7541 dispatchChangeFinished(item, true); 7542 } 7543 7544 /** 7545 * Method to be called by subclasses when a change animation is done. 7546 * 7547 * @see #animateChange(ViewHolder, ViewHolder, int, int, int, int) 7548 * @param item The item which has been changed (this method must be called for 7549 * each non-null ViewHolder passed into 7550 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)}). 7551 * @param oldItem true if this is the old item that was changed, false if 7552 * it is the new item that replaced the old item. 7553 */ 7554 public final void dispatchChangeFinished(ViewHolder item, boolean oldItem) { 7555 onChangeFinished(item, oldItem); 7556 if (mListener != null) { 7557 mListener.onChangeFinished(item); 7558 } 7559 } 7560 7561 /** 7562 * Method to be called by subclasses when a remove animation is being started. 7563 * 7564 * @param item The item being removed 7565 */ 7566 public final void dispatchRemoveStarting(ViewHolder item) { 7567 onRemoveStarting(item); 7568 } 7569 7570 /** 7571 * Method to be called by subclasses when a move animation is being started. 7572 * 7573 * @param item The item being moved 7574 */ 7575 public final void dispatchMoveStarting(ViewHolder item) { 7576 onMoveStarting(item); 7577 } 7578 7579 /** 7580 * Method to be called by subclasses when an add animation is being started. 7581 * 7582 * @param item The item being added 7583 */ 7584 public final void dispatchAddStarting(ViewHolder item) { 7585 onAddStarting(item); 7586 } 7587 7588 /** 7589 * Method to be called by subclasses when a change animation is being started. 7590 * 7591 * @param item The item which has been changed (this method must be called for 7592 * each non-null ViewHolder passed into 7593 * {@link #animateChange(ViewHolder, ViewHolder, int, int, int, int)}). 7594 * @param oldItem true if this is the old item that was changed, false if 7595 * it is the new item that replaced the old item. 7596 */ 7597 public final void dispatchChangeStarting(ViewHolder item, boolean oldItem) { 7598 onChangeStarting(item, oldItem); 7599 } 7600 7601 /** 7602 * Method called when an animation on a view should be ended immediately. 7603 * This could happen when other events, like scrolling, occur, so that 7604 * animating views can be quickly put into their proper end locations. 7605 * Implementations should ensure that any animations running on the item 7606 * are canceled and affected properties are set to their end values. 7607 * Also, appropriate dispatch methods (e.g., {@link #dispatchAddFinished(ViewHolder)} 7608 * should be called since the animations are effectively done when this 7609 * method is called. 7610 * 7611 * @param item The item for which an animation should be stopped. 7612 */ 7613 abstract public void endAnimation(ViewHolder item); 7614 7615 /** 7616 * Method called when all item animations should be ended immediately. 7617 * This could happen when other events, like scrolling, occur, so that 7618 * animating views can be quickly put into their proper end locations. 7619 * Implementations should ensure that any animations running on any items 7620 * are canceled and affected properties are set to their end values. 7621 * Also, appropriate dispatch methods (e.g., {@link #dispatchAddFinished(ViewHolder)} 7622 * should be called since the animations are effectively done when this 7623 * method is called. 7624 */ 7625 abstract public void endAnimations(); 7626 7627 /** 7628 * Method which returns whether there are any item animations currently running. 7629 * This method can be used to determine whether to delay other actions until 7630 * animations end. 7631 * 7632 * @return true if there are any item animations currently running, false otherwise. 7633 */ 7634 abstract public boolean isRunning(); 7635 7636 /** 7637 * Like {@link #isRunning()}, this method returns whether there are any item 7638 * animations currently running. Addtionally, the listener passed in will be called 7639 * when there are no item animations running, either immediately (before the method 7640 * returns) if no animations are currently running, or when the currently running 7641 * animations are {@link #dispatchAnimationsFinished() finished}. 7642 * 7643 * <p>Note that the listener is transient - it is either called immediately and not 7644 * stored at all, or stored only until it is called when running animations 7645 * are finished sometime later.</p> 7646 * 7647 * @param listener A listener to be called immediately if no animations are running 7648 * or later when currently-running animations have finished. A null listener is 7649 * equivalent to calling {@link #isRunning()}. 7650 * @return true if there are any item animations currently running, false otherwise. 7651 */ 7652 public final boolean isRunning(ItemAnimatorFinishedListener listener) { 7653 boolean running = isRunning(); 7654 if (listener != null) { 7655 if (!running) { 7656 listener.onAnimationsFinished(); 7657 } else { 7658 mFinishedListeners.add(listener); 7659 } 7660 } 7661 return running; 7662 } 7663 7664 /** 7665 * The interface to be implemented by listeners to animation events from this 7666 * ItemAnimator. This is used internally and is not intended for developers to 7667 * create directly. 7668 */ 7669 private interface ItemAnimatorListener { 7670 void onRemoveFinished(ViewHolder item); 7671 void onAddFinished(ViewHolder item); 7672 void onMoveFinished(ViewHolder item); 7673 void onChangeFinished(ViewHolder item); 7674 } 7675 7676 /** 7677 * This method should be called by ItemAnimator implementations to notify 7678 * any listeners that all pending and active item animations are finished. 7679 */ 7680 public final void dispatchAnimationsFinished() { 7681 final int count = mFinishedListeners.size(); 7682 for (int i = 0; i < count; ++i) { 7683 mFinishedListeners.get(i).onAnimationsFinished(); 7684 } 7685 mFinishedListeners.clear(); 7686 } 7687 7688 /** 7689 * This interface is used to inform listeners when all pending or running animations 7690 * in an ItemAnimator are finished. This can be used, for example, to delay an action 7691 * in a data set until currently-running animations are complete. 7692 * 7693 * @see #isRunning(ItemAnimatorFinishedListener) 7694 */ 7695 public interface ItemAnimatorFinishedListener { 7696 void onAnimationsFinished(); 7697 } 7698 7699 /** 7700 * Called when a remove animation is being started on the given ViewHolder. 7701 * The default implementation does nothing. Subclasses may wish to override 7702 * this method to handle any ViewHolder-specific operations linked to animation 7703 * lifecycles. 7704 * 7705 * @param item The ViewHolder being animated. 7706 */ 7707 public void onRemoveStarting(ViewHolder item) {} 7708 7709 /** 7710 * Called when a remove animation has ended on the given ViewHolder. 7711 * The default implementation does nothing. Subclasses may wish to override 7712 * this method to handle any ViewHolder-specific operations linked to animation 7713 * lifecycles. 7714 * 7715 * @param item The ViewHolder being animated. 7716 */ 7717 public void onRemoveFinished(ViewHolder item) {} 7718 7719 /** 7720 * Called when an add animation is being started on the given ViewHolder. 7721 * The default implementation does nothing. Subclasses may wish to override 7722 * this method to handle any ViewHolder-specific operations linked to animation 7723 * lifecycles. 7724 * 7725 * @param item The ViewHolder being animated. 7726 */ 7727 public void onAddStarting(ViewHolder item) {} 7728 7729 /** 7730 * Called when an add animation has ended on the given ViewHolder. 7731 * The default implementation does nothing. Subclasses may wish to override 7732 * this method to handle any ViewHolder-specific operations linked to animation 7733 * lifecycles. 7734 * 7735 * @param item The ViewHolder being animated. 7736 */ 7737 public void onAddFinished(ViewHolder item) {} 7738 7739 /** 7740 * Called when a move animation is being started on the given ViewHolder. 7741 * The default implementation does nothing. Subclasses may wish to override 7742 * this method to handle any ViewHolder-specific operations linked to animation 7743 * lifecycles. 7744 * 7745 * @param item The ViewHolder being animated. 7746 */ 7747 public void onMoveStarting(ViewHolder item) {} 7748 7749 /** 7750 * Called when a move animation has ended on the given ViewHolder. 7751 * The default implementation does nothing. Subclasses may wish to override 7752 * this method to handle any ViewHolder-specific operations linked to animation 7753 * lifecycles. 7754 * 7755 * @param item The ViewHolder being animated. 7756 */ 7757 public void onMoveFinished(ViewHolder item) {} 7758 7759 /** 7760 * Called when a change animation is being started on the given ViewHolder. 7761 * The default implementation does nothing. Subclasses may wish to override 7762 * this method to handle any ViewHolder-specific operations linked to animation 7763 * lifecycles. 7764 * 7765 * @param item The ViewHolder being animated. 7766 * @param oldItem true if this is the old item that was changed, false if 7767 * it is the new item that replaced the old item. 7768 */ 7769 public void onChangeStarting(ViewHolder item, boolean oldItem) {} 7770 7771 /** 7772 * Called when a change animation has ended on the given ViewHolder. 7773 * The default implementation does nothing. Subclasses may wish to override 7774 * this method to handle any ViewHolder-specific operations linked to animation 7775 * lifecycles. 7776 * 7777 * @param item The ViewHolder being animated. 7778 * @param oldItem true if this is the old item that was changed, false if 7779 * it is the new item that replaced the old item. 7780 */ 7781 public void onChangeFinished(ViewHolder item, boolean oldItem) {} 7782 7783 } 7784 7785 /** 7786 * Internal data structure that holds information about an item's bounds. 7787 * This information is used in calculating item animations. 7788 */ 7789 private static class ItemHolderInfo { 7790 ViewHolder holder; 7791 int left, top, right, bottom; 7792 7793 ItemHolderInfo(ViewHolder holder, int left, int top, int right, int bottom) { 7794 this.holder = holder; 7795 this.left = left; 7796 this.top = top; 7797 this.right = right; 7798 this.bottom = bottom; 7799 } 7800 } 7801} 7802