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