RecyclerView.java revision 43326c5ebe76a36e6b85e6165efa95eef3ffce65
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;
19import android.content.Context;
20import android.content.res.TypedArray;
21import android.database.Observable;
22import android.graphics.Canvas;
23import android.graphics.PointF;
24import android.graphics.Rect;
25import android.os.Build;
26import android.os.Bundle;
27import android.os.Parcel;
28import android.os.Parcelable;
29import android.os.SystemClock;
30import android.support.annotation.CallSuper;
31import android.support.annotation.IntDef;
32import android.support.annotation.NonNull;
33import android.support.annotation.Nullable;
34import android.support.v4.os.TraceCompat;
35import android.support.v4.view.InputDeviceCompat;
36import android.support.v4.view.MotionEventCompat;
37import android.support.v4.view.NestedScrollingChild;
38import android.support.v4.view.NestedScrollingChildHelper;
39import android.support.v4.view.ScrollingView;
40import android.support.v4.view.VelocityTrackerCompat;
41import android.support.v4.view.ViewCompat;
42import android.support.v4.view.ViewConfigurationCompat;
43import android.support.v4.view.accessibility.AccessibilityEventCompat;
44import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
45import android.support.v4.view.accessibility.AccessibilityRecordCompat;
46import android.support.v4.widget.EdgeEffectCompat;
47import android.support.v4.widget.ScrollerCompat;
48import android.support.v7.recyclerview.R;
49import android.util.AttributeSet;
50import android.util.Log;
51import android.util.SparseArray;
52import android.util.SparseIntArray;
53import android.util.TypedValue;
54import android.view.FocusFinder;
55import android.view.MotionEvent;
56import android.view.VelocityTracker;
57import android.view.View;
58import android.view.ViewConfiguration;
59import android.view.ViewGroup;
60import android.view.ViewParent;
61import android.view.accessibility.AccessibilityEvent;
62import android.view.accessibility.AccessibilityManager;
63import android.view.animation.Interpolator;
64
65import java.lang.annotation.Retention;
66import java.lang.annotation.RetentionPolicy;
67import java.lang.reflect.Constructor;
68import java.lang.reflect.InvocationTargetException;
69import java.util.ArrayList;
70import java.util.Collections;
71import java.util.List;
72
73import static android.support.v7.widget.AdapterHelper.Callback;
74import static android.support.v7.widget.AdapterHelper.UpdateOp;
75import android.support.v7.widget.RecyclerView.ItemAnimator.ItemHolderInfo;
76
77/**
78 * A flexible view for providing a limited window into a large data set.
79 *
80 * <h3>Glossary of terms:</h3>
81 *
82 * <ul>
83 *     <li><em>Adapter:</em> A subclass of {@link Adapter} responsible for providing views
84 *     that represent items in a data set.</li>
85 *     <li><em>Position:</em> The position of a data item within an <em>Adapter</em>.</li>
86 *     <li><em>Index:</em> The index of an attached child view as used in a call to
87 *     {@link ViewGroup#getChildAt}. Contrast with <em>Position.</em></li>
88 *     <li><em>Binding:</em> The process of preparing a child view to display data corresponding
89 *     to a <em>position</em> within the adapter.</li>
90 *     <li><em>Recycle (view):</em> A view previously used to display data for a specific adapter
91 *     position may be placed in a cache for later reuse to display the same type of data again
92 *     later. This can drastically improve performance by skipping initial layout inflation
93 *     or construction.</li>
94 *     <li><em>Scrap (view):</em> A child view that has entered into a temporarily detached
95 *     state during layout. Scrap views may be reused without becoming fully detached
96 *     from the parent RecyclerView, either unmodified if no rebinding is required or modified
97 *     by the adapter if the view was considered <em>dirty</em>.</li>
98 *     <li><em>Dirty (view):</em> A child view that must be rebound by the adapter before
99 *     being displayed.</li>
100 * </ul>
101 *
102 * <h4>Positions in RecyclerView:</h4>
103 * <p>
104 * RecyclerView introduces an additional level of abstraction between the {@link Adapter} and
105 * {@link LayoutManager} to be able to detect data set changes in batches during a layout
106 * calculation. This saves LayoutManager from tracking adapter changes to calculate animations.
107 * It also helps with performance because all view bindings happen at the same time and unnecessary
108 * bindings are avoided.
109 * <p>
110 * For this reason, there are two types of <code>position</code> related methods in RecyclerView:
111 * <ul>
112 *     <li>layout position: Position of an item in the latest layout calculation. This is the
113 *     position from the LayoutManager's perspective.</li>
114 *     <li>adapter position: Position of an item in the adapter. This is the position from
115 *     the Adapter's perspective.</li>
116 * </ul>
117 * <p>
118 * These two positions are the same except the time between dispatching <code>adapter.notify*
119 * </code> events and calculating the updated layout.
120 * <p>
121 * Methods that return or receive <code>*LayoutPosition*</code> use position as of the latest
122 * layout calculation (e.g. {@link ViewHolder#getLayoutPosition()},
123 * {@link #findViewHolderForLayoutPosition(int)}). These positions include all changes until the
124 * last layout calculation. You can rely on these positions to be consistent with what user is
125 * currently seeing on the screen. For example, if you have a list of items on the screen and user
126 * asks for the 5<sup>th</sup> element, you should use these methods as they'll match what user
127 * is seeing.
128 * <p>
129 * The other set of position related methods are in the form of
130 * <code>*AdapterPosition*</code>. (e.g. {@link ViewHolder#getAdapterPosition()},
131 * {@link #findViewHolderForAdapterPosition(int)}) You should use these methods when you need to
132 * work with up-to-date adapter positions even if they may not have been reflected to layout yet.
133 * For example, if you want to access the item in the adapter on a ViewHolder click, you should use
134 * {@link ViewHolder#getAdapterPosition()}. Beware that these methods may not be able to calculate
135 * adapter positions if {@link Adapter#notifyDataSetChanged()} has been called and new layout has
136 * not yet been calculated. For this reasons, you should carefully handle {@link #NO_POSITION} or
137 * <code>null</code> results from these methods.
138 * <p>
139 * When writing a {@link LayoutManager} you almost always want to use layout positions whereas when
140 * writing an {@link Adapter}, you probably want to use adapter positions.
141 *
142 * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_layoutManager
143 */
144public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild {
145
146    private static final String TAG = "RecyclerView";
147
148    private static final boolean DEBUG = false;
149
150    /**
151     * On Kitkat and JB MR2, there is a bug which prevents DisplayList from being invalidated if
152     * a View is two levels deep(wrt to ViewHolder.itemView). DisplayList can be invalidated by
153     * setting View's visibility to INVISIBLE when View is detached. On Kitkat and JB MR2, Recycler
154     * recursively traverses itemView and invalidates display list for each ViewGroup that matches
155     * this criteria.
156     */
157    private static final boolean FORCE_INVALIDATE_DISPLAY_LIST = Build.VERSION.SDK_INT == 18
158            || Build.VERSION.SDK_INT == 19 || Build.VERSION.SDK_INT == 20;
159
160    private static final boolean DISPATCH_TEMP_DETACH = false;
161    public static final int HORIZONTAL = 0;
162    public static final int VERTICAL = 1;
163
164    public static final int NO_POSITION = -1;
165    public static final long NO_ID = -1;
166    public static final int INVALID_TYPE = -1;
167
168    /**
169     * Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
170     * that the RecyclerView should use the standard touch slop for smooth,
171     * continuous scrolling.
172     */
173    public static final int TOUCH_SLOP_DEFAULT = 0;
174
175    /**
176     * Constant for use with {@link #setScrollingTouchSlop(int)}. Indicates
177     * that the RecyclerView should use the standard touch slop for scrolling
178     * widgets that snap to a page or other coarse-grained barrier.
179     */
180    public static final int TOUCH_SLOP_PAGING = 1;
181
182    private static final int MAX_SCROLL_DURATION = 2000;
183
184    /**
185     * RecyclerView is calculating a scroll.
186     * If there are too many of these in Systrace, some Views inside RecyclerView might be causing
187     * it. Try to avoid using EditText, focusable views or handle them with care.
188     */
189    private static final String TRACE_SCROLL_TAG = "RV Scroll";
190
191    /**
192     * OnLayout has been called by the View system.
193     * If this shows up too many times in Systrace, make sure the children of RecyclerView do not
194     * update themselves directly. This will cause a full re-layout but when it happens via the
195     * Adapter notifyItemChanged, RecyclerView can avoid full layout calculation.
196     */
197    private static final String TRACE_ON_LAYOUT_TAG = "RV OnLayout";
198
199    /**
200     * NotifyDataSetChanged or equal has been called.
201     * If this is taking a long time, try sending granular notify adapter changes instead of just
202     * calling notifyDataSetChanged or setAdapter / swapAdapter. Adding stable ids to your adapter
203     * might help.
204     */
205    private static final String TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG = "RV FullInvalidate";
206
207    /**
208     * RecyclerView is doing a layout for partial adapter updates (we know what has changed)
209     * If this is taking a long time, you may have dispatched too many Adapter updates causing too
210     * many Views being rebind. Make sure all are necessary and also prefer using notify*Range
211     * methods.
212     */
213    private static final String TRACE_HANDLE_ADAPTER_UPDATES_TAG = "RV PartialInvalidate";
214
215    /**
216     * RecyclerView is rebinding a View.
217     * If this is taking a lot of time, consider optimizing your layout or make sure you are not
218     * doing extra operations in onBindViewHolder call.
219     */
220    private static final String TRACE_BIND_VIEW_TAG = "RV OnBindView";
221
222    /**
223     * RecyclerView is creating a new View.
224     * If too many of these present in Systrace:
225     * - There might be a problem in Recycling (e.g. custom Animations that set transient state and
226     * prevent recycling or ItemAnimator not implementing the contract properly. ({@link
227     * > Adapter#onFailedToRecycleView(ViewHolder)})
228     *
229     * - There might be too many item view types.
230     * > Try merging them
231     *
232     * - There might be too many itemChange animations and not enough space in RecyclerPool.
233     * >Try increasing your pool size and item cache size.
234     */
235    private static final String TRACE_CREATE_VIEW_TAG = "RV CreateView";
236    private static final Class<?>[] LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE =
237            new Class[]{Context.class, AttributeSet.class, int.class, int.class};
238
239    private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver();
240
241    final Recycler mRecycler = new Recycler();
242
243    private SavedState mPendingSavedState;
244
245    /**
246     * Handles adapter updates
247     */
248    AdapterHelper mAdapterHelper;
249
250    /**
251     * Handles abstraction between LayoutManager children and RecyclerView children
252     */
253    ChildHelper mChildHelper;
254
255    /**
256     * Keeps data about views to be used for animations
257     */
258    final ViewInfoStore mViewInfoStore = new ViewInfoStore();
259
260    /**
261     * Prior to L, there is no way to query this variable which is why we override the setter and
262     * track it here.
263     */
264    private boolean mClipToPadding;
265
266    /**
267     * Note: this Runnable is only ever posted if:
268     * 1) We've been through first layout
269     * 2) We know we have a fixed size (mHasFixedSize)
270     * 3) We're attached
271     */
272    private final Runnable mUpdateChildViewsRunnable = new Runnable() {
273        public void run() {
274            if (!mFirstLayoutComplete || isLayoutRequested()) {
275                // a layout request will happen, we should not do layout here.
276                return;
277            }
278            if (mLayoutFrozen) {
279                mLayoutRequestEaten = true;
280                return; //we'll process updates when ice age ends.
281            }
282            consumePendingUpdateOperations();
283        }
284    };
285
286    private final Rect mTempRect = new Rect();
287    private Adapter mAdapter;
288    private LayoutManager mLayout;
289    private RecyclerListener mRecyclerListener;
290    private final ArrayList<ItemDecoration> mItemDecorations = new ArrayList<ItemDecoration>();
291    private final ArrayList<OnItemTouchListener> mOnItemTouchListeners =
292            new ArrayList<OnItemTouchListener>();
293    private OnItemTouchListener mActiveOnItemTouchListener;
294    private boolean mIsAttached;
295    private boolean mHasFixedSize;
296    private boolean mFirstLayoutComplete;
297    private boolean mEatRequestLayout;
298    private boolean mLayoutRequestEaten;
299    private boolean mLayoutFrozen;
300    private boolean mIgnoreMotionEventTillDown;
301
302    // binary OR of change events that were eaten during a layout or scroll.
303    private int mEatenAccessibilityChangeFlags;
304    private boolean mAdapterUpdateDuringMeasure;
305    private final boolean mPostUpdatesOnAnimation;
306    private final AccessibilityManager mAccessibilityManager;
307    private List<OnChildAttachStateChangeListener> mOnChildAttachStateListeners;
308
309    /**
310     * Set to true when an adapter data set changed notification is received.
311     * In that case, we cannot run any animations since we don't know what happened.
312     */
313    private boolean mDataSetHasChangedAfterLayout = false;
314
315    /**
316     * This variable is incremented during a dispatchLayout and/or scroll.
317     * Some methods should not be called during these periods (e.g. adapter data change).
318     * Doing so will create hard to find bugs so we better check it and throw an exception.
319     *
320     * @see #assertInLayoutOrScroll(String)
321     * @see #assertNotInLayoutOrScroll(String)
322     */
323    private int mLayoutOrScrollCounter = 0;
324
325    private EdgeEffectCompat mLeftGlow, mTopGlow, mRightGlow, mBottomGlow;
326
327    ItemAnimator mItemAnimator = new DefaultItemAnimator();
328
329    private static final int INVALID_POINTER = -1;
330
331    /**
332     * The RecyclerView is not currently scrolling.
333     * @see #getScrollState()
334     */
335    public static final int SCROLL_STATE_IDLE = 0;
336
337    /**
338     * The RecyclerView is currently being dragged by outside input such as user touch input.
339     * @see #getScrollState()
340     */
341    public static final int SCROLL_STATE_DRAGGING = 1;
342
343    /**
344     * The RecyclerView is currently animating to a final position while not under
345     * outside control.
346     * @see #getScrollState()
347     */
348    public static final int SCROLL_STATE_SETTLING = 2;
349
350    // Touch/scrolling handling
351
352    private int mScrollState = SCROLL_STATE_IDLE;
353    private int mScrollPointerId = INVALID_POINTER;
354    private VelocityTracker mVelocityTracker;
355    private int mInitialTouchX;
356    private int mInitialTouchY;
357    private int mLastTouchX;
358    private int mLastTouchY;
359    private int mTouchSlop;
360    private final int mMinFlingVelocity;
361    private final int mMaxFlingVelocity;
362    // This value is used when handling generic motion events.
363    private float mScrollFactor = Float.MIN_VALUE;
364
365    private final ViewFlinger mViewFlinger = new ViewFlinger();
366
367    final State mState = new State();
368
369    private OnScrollListener mScrollListener;
370    private List<OnScrollListener> mScrollListeners;
371
372    // For use in item animations
373    boolean mItemsAddedOrRemoved = false;
374    boolean mItemsChanged = false;
375    private ItemAnimator.ItemAnimatorListener mItemAnimatorListener =
376            new ItemAnimatorRestoreListener();
377    private boolean mPostedAnimatorRunner = false;
378    private RecyclerViewAccessibilityDelegate mAccessibilityDelegate;
379    private ChildDrawingOrderCallback mChildDrawingOrderCallback;
380
381    // simple array to keep min and max child position during a layout calculation
382    // preserved not to create a new one in each layout pass
383    private final int[] mMinMaxLayoutPositions = new int[2];
384
385    private final NestedScrollingChildHelper mScrollingChildHelper;
386    private final int[] mScrollOffset = new int[2];
387    private final int[] mScrollConsumed = new int[2];
388    private final int[] mNestedOffsets = new int[2];
389
390    private Runnable mItemAnimatorRunner = new Runnable() {
391        @Override
392        public void run() {
393            if (mItemAnimator != null) {
394                mItemAnimator.runPendingAnimations();
395            }
396            mPostedAnimatorRunner = false;
397        }
398    };
399
400    private static final Interpolator sQuinticInterpolator = new Interpolator() {
401        public float getInterpolation(float t) {
402            t -= 1.0f;
403            return t * t * t * t * t + 1.0f;
404        }
405    };
406
407    /**
408     * The callback to convert view info diffs into animations.
409     */
410    private final ViewInfoStore.ProcessCallback mViewInfoProcessCallback =
411            new ViewInfoStore.ProcessCallback() {
412        @Override
413        public void processDisappeared(ViewHolder viewHolder, ItemHolderInfo info,
414                ItemHolderInfo postInfo) {
415            mRecycler.unscrapView(viewHolder);
416            animateDisappearance(viewHolder, info, postInfo);
417        }
418        @Override
419        public void processAppeared(ViewHolder viewHolder,
420                ItemHolderInfo preInfo, ItemHolderInfo info) {
421            animateAppearance(viewHolder, preInfo, info);
422        }
423
424        @Override
425        public void processPersistent(ViewHolder viewHolder,
426                @NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo) {
427            viewHolder.setIsRecyclable(false);
428            if (mDataSetHasChangedAfterLayout) {
429                // since it was rebound, use change instead as we'll be mapping them from
430                // stable ids. If stable ids were false, we would not be running any
431                // animations
432                if (mItemAnimator.animateChange(viewHolder, viewHolder, preInfo, postInfo)) {
433                    postAnimationRunner();
434                }
435            } else if (mItemAnimator.animatePersistence(viewHolder, preInfo, postInfo)) {
436                postAnimationRunner();
437            }
438        }
439        @Override
440        public void unused(ViewHolder viewHolder) {
441            mLayout.removeAndRecycleView(viewHolder.itemView, mRecycler);
442        }
443    };
444
445    public RecyclerView(Context context) {
446        this(context, null);
447    }
448
449    public RecyclerView(Context context, @Nullable AttributeSet attrs) {
450        this(context, attrs, 0);
451    }
452
453    public RecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
454        super(context, attrs, defStyle);
455        setScrollContainer(true);
456        setFocusableInTouchMode(true);
457        final int version = Build.VERSION.SDK_INT;
458        mPostUpdatesOnAnimation = version >= 16;
459
460        final ViewConfiguration vc = ViewConfiguration.get(context);
461        mTouchSlop = vc.getScaledTouchSlop();
462        mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
463        mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
464        setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
465
466        mItemAnimator.setListener(mItemAnimatorListener);
467        initAdapterManager();
468        initChildrenHelper();
469        // If not explicitly specified this view is important for accessibility.
470        if (ViewCompat.getImportantForAccessibility(this)
471                == ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
472            ViewCompat.setImportantForAccessibility(this,
473                    ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
474        }
475        mAccessibilityManager = (AccessibilityManager) getContext()
476                .getSystemService(Context.ACCESSIBILITY_SERVICE);
477        setAccessibilityDelegateCompat(new RecyclerViewAccessibilityDelegate(this));
478        // Create the layoutManager if specified.
479        if (attrs != null) {
480            int defStyleRes = 0;
481            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView,
482                    defStyle, defStyleRes);
483            String layoutManagerName = a.getString(R.styleable.RecyclerView_layoutManager);
484            a.recycle();
485            createLayoutManager(context, layoutManagerName, attrs, defStyle, defStyleRes);
486        }
487
488        mScrollingChildHelper = new NestedScrollingChildHelper(this);
489        setNestedScrollingEnabled(true);
490    }
491
492    /**
493     * Returns the accessibility delegate compatibility implementation used by the RecyclerView.
494     * @return An instance of AccessibilityDelegateCompat used by RecyclerView
495     */
496    public RecyclerViewAccessibilityDelegate getCompatAccessibilityDelegate() {
497        return mAccessibilityDelegate;
498    }
499
500    /**
501     * Sets the accessibility delegate compatibility implementation used by RecyclerView.
502     * @param accessibilityDelegate The accessibility delegate to be used by RecyclerView.
503     */
504    public void setAccessibilityDelegateCompat(
505            RecyclerViewAccessibilityDelegate accessibilityDelegate) {
506        mAccessibilityDelegate = accessibilityDelegate;
507        ViewCompat.setAccessibilityDelegate(this, mAccessibilityDelegate);
508    }
509
510    /**
511     * Instantiate and set a LayoutManager, if specified in the attributes.
512     */
513    private void createLayoutManager(Context context, String className, AttributeSet attrs,
514            int defStyleAttr, int defStyleRes) {
515        if (className != null) {
516            className = className.trim();
517            if (className.length() != 0) {  // Can't use isEmpty since it was added in API 9.
518                className = getFullClassName(context, className);
519                try {
520                    ClassLoader classLoader;
521                    if (isInEditMode()) {
522                        // Stupid layoutlib cannot handle simple class loaders.
523                        classLoader = this.getClass().getClassLoader();
524                    } else {
525                        classLoader = context.getClassLoader();
526                    }
527                    Class<? extends LayoutManager> layoutManagerClass =
528                            classLoader.loadClass(className).asSubclass(LayoutManager.class);
529                    Constructor<? extends LayoutManager> constructor;
530                    Object[] constructorArgs = null;
531                    try {
532                        constructor = layoutManagerClass
533                                .getConstructor(LAYOUT_MANAGER_CONSTRUCTOR_SIGNATURE);
534                        constructorArgs = new Object[]{context, attrs, defStyleAttr, defStyleRes};
535                    } catch (NoSuchMethodException e) {
536                        try {
537                            constructor = layoutManagerClass.getConstructor();
538                        } catch (NoSuchMethodException e1) {
539                            e1.initCause(e);
540                            throw new IllegalStateException(attrs.getPositionDescription() +
541                                    ": Error creating LayoutManager " + className, e1);
542                        }
543                    }
544                    constructor.setAccessible(true);
545                    setLayoutManager(constructor.newInstance(constructorArgs));
546                } catch (ClassNotFoundException e) {
547                    throw new IllegalStateException(attrs.getPositionDescription()
548                            + ": Unable to find LayoutManager " + className, e);
549                } catch (InvocationTargetException e) {
550                    throw new IllegalStateException(attrs.getPositionDescription()
551                            + ": Could not instantiate the LayoutManager: " + className, e);
552                } catch (InstantiationException e) {
553                    throw new IllegalStateException(attrs.getPositionDescription()
554                            + ": Could not instantiate the LayoutManager: " + className, e);
555                } catch (IllegalAccessException e) {
556                    throw new IllegalStateException(attrs.getPositionDescription()
557                            + ": Cannot access non-public constructor " + className, e);
558                } catch (ClassCastException e) {
559                    throw new IllegalStateException(attrs.getPositionDescription()
560                            + ": Class is not a LayoutManager " + className, e);
561                }
562            }
563        }
564    }
565
566    private String getFullClassName(Context context, String className) {
567        if (className.charAt(0) == '.') {
568            return context.getPackageName() + className;
569        }
570        if (className.contains(".")) {
571            return className;
572        }
573        return RecyclerView.class.getPackage().getName() + '.' + className;
574    }
575
576    private void initChildrenHelper() {
577        mChildHelper = new ChildHelper(new ChildHelper.Callback() {
578            @Override
579            public int getChildCount() {
580                return RecyclerView.this.getChildCount();
581            }
582
583            @Override
584            public void addView(View child, int index) {
585                RecyclerView.this.addView(child, index);
586                dispatchChildAttached(child);
587            }
588
589            @Override
590            public int indexOfChild(View view) {
591                return RecyclerView.this.indexOfChild(view);
592            }
593
594            @Override
595            public void removeViewAt(int index) {
596                final View child = RecyclerView.this.getChildAt(index);
597                if (child != null) {
598                    dispatchChildDetached(child);
599                }
600                RecyclerView.this.removeViewAt(index);
601            }
602
603            @Override
604            public View getChildAt(int offset) {
605                return RecyclerView.this.getChildAt(offset);
606            }
607
608            @Override
609            public void removeAllViews() {
610                final int count = getChildCount();
611                for (int i = 0; i < count; i ++) {
612                    dispatchChildDetached(getChildAt(i));
613                }
614                RecyclerView.this.removeAllViews();
615            }
616
617            @Override
618            public ViewHolder getChildViewHolder(View view) {
619                return getChildViewHolderInt(view);
620            }
621
622            @Override
623            public void attachViewToParent(View child, int index,
624                    ViewGroup.LayoutParams layoutParams) {
625                final ViewHolder vh = getChildViewHolderInt(child);
626                if (vh != null) {
627                    if (!vh.isTmpDetached() && !vh.shouldIgnore()) {
628                        throw new IllegalArgumentException("Called attach on a child which is not"
629                                + " detached: " + vh);
630                    }
631                    if (DEBUG) {
632                        Log.d(TAG, "reAttach " + vh);
633                    }
634                    vh.clearTmpDetachFlag();
635                }
636                RecyclerView.this.attachViewToParent(child, index, layoutParams);
637            }
638
639            @Override
640            public void detachViewFromParent(int offset) {
641                final View view = getChildAt(offset);
642                if (view != null) {
643                    final ViewHolder vh = getChildViewHolderInt(view);
644                    if (vh != null) {
645                        if (vh.isTmpDetached() && !vh.shouldIgnore()) {
646                            throw new IllegalArgumentException("called detach on an already"
647                                    + " detached child " + vh);
648                        }
649                        if (DEBUG) {
650                            Log.d(TAG, "tmpDetach " + vh);
651                        }
652                        vh.addFlags(ViewHolder.FLAG_TMP_DETACHED);
653                    }
654                }
655                RecyclerView.this.detachViewFromParent(offset);
656            }
657
658            @Override
659            public void onEnteredHiddenState(View child) {
660                final ViewHolder vh = getChildViewHolderInt(child);
661                if (vh != null) {
662                    vh.onEnteredHiddenState();
663                }
664            }
665
666            @Override
667            public void onLeftHiddenState(View child) {
668                final ViewHolder vh = getChildViewHolderInt(child);
669                if (vh != null) {
670                    vh.onLeftHiddenState();
671                }
672            }
673        });
674    }
675
676    void initAdapterManager() {
677        mAdapterHelper = new AdapterHelper(new Callback() {
678            @Override
679            public ViewHolder findViewHolder(int position) {
680                final ViewHolder vh = findViewHolderForPosition(position, true);
681                if (vh == null) {
682                    return null;
683                }
684                // ensure it is not hidden because for adapter helper, the only thing matter is that
685                // LM thinks view is a child.
686                if (mChildHelper.isHidden(vh.itemView)) {
687                    if (DEBUG) {
688                        Log.d(TAG, "assuming view holder cannot be find because it is hidden");
689                    }
690                    return null;
691                }
692                return vh;
693            }
694
695            @Override
696            public void offsetPositionsForRemovingInvisible(int start, int count) {
697                offsetPositionRecordsForRemove(start, count, true);
698                mItemsAddedOrRemoved = true;
699                mState.mDeletedInvisibleItemCountSincePreviousLayout += count;
700            }
701
702            @Override
703            public void offsetPositionsForRemovingLaidOutOrNewView(int positionStart, int itemCount) {
704                offsetPositionRecordsForRemove(positionStart, itemCount, false);
705                mItemsAddedOrRemoved = true;
706            }
707
708            @Override
709            public void markViewHoldersUpdated(int positionStart, int itemCount, Object payload) {
710                viewRangeUpdate(positionStart, itemCount, payload);
711                mItemsChanged = true;
712            }
713
714            @Override
715            public void onDispatchFirstPass(UpdateOp op) {
716                dispatchUpdate(op);
717            }
718
719            void dispatchUpdate(UpdateOp op) {
720                switch (op.cmd) {
721                    case UpdateOp.ADD:
722                        mLayout.onItemsAdded(RecyclerView.this, op.positionStart, op.itemCount);
723                        break;
724                    case UpdateOp.REMOVE:
725                        mLayout.onItemsRemoved(RecyclerView.this, op.positionStart, op.itemCount);
726                        break;
727                    case UpdateOp.UPDATE:
728                        mLayout.onItemsUpdated(RecyclerView.this, op.positionStart, op.itemCount,
729                                op.payload);
730                        break;
731                    case UpdateOp.MOVE:
732                        mLayout.onItemsMoved(RecyclerView.this, op.positionStart, op.itemCount, 1);
733                        break;
734                }
735            }
736
737            @Override
738            public void onDispatchSecondPass(UpdateOp op) {
739                dispatchUpdate(op);
740            }
741
742            @Override
743            public void offsetPositionsForAdd(int positionStart, int itemCount) {
744                offsetPositionRecordsForInsert(positionStart, itemCount);
745                mItemsAddedOrRemoved = true;
746            }
747
748            @Override
749            public void offsetPositionsForMove(int from, int to) {
750                offsetPositionRecordsForMove(from, to);
751                // should we create mItemsMoved ?
752                mItemsAddedOrRemoved = true;
753            }
754        });
755    }
756
757    /**
758     * RecyclerView can perform several optimizations if it can know in advance that changes in
759     * adapter content cannot change the size of the RecyclerView itself.
760     * If your use of RecyclerView falls into this category, set this to true.
761     *
762     * @param hasFixedSize true if adapter changes cannot affect the size of the RecyclerView.
763     */
764    public void setHasFixedSize(boolean hasFixedSize) {
765        mHasFixedSize = hasFixedSize;
766    }
767
768    /**
769     * @return true if the app has specified that changes in adapter content cannot change
770     * the size of the RecyclerView itself.
771     */
772    public boolean hasFixedSize() {
773        return mHasFixedSize;
774    }
775
776    @Override
777    public void setClipToPadding(boolean clipToPadding) {
778        if (clipToPadding != mClipToPadding) {
779            invalidateGlows();
780        }
781        mClipToPadding = clipToPadding;
782        super.setClipToPadding(clipToPadding);
783        if (mFirstLayoutComplete) {
784            requestLayout();
785        }
786    }
787
788    /**
789     * Configure the scrolling touch slop for a specific use case.
790     *
791     * Set up the RecyclerView's scrolling motion threshold based on common usages.
792     * Valid arguments are {@link #TOUCH_SLOP_DEFAULT} and {@link #TOUCH_SLOP_PAGING}.
793     *
794     * @param slopConstant One of the <code>TOUCH_SLOP_</code> constants representing
795     *                     the intended usage of this RecyclerView
796     */
797    public void setScrollingTouchSlop(int slopConstant) {
798        final ViewConfiguration vc = ViewConfiguration.get(getContext());
799        switch (slopConstant) {
800            default:
801                Log.w(TAG, "setScrollingTouchSlop(): bad argument constant "
802                      + slopConstant + "; using default value");
803                // fall-through
804            case TOUCH_SLOP_DEFAULT:
805                mTouchSlop = vc.getScaledTouchSlop();
806                break;
807
808            case TOUCH_SLOP_PAGING:
809                mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(vc);
810                break;
811        }
812    }
813
814    /**
815     * Swaps the current adapter with the provided one. It is similar to
816     * {@link #setAdapter(Adapter)} but assumes existing adapter and the new adapter uses the same
817     * {@link ViewHolder} and does not clear the RecycledViewPool.
818     * <p>
819     * Note that it still calls onAdapterChanged callbacks.
820     *
821     * @param adapter The new adapter to set, or null to set no adapter.
822     * @param removeAndRecycleExistingViews If set to true, RecyclerView will recycle all existing
823     *                                      Views. If adapters have stable ids and/or you want to
824     *                                      animate the disappearing views, you may prefer to set
825     *                                      this to false.
826     * @see #setAdapter(Adapter)
827     */
828    public void swapAdapter(Adapter adapter, boolean removeAndRecycleExistingViews) {
829        // bail out if layout is frozen
830        setLayoutFrozen(false);
831        setAdapterInternal(adapter, true, removeAndRecycleExistingViews);
832        setDataSetChangedAfterLayout();
833        requestLayout();
834    }
835    /**
836     * Set a new adapter to provide child views on demand.
837     * <p>
838     * When adapter is changed, all existing views are recycled back to the pool. If the pool has
839     * only one adapter, it will be cleared.
840     *
841     * @param adapter The new adapter to set, or null to set no adapter.
842     * @see #swapAdapter(Adapter, boolean)
843     */
844    public void setAdapter(Adapter adapter) {
845        // bail out if layout is frozen
846        setLayoutFrozen(false);
847        setAdapterInternal(adapter, false, true);
848        requestLayout();
849    }
850
851    /**
852     * Replaces the current adapter with the new one and triggers listeners.
853     * @param adapter The new adapter
854     * @param compatibleWithPrevious If true, the new adapter is using the same View Holders and
855     *                               item types with the current adapter (helps us avoid cache
856     *                               invalidation).
857     * @param removeAndRecycleViews  If true, we'll remove and recycle all existing views. If
858     *                               compatibleWithPrevious is false, this parameter is ignored.
859     */
860    private void setAdapterInternal(Adapter adapter, boolean compatibleWithPrevious,
861            boolean removeAndRecycleViews) {
862        if (mAdapter != null) {
863            mAdapter.unregisterAdapterDataObserver(mObserver);
864            mAdapter.onDetachedFromRecyclerView(this);
865        }
866        if (!compatibleWithPrevious || removeAndRecycleViews) {
867            // end all running animations
868            if (mItemAnimator != null) {
869                mItemAnimator.endAnimations();
870            }
871            // Since animations are ended, mLayout.children should be equal to
872            // recyclerView.children. This may not be true if item animator's end does not work as
873            // expected. (e.g. not release children instantly). It is safer to use mLayout's child
874            // count.
875            if (mLayout != null) {
876                mLayout.removeAndRecycleAllViews(mRecycler);
877                mLayout.removeAndRecycleScrapInt(mRecycler);
878            }
879            // we should clear it here before adapters are swapped to ensure correct callbacks.
880            mRecycler.clear();
881        }
882        mAdapterHelper.reset();
883        final Adapter oldAdapter = mAdapter;
884        mAdapter = adapter;
885        if (adapter != null) {
886            adapter.registerAdapterDataObserver(mObserver);
887            adapter.onAttachedToRecyclerView(this);
888        }
889        if (mLayout != null) {
890            mLayout.onAdapterChanged(oldAdapter, mAdapter);
891        }
892        mRecycler.onAdapterChanged(oldAdapter, mAdapter, compatibleWithPrevious);
893        mState.mStructureChanged = true;
894        markKnownViewsInvalid();
895    }
896
897    /**
898     * Retrieves the previously set adapter or null if no adapter is set.
899     *
900     * @return The previously set adapter
901     * @see #setAdapter(Adapter)
902     */
903    public Adapter getAdapter() {
904        return mAdapter;
905    }
906
907    /**
908     * Register a listener that will be notified whenever a child view is recycled.
909     *
910     * <p>This listener will be called when a LayoutManager or the RecyclerView decides
911     * that a child view is no longer needed. If an application associates expensive
912     * or heavyweight data with item views, this may be a good place to release
913     * or free those resources.</p>
914     *
915     * @param listener Listener to register, or null to clear
916     */
917    public void setRecyclerListener(RecyclerListener listener) {
918        mRecyclerListener = listener;
919    }
920
921    /**
922     * <p>Return the offset of the RecyclerView's text baseline from the its top
923     * boundary. If the LayoutManager of this RecyclerView does not support baseline alignment,
924     * this method returns -1.</p>
925     *
926     * @return the offset of the baseline within the RecyclerView's bounds or -1
927     *         if baseline alignment is not supported
928     */
929    @Override
930    public int getBaseline() {
931        if (mLayout != null) {
932            return mLayout.getBaseline();
933        } else {
934            return super.getBaseline();
935        }
936    }
937
938    /**
939     * Register a listener that will be notified whenever a child view is attached to or detached
940     * from RecyclerView.
941     *
942     * <p>This listener will be called when a LayoutManager or the RecyclerView decides
943     * that a child view is no longer needed. If an application associates expensive
944     * or heavyweight data with item views, this may be a good place to release
945     * or free those resources.</p>
946     *
947     * @param listener Listener to register
948     */
949    public void addOnChildAttachStateChangeListener(OnChildAttachStateChangeListener listener) {
950        if (mOnChildAttachStateListeners == null) {
951            mOnChildAttachStateListeners = new ArrayList<OnChildAttachStateChangeListener>();
952        }
953        mOnChildAttachStateListeners.add(listener);
954    }
955
956    /**
957     * Removes the provided listener from child attached state listeners list.
958     *
959     * @param listener Listener to unregister
960     */
961    public void removeOnChildAttachStateChangeListener(OnChildAttachStateChangeListener listener) {
962        if (mOnChildAttachStateListeners == null) {
963            return;
964        }
965        mOnChildAttachStateListeners.remove(listener);
966    }
967
968    /**
969     * Removes all listeners that were added via
970     * {@link #addOnChildAttachStateChangeListener(OnChildAttachStateChangeListener)}.
971     */
972    public void clearOnChildAttachStateChangeListeners() {
973        if (mOnChildAttachStateListeners != null) {
974            mOnChildAttachStateListeners.clear();
975        }
976    }
977
978    /**
979     * Set the {@link LayoutManager} that this RecyclerView will use.
980     *
981     * <p>In contrast to other adapter-backed views such as {@link android.widget.ListView}
982     * or {@link android.widget.GridView}, RecyclerView allows client code to provide custom
983     * layout arrangements for child views. These arrangements are controlled by the
984     * {@link LayoutManager}. A LayoutManager must be provided for RecyclerView to function.</p>
985     *
986     * <p>Several default strategies are provided for common uses such as lists and grids.</p>
987     *
988     * @param layout LayoutManager to use
989     */
990    public void setLayoutManager(LayoutManager layout) {
991        if (layout == mLayout) {
992            return;
993        }
994        // TODO We should do this switch a dispachLayout pass and animate children. There is a good
995        // chance that LayoutManagers will re-use views.
996        if (mLayout != null) {
997            if (mIsAttached) {
998                mLayout.dispatchDetachedFromWindow(this, mRecycler);
999            }
1000            mLayout.setRecyclerView(null);
1001        }
1002        mRecycler.clear();
1003        mChildHelper.removeAllViewsUnfiltered();
1004        mLayout = layout;
1005        if (layout != null) {
1006            if (layout.mRecyclerView != null) {
1007                throw new IllegalArgumentException("LayoutManager " + layout +
1008                        " is already attached to a RecyclerView: " + layout.mRecyclerView);
1009            }
1010            mLayout.setRecyclerView(this);
1011            if (mIsAttached) {
1012                mLayout.dispatchAttachedToWindow(this);
1013            }
1014        }
1015        requestLayout();
1016    }
1017
1018    @Override
1019    protected Parcelable onSaveInstanceState() {
1020        SavedState state = new SavedState(super.onSaveInstanceState());
1021        if (mPendingSavedState != null) {
1022            state.copyFrom(mPendingSavedState);
1023        } else if (mLayout != null) {
1024            state.mLayoutState = mLayout.onSaveInstanceState();
1025        } else {
1026            state.mLayoutState = null;
1027        }
1028
1029        return state;
1030    }
1031
1032    @Override
1033    protected void onRestoreInstanceState(Parcelable state) {
1034        mPendingSavedState = (SavedState) state;
1035        super.onRestoreInstanceState(mPendingSavedState.getSuperState());
1036        if (mLayout != null && mPendingSavedState.mLayoutState != null) {
1037            mLayout.onRestoreInstanceState(mPendingSavedState.mLayoutState);
1038        }
1039    }
1040
1041    /**
1042     * Override to prevent freezing of any views created by the adapter.
1043     */
1044    @Override
1045    protected void dispatchSaveInstanceState(SparseArray<Parcelable> container) {
1046        dispatchFreezeSelfOnly(container);
1047    }
1048
1049    /**
1050     * Override to prevent thawing of any views created by the adapter.
1051     */
1052    @Override
1053    protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) {
1054        dispatchThawSelfOnly(container);
1055    }
1056
1057    /**
1058     * Adds a view to the animatingViews list.
1059     * mAnimatingViews holds the child views that are currently being kept around
1060     * purely for the purpose of being animated out of view. They are drawn as a regular
1061     * part of the child list of the RecyclerView, but they are invisible to the LayoutManager
1062     * as they are managed separately from the regular child views.
1063     * @param viewHolder The ViewHolder to be removed
1064     */
1065    private void addAnimatingView(ViewHolder viewHolder) {
1066        final View view = viewHolder.itemView;
1067        final boolean alreadyParented = view.getParent() == this;
1068        mRecycler.unscrapView(getChildViewHolder(view));
1069        if (viewHolder.isTmpDetached()) {
1070            // re-attach
1071            mChildHelper.attachViewToParent(view, -1, view.getLayoutParams(), true);
1072        } else if(!alreadyParented) {
1073            mChildHelper.addView(view, true);
1074        } else {
1075            mChildHelper.hide(view);
1076        }
1077    }
1078
1079    /**
1080     * Removes a view from the animatingViews list.
1081     * @param view The view to be removed
1082     * @see #addAnimatingView(RecyclerView.ViewHolder)
1083     * @return true if an animating view is removed
1084     */
1085    private boolean removeAnimatingView(View view) {
1086        eatRequestLayout();
1087        final boolean removed = mChildHelper.removeViewIfHidden(view);
1088        if (removed) {
1089            final ViewHolder viewHolder = getChildViewHolderInt(view);
1090            mRecycler.unscrapView(viewHolder);
1091            mRecycler.recycleViewHolderInternal(viewHolder);
1092            if (DEBUG) {
1093                Log.d(TAG, "after removing animated view: " + view + ", " + this);
1094            }
1095        }
1096        resumeRequestLayout(false);
1097        return removed;
1098    }
1099
1100    /**
1101     * Return the {@link LayoutManager} currently responsible for
1102     * layout policy for this RecyclerView.
1103     *
1104     * @return The currently bound LayoutManager
1105     */
1106    public LayoutManager getLayoutManager() {
1107        return mLayout;
1108    }
1109
1110    /**
1111     * Retrieve this RecyclerView's {@link RecycledViewPool}. This method will never return null;
1112     * if no pool is set for this view a new one will be created. See
1113     * {@link #setRecycledViewPool(RecycledViewPool) setRecycledViewPool} for more information.
1114     *
1115     * @return The pool used to store recycled item views for reuse.
1116     * @see #setRecycledViewPool(RecycledViewPool)
1117     */
1118    public RecycledViewPool getRecycledViewPool() {
1119        return mRecycler.getRecycledViewPool();
1120    }
1121
1122    /**
1123     * Recycled view pools allow multiple RecyclerViews to share a common pool of scrap views.
1124     * This can be useful if you have multiple RecyclerViews with adapters that use the same
1125     * view types, for example if you have several data sets with the same kinds of item views
1126     * displayed by a {@link android.support.v4.view.ViewPager ViewPager}.
1127     *
1128     * @param pool Pool to set. If this parameter is null a new pool will be created and used.
1129     */
1130    public void setRecycledViewPool(RecycledViewPool pool) {
1131        mRecycler.setRecycledViewPool(pool);
1132    }
1133
1134    /**
1135     * Sets a new {@link ViewCacheExtension} to be used by the Recycler.
1136     *
1137     * @param extension ViewCacheExtension to be used or null if you want to clear the existing one.
1138     *
1139     * @see {@link ViewCacheExtension#getViewForPositionAndType(Recycler, int, int)}
1140     */
1141    public void setViewCacheExtension(ViewCacheExtension extension) {
1142        mRecycler.setViewCacheExtension(extension);
1143    }
1144
1145    /**
1146     * Set the number of offscreen views to retain before adding them to the potentially shared
1147     * {@link #getRecycledViewPool() recycled view pool}.
1148     *
1149     * <p>The offscreen view cache stays aware of changes in the attached adapter, allowing
1150     * a LayoutManager to reuse those views unmodified without needing to return to the adapter
1151     * to rebind them.</p>
1152     *
1153     * @param size Number of views to cache offscreen before returning them to the general
1154     *             recycled view pool
1155     */
1156    public void setItemViewCacheSize(int size) {
1157        mRecycler.setViewCacheSize(size);
1158    }
1159
1160    /**
1161     * Return the current scrolling state of the RecyclerView.
1162     *
1163     * @return {@link #SCROLL_STATE_IDLE}, {@link #SCROLL_STATE_DRAGGING} or
1164     * {@link #SCROLL_STATE_SETTLING}
1165     */
1166    public int getScrollState() {
1167        return mScrollState;
1168    }
1169
1170    private void setScrollState(int state) {
1171        if (state == mScrollState) {
1172            return;
1173        }
1174        if (DEBUG) {
1175            Log.d(TAG, "setting scroll state to " + state + " from " + mScrollState,
1176                    new Exception());
1177        }
1178        mScrollState = state;
1179        if (state != SCROLL_STATE_SETTLING) {
1180            stopScrollersInternal();
1181        }
1182        dispatchOnScrollStateChanged(state);
1183    }
1184
1185    /**
1186     * Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
1187     * affect both measurement and drawing of individual item views.
1188     *
1189     * <p>Item decorations are ordered. Decorations placed earlier in the list will
1190     * be run/queried/drawn first for their effects on item views. Padding added to views
1191     * will be nested; a padding added by an earlier decoration will mean further
1192     * item decorations in the list will be asked to draw/pad within the previous decoration's
1193     * given area.</p>
1194     *
1195     * @param decor Decoration to add
1196     * @param index Position in the decoration chain to insert this decoration at. If this value
1197     *              is negative the decoration will be added at the end.
1198     */
1199    public void addItemDecoration(ItemDecoration decor, int index) {
1200        if (mLayout != null) {
1201            mLayout.assertNotInLayoutOrScroll("Cannot add item decoration during a scroll  or"
1202                    + " layout");
1203        }
1204        if (mItemDecorations.isEmpty()) {
1205            setWillNotDraw(false);
1206        }
1207        if (index < 0) {
1208            mItemDecorations.add(decor);
1209        } else {
1210            mItemDecorations.add(index, decor);
1211        }
1212        markItemDecorInsetsDirty();
1213        requestLayout();
1214    }
1215
1216    /**
1217     * Add an {@link ItemDecoration} to this RecyclerView. Item decorations can
1218     * affect both measurement and drawing of individual item views.
1219     *
1220     * <p>Item decorations are ordered. Decorations placed earlier in the list will
1221     * be run/queried/drawn first for their effects on item views. Padding added to views
1222     * will be nested; a padding added by an earlier decoration will mean further
1223     * item decorations in the list will be asked to draw/pad within the previous decoration's
1224     * given area.</p>
1225     *
1226     * @param decor Decoration to add
1227     */
1228    public void addItemDecoration(ItemDecoration decor) {
1229        addItemDecoration(decor, -1);
1230    }
1231
1232    /**
1233     * Remove an {@link ItemDecoration} from this RecyclerView.
1234     *
1235     * <p>The given decoration will no longer impact the measurement and drawing of
1236     * item views.</p>
1237     *
1238     * @param decor Decoration to remove
1239     * @see #addItemDecoration(ItemDecoration)
1240     */
1241    public void removeItemDecoration(ItemDecoration decor) {
1242        if (mLayout != null) {
1243            mLayout.assertNotInLayoutOrScroll("Cannot remove item decoration during a scroll  or"
1244                    + " layout");
1245        }
1246        mItemDecorations.remove(decor);
1247        if (mItemDecorations.isEmpty()) {
1248            setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
1249        }
1250        markItemDecorInsetsDirty();
1251        requestLayout();
1252    }
1253
1254    /**
1255     * Sets the {@link ChildDrawingOrderCallback} to be used for drawing children.
1256     * <p>
1257     * See {@link ViewGroup#getChildDrawingOrder(int, int)} for details. Calling this method will
1258     * always call {@link ViewGroup#setChildrenDrawingOrderEnabled(boolean)}. The parameter will be
1259     * true if childDrawingOrderCallback is not null, false otherwise.
1260     * <p>
1261     * Note that child drawing order may be overridden by View's elevation.
1262     *
1263     * @param childDrawingOrderCallback The ChildDrawingOrderCallback to be used by the drawing
1264     *                                  system.
1265     */
1266    public void setChildDrawingOrderCallback(ChildDrawingOrderCallback childDrawingOrderCallback) {
1267        if (childDrawingOrderCallback == mChildDrawingOrderCallback) {
1268            return;
1269        }
1270        mChildDrawingOrderCallback = childDrawingOrderCallback;
1271        setChildrenDrawingOrderEnabled(mChildDrawingOrderCallback != null);
1272    }
1273
1274    /**
1275     * Set a listener that will be notified of any changes in scroll state or position.
1276     *
1277     * @param listener Listener to set or null to clear
1278     *
1279     * @deprecated Use {@link #addOnScrollListener(OnScrollListener)} and
1280     *             {@link #removeOnScrollListener(OnScrollListener)}
1281     */
1282    @Deprecated
1283    public void setOnScrollListener(OnScrollListener listener) {
1284        mScrollListener = listener;
1285    }
1286
1287    /**
1288     * Add a listener that will be notified of any changes in scroll state or position.
1289     *
1290     * <p>Components that add a listener should take care to remove it when finished.
1291     * Other components that take ownership of a view may call {@link #clearOnScrollListeners()}
1292     * to remove all attached listeners.</p>
1293     *
1294     * @param listener listener to set or null to clear
1295     */
1296    public void addOnScrollListener(OnScrollListener listener) {
1297        if (mScrollListeners == null) {
1298            mScrollListeners = new ArrayList<OnScrollListener>();
1299        }
1300        mScrollListeners.add(listener);
1301    }
1302
1303    /**
1304     * Remove a listener that was notified of any changes in scroll state or position.
1305     *
1306     * @param listener listener to set or null to clear
1307     */
1308    public void removeOnScrollListener(OnScrollListener listener) {
1309        if (mScrollListeners != null) {
1310            mScrollListeners.remove(listener);
1311        }
1312    }
1313
1314    /**
1315     * Remove all secondary listener that were notified of any changes in scroll state or position.
1316     */
1317    public void clearOnScrollListeners() {
1318        if (mScrollListeners != null) {
1319            mScrollListeners.clear();
1320        }
1321    }
1322
1323    /**
1324     * Convenience method to scroll to a certain position.
1325     *
1326     * RecyclerView does not implement scrolling logic, rather forwards the call to
1327     * {@link android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)}
1328     * @param position Scroll to this adapter position
1329     * @see android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition(int)
1330     */
1331    public void scrollToPosition(int position) {
1332        if (mLayoutFrozen) {
1333            return;
1334        }
1335        stopScroll();
1336        if (mLayout == null) {
1337            Log.e(TAG, "Cannot scroll to position a LayoutManager set. " +
1338                    "Call setLayoutManager with a non-null argument.");
1339            return;
1340        }
1341        mLayout.scrollToPosition(position);
1342        awakenScrollBars();
1343    }
1344
1345    private void jumpToPositionForSmoothScroller(int position) {
1346        if (mLayout == null) {
1347            return;
1348        }
1349        mLayout.scrollToPosition(position);
1350        awakenScrollBars();
1351    }
1352
1353    /**
1354     * Starts a smooth scroll to an adapter position.
1355     * <p>
1356     * To support smooth scrolling, you must override
1357     * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a
1358     * {@link SmoothScroller}.
1359     * <p>
1360     * {@link LayoutManager} is responsible for creating the actual scroll action. If you want to
1361     * provide a custom smooth scroll logic, override
1362     * {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your
1363     * LayoutManager.
1364     *
1365     * @param position The adapter position to scroll to
1366     * @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int)
1367     */
1368    public void smoothScrollToPosition(int position) {
1369        if (mLayoutFrozen) {
1370            return;
1371        }
1372        if (mLayout == null) {
1373            Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
1374                    "Call setLayoutManager with a non-null argument.");
1375            return;
1376        }
1377        mLayout.smoothScrollToPosition(this, mState, position);
1378    }
1379
1380    @Override
1381    public void scrollTo(int x, int y) {
1382        Log.w(TAG, "RecyclerView does not support scrolling to an absolute position. "
1383                + "Use scrollToPosition instead");
1384    }
1385
1386    @Override
1387    public void scrollBy(int x, int y) {
1388        if (mLayout == null) {
1389            Log.e(TAG, "Cannot scroll without a LayoutManager set. " +
1390                    "Call setLayoutManager with a non-null argument.");
1391            return;
1392        }
1393        if (mLayoutFrozen) {
1394            return;
1395        }
1396        final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
1397        final boolean canScrollVertical = mLayout.canScrollVertically();
1398        if (canScrollHorizontal || canScrollVertical) {
1399            scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0, null);
1400        }
1401    }
1402
1403    /**
1404     * Helper method reflect data changes to the state.
1405     * <p>
1406     * Adapter changes during a scroll may trigger a crash because scroll assumes no data change
1407     * but data actually changed.
1408     * <p>
1409     * This method consumes all deferred changes to avoid that case.
1410     */
1411    private void consumePendingUpdateOperations() {
1412        if (!mFirstLayoutComplete) {
1413            // a layout request will happen, we should not do layout here.
1414            return;
1415        }
1416        if (mDataSetHasChangedAfterLayout) {
1417            TraceCompat.beginSection(TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG);
1418            dispatchLayout();
1419            TraceCompat.endSection();
1420            return;
1421        }
1422        if (!mAdapterHelper.hasPendingUpdates()) {
1423            return;
1424        }
1425
1426        // if it is only an item change (no add-remove-notifyDataSetChanged) we can check if any
1427        // of the visible items is affected and if not, just ignore the change.
1428        if (mAdapterHelper.hasAnyUpdateTypes(UpdateOp.UPDATE) && !mAdapterHelper
1429                .hasAnyUpdateTypes(UpdateOp.ADD | UpdateOp.REMOVE | UpdateOp.MOVE)) {
1430            TraceCompat.beginSection(TRACE_HANDLE_ADAPTER_UPDATES_TAG);
1431            eatRequestLayout();
1432            mAdapterHelper.preProcess();
1433            if (!mLayoutRequestEaten) {
1434                if (hasUpdatedView()) {
1435                    dispatchLayout();
1436                } else {
1437                    // no need to layout, clean state
1438                    mAdapterHelper.consumePostponedUpdates();
1439                }
1440            }
1441            resumeRequestLayout(true);
1442            TraceCompat.endSection();
1443        } else if (mAdapterHelper.hasPendingUpdates()) {
1444            TraceCompat.beginSection(TRACE_ON_DATA_SET_CHANGE_LAYOUT_TAG);
1445            dispatchLayout();
1446            TraceCompat.endSection();
1447        }
1448    }
1449
1450    /**
1451     * @return True if an existing view holder needs to be updated
1452     */
1453    private boolean hasUpdatedView() {
1454        final int childCount = mChildHelper.getChildCount();
1455        for (int i = 0; i < childCount; i++) {
1456            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
1457            if (holder == null || holder.shouldIgnore()) {
1458                continue;
1459            }
1460            if (holder.isUpdated()) {
1461                return true;
1462            }
1463        }
1464        return false;
1465    }
1466
1467    /**
1468     * Does not perform bounds checking. Used by internal methods that have already validated input.
1469     * <p>
1470     * It also reports any unused scroll request to the related EdgeEffect.
1471     *
1472     * @param x The amount of horizontal scroll request
1473     * @param y The amount of vertical scroll request
1474     * @param ev The originating MotionEvent, or null if not from a touch event.
1475     *
1476     * @return Whether any scroll was consumed in either direction.
1477     */
1478    boolean scrollByInternal(int x, int y, MotionEvent ev) {
1479        int unconsumedX = 0, unconsumedY = 0;
1480        int consumedX = 0, consumedY = 0;
1481
1482        consumePendingUpdateOperations();
1483        if (mAdapter != null) {
1484            eatRequestLayout();
1485            onEnterLayoutOrScroll();
1486            TraceCompat.beginSection(TRACE_SCROLL_TAG);
1487            if (x != 0) {
1488                consumedX = mLayout.scrollHorizontallyBy(x, mRecycler, mState);
1489                unconsumedX = x - consumedX;
1490            }
1491            if (y != 0) {
1492                consumedY = mLayout.scrollVerticallyBy(y, mRecycler, mState);
1493                unconsumedY = y - consumedY;
1494            }
1495            TraceCompat.endSection();
1496            repositionShadowingViews();
1497            onExitLayoutOrScroll();
1498            resumeRequestLayout(false);
1499        }
1500        if (!mItemDecorations.isEmpty()) {
1501            invalidate();
1502        }
1503
1504        if (dispatchNestedScroll(consumedX, consumedY, unconsumedX, unconsumedY, mScrollOffset)) {
1505            // Update the last touch co-ords, taking any scroll offset into account
1506            mLastTouchX -= mScrollOffset[0];
1507            mLastTouchY -= mScrollOffset[1];
1508            if (ev != null) {
1509                ev.offsetLocation(mScrollOffset[0], mScrollOffset[1]);
1510            }
1511            mNestedOffsets[0] += mScrollOffset[0];
1512            mNestedOffsets[1] += mScrollOffset[1];
1513        } else if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
1514            if (ev != null) {
1515                pullGlows(ev.getX(), unconsumedX, ev.getY(), unconsumedY);
1516            }
1517            considerReleasingGlowsOnScroll(x, y);
1518        }
1519        if (consumedX != 0 || consumedY != 0) {
1520            dispatchOnScrolled(consumedX, consumedY);
1521        }
1522        if (!awakenScrollBars()) {
1523            invalidate();
1524        }
1525        return consumedX != 0 || consumedY != 0;
1526    }
1527
1528    /**
1529     * <p>Compute the horizontal offset of the horizontal scrollbar's thumb within the horizontal
1530     * range. This value is used to compute the length of the thumb within the scrollbar's track.
1531     * </p>
1532     *
1533     * <p>The range is expressed in arbitrary units that must be the same as the units used by
1534     * {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollExtent()}.</p>
1535     *
1536     * <p>Default implementation returns 0.</p>
1537     *
1538     * <p>If you want to support scroll bars, override
1539     * {@link RecyclerView.LayoutManager#computeHorizontalScrollOffset(RecyclerView.State)} in your
1540     * LayoutManager. </p>
1541     *
1542     * @return The horizontal offset of the scrollbar's thumb
1543     * @see android.support.v7.widget.RecyclerView.LayoutManager#computeHorizontalScrollOffset
1544     * (RecyclerView.State)
1545     */
1546    @Override
1547    public int computeHorizontalScrollOffset() {
1548        return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollOffset(mState)
1549                : 0;
1550    }
1551
1552    /**
1553     * <p>Compute the horizontal extent of the horizontal scrollbar's thumb within the
1554     * horizontal range. This value is used to compute the length of the thumb within the
1555     * scrollbar's track.</p>
1556     *
1557     * <p>The range is expressed in arbitrary units that must be the same as the units used by
1558     * {@link #computeHorizontalScrollRange()} and {@link #computeHorizontalScrollOffset()}.</p>
1559     *
1560     * <p>Default implementation returns 0.</p>
1561     *
1562     * <p>If you want to support scroll bars, override
1563     * {@link RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)} in your
1564     * LayoutManager.</p>
1565     *
1566     * @return The horizontal extent of the scrollbar's thumb
1567     * @see RecyclerView.LayoutManager#computeHorizontalScrollExtent(RecyclerView.State)
1568     */
1569    @Override
1570    public int computeHorizontalScrollExtent() {
1571        return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollExtent(mState) : 0;
1572    }
1573
1574    /**
1575     * <p>Compute the horizontal range that the horizontal scrollbar represents.</p>
1576     *
1577     * <p>The range is expressed in arbitrary units that must be the same as the units used by
1578     * {@link #computeHorizontalScrollExtent()} and {@link #computeHorizontalScrollOffset()}.</p>
1579     *
1580     * <p>Default implementation returns 0.</p>
1581     *
1582     * <p>If you want to support scroll bars, override
1583     * {@link RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)} in your
1584     * LayoutManager.</p>
1585     *
1586     * @return The total horizontal range represented by the vertical scrollbar
1587     * @see RecyclerView.LayoutManager#computeHorizontalScrollRange(RecyclerView.State)
1588     */
1589    @Override
1590    public int computeHorizontalScrollRange() {
1591        return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollRange(mState) : 0;
1592    }
1593
1594    /**
1595     * <p>Compute the vertical offset of the vertical scrollbar's thumb within the vertical range.
1596     * This value is used to compute the length of the thumb within the scrollbar's track. </p>
1597     *
1598     * <p>The range is expressed in arbitrary units that must be the same as the units used by
1599     * {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollExtent()}.</p>
1600     *
1601     * <p>Default implementation returns 0.</p>
1602     *
1603     * <p>If you want to support scroll bars, override
1604     * {@link RecyclerView.LayoutManager#computeVerticalScrollOffset(RecyclerView.State)} in your
1605     * LayoutManager.</p>
1606     *
1607     * @return The vertical offset of the scrollbar's thumb
1608     * @see android.support.v7.widget.RecyclerView.LayoutManager#computeVerticalScrollOffset
1609     * (RecyclerView.State)
1610     */
1611    @Override
1612    public int computeVerticalScrollOffset() {
1613        return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollOffset(mState) : 0;
1614    }
1615
1616    /**
1617     * <p>Compute the vertical extent of the vertical scrollbar's thumb within the vertical range.
1618     * This value is used to compute the length of the thumb within the scrollbar's track.</p>
1619     *
1620     * <p>The range is expressed in arbitrary units that must be the same as the units used by
1621     * {@link #computeVerticalScrollRange()} and {@link #computeVerticalScrollOffset()}.</p>
1622     *
1623     * <p>Default implementation returns 0.</p>
1624     *
1625     * <p>If you want to support scroll bars, override
1626     * {@link RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)} in your
1627     * LayoutManager.</p>
1628     *
1629     * @return The vertical extent of the scrollbar's thumb
1630     * @see RecyclerView.LayoutManager#computeVerticalScrollExtent(RecyclerView.State)
1631     */
1632    @Override
1633    public int computeVerticalScrollExtent() {
1634        return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollExtent(mState) : 0;
1635    }
1636
1637    /**
1638     * <p>Compute the vertical range that the vertical scrollbar represents.</p>
1639     *
1640     * <p>The range is expressed in arbitrary units that must be the same as the units used by
1641     * {@link #computeVerticalScrollExtent()} and {@link #computeVerticalScrollOffset()}.</p>
1642     *
1643     * <p>Default implementation returns 0.</p>
1644     *
1645     * <p>If you want to support scroll bars, override
1646     * {@link RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)} in your
1647     * LayoutManager.</p>
1648     *
1649     * @return The total vertical range represented by the vertical scrollbar
1650     * @see RecyclerView.LayoutManager#computeVerticalScrollRange(RecyclerView.State)
1651     */
1652    @Override
1653    public int computeVerticalScrollRange() {
1654        return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollRange(mState) : 0;
1655    }
1656
1657
1658    void eatRequestLayout() {
1659        if (!mEatRequestLayout) {
1660            mEatRequestLayout = true;
1661            if (!mLayoutFrozen) {
1662                mLayoutRequestEaten = false;
1663            }
1664        }
1665    }
1666
1667    void resumeRequestLayout(boolean performLayoutChildren) {
1668        if (mEatRequestLayout) {
1669            // when layout is frozen we should delay dispatchLayout()
1670            if (performLayoutChildren && mLayoutRequestEaten && !mLayoutFrozen &&
1671                    mLayout != null && mAdapter != null) {
1672                dispatchLayout();
1673            }
1674            mEatRequestLayout = false;
1675            if (!mLayoutFrozen) {
1676                mLayoutRequestEaten = false;
1677            }
1678        }
1679    }
1680
1681    /**
1682     * Enable or disable layout and scroll.  After <code>setLayoutFrozen(true)</code> is called,
1683     * Layout requests will be postponed until <code>setLayoutFrozen(false)</code> is called;
1684     * child views are not updated when RecyclerView is frozen, {@link #smoothScrollBy(int, int)},
1685     * {@link #scrollBy(int, int)}, {@link #scrollToPosition(int)} and
1686     * {@link #smoothScrollToPosition(int)} are dropped; TouchEvents and GenericMotionEvents are
1687     * dropped; {@link LayoutManager#onFocusSearchFailed(View, int, Recycler, State)} will not be
1688     * called.
1689     *
1690     * <p>
1691     * <code>setLayoutFrozen(true)</code> does not prevent app from directly calling {@link
1692     * LayoutManager#scrollToPosition(int)}, {@link LayoutManager#smoothScrollToPosition(
1693     * RecyclerView, State, int)}.
1694     * <p>
1695     * {@link #setAdapter(Adapter)} and {@link #swapAdapter(Adapter, boolean)} will automatically
1696     * stop frozen.
1697     * <p>
1698     * Note: Running ItemAnimator is not stopped automatically,  it's caller's
1699     * responsibility to call ItemAnimator.end().
1700     *
1701     * @param frozen   true to freeze layout and scroll, false to re-enable.
1702     */
1703    public void setLayoutFrozen(boolean frozen) {
1704        if (frozen != mLayoutFrozen) {
1705            assertNotInLayoutOrScroll("Do not setLayoutFrozen in layout or scroll");
1706            if (!frozen) {
1707                mLayoutFrozen = frozen;
1708                if (mLayoutRequestEaten && mLayout != null && mAdapter != null) {
1709                    requestLayout();
1710                }
1711                mLayoutRequestEaten = false;
1712            } else {
1713                final long now = SystemClock.uptimeMillis();
1714                MotionEvent cancelEvent = MotionEvent.obtain(now, now,
1715                        MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
1716                onTouchEvent(cancelEvent);
1717                mLayoutFrozen = frozen;
1718                mIgnoreMotionEventTillDown = true;
1719                stopScroll();
1720            }
1721        }
1722    }
1723
1724    /**
1725     * Returns true if layout and scroll are frozen.
1726     *
1727     * @return true if layout and scroll are frozen
1728     * @see #setLayoutFrozen(boolean)
1729     */
1730    public boolean isLayoutFrozen() {
1731        return mLayoutFrozen;
1732    }
1733
1734    /**
1735     * Animate a scroll by the given amount of pixels along either axis.
1736     *
1737     * @param dx Pixels to scroll horizontally
1738     * @param dy Pixels to scroll vertically
1739     */
1740    public void smoothScrollBy(int dx, int dy) {
1741        if (mLayout == null) {
1742            Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " +
1743                    "Call setLayoutManager with a non-null argument.");
1744            return;
1745        }
1746        if (mLayoutFrozen) {
1747            return;
1748        }
1749        if (!mLayout.canScrollHorizontally()) {
1750            dx = 0;
1751        }
1752        if (!mLayout.canScrollVertically()) {
1753            dy = 0;
1754        }
1755        if (dx != 0 || dy != 0) {
1756            mViewFlinger.smoothScrollBy(dx, dy);
1757        }
1758    }
1759
1760    /**
1761     * Begin a standard fling with an initial velocity along each axis in pixels per second.
1762     * If the velocity given is below the system-defined minimum this method will return false
1763     * and no fling will occur.
1764     *
1765     * @param velocityX Initial horizontal velocity in pixels per second
1766     * @param velocityY Initial vertical velocity in pixels per second
1767     * @return true if the fling was started, false if the velocity was too low to fling or
1768     * LayoutManager does not support scrolling in the axis fling is issued.
1769     *
1770     * @see LayoutManager#canScrollVertically()
1771     * @see LayoutManager#canScrollHorizontally()
1772     */
1773    public boolean fling(int velocityX, int velocityY) {
1774        if (mLayout == null) {
1775            Log.e(TAG, "Cannot fling without a LayoutManager set. " +
1776                    "Call setLayoutManager with a non-null argument.");
1777            return false;
1778        }
1779        if (mLayoutFrozen) {
1780            return false;
1781        }
1782
1783        final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
1784        final boolean canScrollVertical = mLayout.canScrollVertically();
1785
1786        if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) {
1787            velocityX = 0;
1788        }
1789        if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) {
1790            velocityY = 0;
1791        }
1792        if (velocityX == 0 && velocityY == 0) {
1793            // If we don't have any velocity, return false
1794            return false;
1795        }
1796
1797        if (!dispatchNestedPreFling(velocityX, velocityY)) {
1798            final boolean canScroll = canScrollHorizontal || canScrollVertical;
1799            dispatchNestedFling(velocityX, velocityY, canScroll);
1800
1801            if (canScroll) {
1802                velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity));
1803                velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity));
1804                mViewFlinger.fling(velocityX, velocityY);
1805                return true;
1806            }
1807        }
1808        return false;
1809    }
1810
1811    /**
1812     * Stop any current scroll in progress, such as one started by
1813     * {@link #smoothScrollBy(int, int)}, {@link #fling(int, int)} or a touch-initiated fling.
1814     */
1815    public void stopScroll() {
1816        setScrollState(SCROLL_STATE_IDLE);
1817        stopScrollersInternal();
1818    }
1819
1820    /**
1821     * Similar to {@link #stopScroll()} but does not set the state.
1822     */
1823    private void stopScrollersInternal() {
1824        mViewFlinger.stop();
1825        if (mLayout != null) {
1826            mLayout.stopSmoothScroller();
1827        }
1828    }
1829
1830    /**
1831     * Returns the minimum velocity to start a fling.
1832     *
1833     * @return The minimum velocity to start a fling
1834     */
1835    public int getMinFlingVelocity() {
1836        return mMinFlingVelocity;
1837    }
1838
1839
1840    /**
1841     * Returns the maximum fling velocity used by this RecyclerView.
1842     *
1843     * @return The maximum fling velocity used by this RecyclerView.
1844     */
1845    public int getMaxFlingVelocity() {
1846        return mMaxFlingVelocity;
1847    }
1848
1849    /**
1850     * Apply a pull to relevant overscroll glow effects
1851     */
1852    private void pullGlows(float x, float overscrollX, float y, float overscrollY) {
1853        boolean invalidate = false;
1854        if (overscrollX < 0) {
1855            ensureLeftGlow();
1856            if (mLeftGlow.onPull(-overscrollX / getWidth(), 1f - y  / getHeight())) {
1857                invalidate = true;
1858            }
1859        } else if (overscrollX > 0) {
1860            ensureRightGlow();
1861            if (mRightGlow.onPull(overscrollX / getWidth(), y / getHeight())) {
1862                invalidate = true;
1863            }
1864        }
1865
1866        if (overscrollY < 0) {
1867            ensureTopGlow();
1868            if (mTopGlow.onPull(-overscrollY / getHeight(), x / getWidth())) {
1869                invalidate = true;
1870            }
1871        } else if (overscrollY > 0) {
1872            ensureBottomGlow();
1873            if (mBottomGlow.onPull(overscrollY / getHeight(), 1f - x / getWidth())) {
1874                invalidate = true;
1875            }
1876        }
1877
1878        if (invalidate || overscrollX != 0 || overscrollY != 0) {
1879            ViewCompat.postInvalidateOnAnimation(this);
1880        }
1881    }
1882
1883    private void releaseGlows() {
1884        boolean needsInvalidate = false;
1885        if (mLeftGlow != null) needsInvalidate = mLeftGlow.onRelease();
1886        if (mTopGlow != null) needsInvalidate |= mTopGlow.onRelease();
1887        if (mRightGlow != null) needsInvalidate |= mRightGlow.onRelease();
1888        if (mBottomGlow != null) needsInvalidate |= mBottomGlow.onRelease();
1889        if (needsInvalidate) {
1890            ViewCompat.postInvalidateOnAnimation(this);
1891        }
1892    }
1893
1894    private void considerReleasingGlowsOnScroll(int dx, int dy) {
1895        boolean needsInvalidate = false;
1896        if (mLeftGlow != null && !mLeftGlow.isFinished() && dx > 0) {
1897            needsInvalidate = mLeftGlow.onRelease();
1898        }
1899        if (mRightGlow != null && !mRightGlow.isFinished() && dx < 0) {
1900            needsInvalidate |= mRightGlow.onRelease();
1901        }
1902        if (mTopGlow != null && !mTopGlow.isFinished() && dy > 0) {
1903            needsInvalidate |= mTopGlow.onRelease();
1904        }
1905        if (mBottomGlow != null && !mBottomGlow.isFinished() && dy < 0) {
1906            needsInvalidate |= mBottomGlow.onRelease();
1907        }
1908        if (needsInvalidate) {
1909            ViewCompat.postInvalidateOnAnimation(this);
1910        }
1911    }
1912
1913    void absorbGlows(int velocityX, int velocityY) {
1914        if (velocityX < 0) {
1915            ensureLeftGlow();
1916            mLeftGlow.onAbsorb(-velocityX);
1917        } else if (velocityX > 0) {
1918            ensureRightGlow();
1919            mRightGlow.onAbsorb(velocityX);
1920        }
1921
1922        if (velocityY < 0) {
1923            ensureTopGlow();
1924            mTopGlow.onAbsorb(-velocityY);
1925        } else if (velocityY > 0) {
1926            ensureBottomGlow();
1927            mBottomGlow.onAbsorb(velocityY);
1928        }
1929
1930        if (velocityX != 0 || velocityY != 0) {
1931            ViewCompat.postInvalidateOnAnimation(this);
1932        }
1933    }
1934
1935    void ensureLeftGlow() {
1936        if (mLeftGlow != null) {
1937            return;
1938        }
1939        mLeftGlow = new EdgeEffectCompat(getContext());
1940        if (mClipToPadding) {
1941            mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
1942                    getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
1943        } else {
1944            mLeftGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
1945        }
1946    }
1947
1948    void ensureRightGlow() {
1949        if (mRightGlow != null) {
1950            return;
1951        }
1952        mRightGlow = new EdgeEffectCompat(getContext());
1953        if (mClipToPadding) {
1954            mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
1955                    getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
1956        } else {
1957            mRightGlow.setSize(getMeasuredHeight(), getMeasuredWidth());
1958        }
1959    }
1960
1961    void ensureTopGlow() {
1962        if (mTopGlow != null) {
1963            return;
1964        }
1965        mTopGlow = new EdgeEffectCompat(getContext());
1966        if (mClipToPadding) {
1967            mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
1968                    getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
1969        } else {
1970            mTopGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
1971        }
1972
1973    }
1974
1975    void ensureBottomGlow() {
1976        if (mBottomGlow != null) {
1977            return;
1978        }
1979        mBottomGlow = new EdgeEffectCompat(getContext());
1980        if (mClipToPadding) {
1981            mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
1982                    getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
1983        } else {
1984            mBottomGlow.setSize(getMeasuredWidth(), getMeasuredHeight());
1985        }
1986    }
1987
1988    void invalidateGlows() {
1989        mLeftGlow = mRightGlow = mTopGlow = mBottomGlow = null;
1990    }
1991
1992    // Focus handling
1993
1994    @Override
1995    public View focusSearch(View focused, int direction) {
1996        View result = mLayout.onInterceptFocusSearch(focused, direction);
1997        if (result != null) {
1998            return result;
1999        }
2000        final FocusFinder ff = FocusFinder.getInstance();
2001        result = ff.findNextFocus(this, focused, direction);
2002        if (result == null && mAdapter != null && mLayout != null && !isComputingLayout()
2003                && !mLayoutFrozen) {
2004            eatRequestLayout();
2005            result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
2006            resumeRequestLayout(false);
2007        }
2008        return result != null ? result : super.focusSearch(focused, direction);
2009    }
2010
2011    @Override
2012    public void requestChildFocus(View child, View focused) {
2013        if (!mLayout.onRequestChildFocus(this, mState, child, focused) && focused != null) {
2014            mTempRect.set(0, 0, focused.getWidth(), focused.getHeight());
2015
2016            // get item decor offsets w/o refreshing. If they are invalid, there will be another
2017            // layout pass to fix them, then it is LayoutManager's responsibility to keep focused
2018            // View in viewport.
2019            final ViewGroup.LayoutParams focusedLayoutParams = focused.getLayoutParams();
2020            if (focusedLayoutParams instanceof LayoutParams) {
2021                // if focused child has item decors, use them. Otherwise, ignore.
2022                final LayoutParams lp = (LayoutParams) focusedLayoutParams;
2023                if (!lp.mInsetsDirty) {
2024                    final Rect insets = lp.mDecorInsets;
2025                    mTempRect.left -= insets.left;
2026                    mTempRect.right += insets.right;
2027                    mTempRect.top -= insets.top;
2028                    mTempRect.bottom += insets.bottom;
2029                }
2030            }
2031
2032            offsetDescendantRectToMyCoords(focused, mTempRect);
2033            offsetRectIntoDescendantCoords(child, mTempRect);
2034            requestChildRectangleOnScreen(child, mTempRect, !mFirstLayoutComplete);
2035        }
2036        super.requestChildFocus(child, focused);
2037    }
2038
2039    @Override
2040    public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) {
2041        return mLayout.requestChildRectangleOnScreen(this, child, rect, immediate);
2042    }
2043
2044    @Override
2045    public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
2046        if (mLayout == null || !mLayout.onAddFocusables(this, views, direction, focusableMode)) {
2047            super.addFocusables(views, direction, focusableMode);
2048        }
2049    }
2050
2051    @Override
2052    protected void onAttachedToWindow() {
2053        super.onAttachedToWindow();
2054        mLayoutOrScrollCounter = 0;
2055        mIsAttached = true;
2056        mFirstLayoutComplete = false;
2057        if (mLayout != null) {
2058            mLayout.dispatchAttachedToWindow(this);
2059        }
2060        mPostedAnimatorRunner = false;
2061    }
2062
2063    @Override
2064    protected void onDetachedFromWindow() {
2065        super.onDetachedFromWindow();
2066        if (mItemAnimator != null) {
2067            mItemAnimator.endAnimations();
2068        }
2069        mFirstLayoutComplete = false;
2070
2071        stopScroll();
2072        mIsAttached = false;
2073        if (mLayout != null) {
2074            mLayout.dispatchDetachedFromWindow(this, mRecycler);
2075        }
2076        removeCallbacks(mItemAnimatorRunner);
2077        mViewInfoStore.onDetach();
2078    }
2079
2080    /**
2081     * Returns true if RecyclerView is attached to window.
2082     */
2083    // @override
2084    public boolean isAttachedToWindow() {
2085        return mIsAttached;
2086    }
2087
2088    /**
2089     * Checks if RecyclerView is in the middle of a layout or scroll and throws an
2090     * {@link IllegalStateException} if it <b>is not</b>.
2091     *
2092     * @param message The message for the exception. Can be null.
2093     * @see #assertNotInLayoutOrScroll(String)
2094     */
2095    void assertInLayoutOrScroll(String message) {
2096        if (!isComputingLayout()) {
2097            if (message == null) {
2098                throw new IllegalStateException("Cannot call this method unless RecyclerView is "
2099                        + "computing a layout or scrolling");
2100            }
2101            throw new IllegalStateException(message);
2102
2103        }
2104    }
2105
2106    /**
2107     * Checks if RecyclerView is in the middle of a layout or scroll and throws an
2108     * {@link IllegalStateException} if it <b>is</b>.
2109     *
2110     * @param message The message for the exception. Can be null.
2111     * @see #assertInLayoutOrScroll(String)
2112     */
2113    void assertNotInLayoutOrScroll(String message) {
2114        if (isComputingLayout()) {
2115            if (message == null) {
2116                throw new IllegalStateException("Cannot call this method while RecyclerView is "
2117                        + "computing a layout or scrolling");
2118            }
2119            throw new IllegalStateException(message);
2120        }
2121    }
2122
2123    /**
2124     * Add an {@link OnItemTouchListener} to intercept touch events before they are dispatched
2125     * to child views or this view's standard scrolling behavior.
2126     *
2127     * <p>Client code may use listeners to implement item manipulation behavior. Once a listener
2128     * returns true from
2129     * {@link OnItemTouchListener#onInterceptTouchEvent(RecyclerView, MotionEvent)} its
2130     * {@link OnItemTouchListener#onTouchEvent(RecyclerView, MotionEvent)} method will be called
2131     * for each incoming MotionEvent until the end of the gesture.</p>
2132     *
2133     * @param listener Listener to add
2134     * @see SimpleOnItemTouchListener
2135     */
2136    public void addOnItemTouchListener(OnItemTouchListener listener) {
2137        mOnItemTouchListeners.add(listener);
2138    }
2139
2140    /**
2141     * Remove an {@link OnItemTouchListener}. It will no longer be able to intercept touch events.
2142     *
2143     * @param listener Listener to remove
2144     */
2145    public void removeOnItemTouchListener(OnItemTouchListener listener) {
2146        mOnItemTouchListeners.remove(listener);
2147        if (mActiveOnItemTouchListener == listener) {
2148            mActiveOnItemTouchListener = null;
2149        }
2150    }
2151
2152    private boolean dispatchOnItemTouchIntercept(MotionEvent e) {
2153        final int action = e.getAction();
2154        if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_DOWN) {
2155            mActiveOnItemTouchListener = null;
2156        }
2157
2158        final int listenerCount = mOnItemTouchListeners.size();
2159        for (int i = 0; i < listenerCount; i++) {
2160            final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
2161            if (listener.onInterceptTouchEvent(this, e) && action != MotionEvent.ACTION_CANCEL) {
2162                mActiveOnItemTouchListener = listener;
2163                return true;
2164            }
2165        }
2166        return false;
2167    }
2168
2169    private boolean dispatchOnItemTouch(MotionEvent e) {
2170        final int action = e.getAction();
2171        if (mActiveOnItemTouchListener != null) {
2172            if (action == MotionEvent.ACTION_DOWN) {
2173                // Stale state from a previous gesture, we're starting a new one. Clear it.
2174                mActiveOnItemTouchListener = null;
2175            } else {
2176                mActiveOnItemTouchListener.onTouchEvent(this, e);
2177                if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
2178                    // Clean up for the next gesture.
2179                    mActiveOnItemTouchListener = null;
2180                }
2181                return true;
2182            }
2183        }
2184
2185        // Listeners will have already received the ACTION_DOWN via dispatchOnItemTouchIntercept
2186        // as called from onInterceptTouchEvent; skip it.
2187        if (action != MotionEvent.ACTION_DOWN) {
2188            final int listenerCount = mOnItemTouchListeners.size();
2189            for (int i = 0; i < listenerCount; i++) {
2190                final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
2191                if (listener.onInterceptTouchEvent(this, e)) {
2192                    mActiveOnItemTouchListener = listener;
2193                    return true;
2194                }
2195            }
2196        }
2197        return false;
2198    }
2199
2200    @Override
2201    public boolean onInterceptTouchEvent(MotionEvent e) {
2202        if (mLayoutFrozen) {
2203            // When layout is frozen,  RV does not intercept the motion event.
2204            // A child view e.g. a button may still get the click.
2205            return false;
2206        }
2207        if (dispatchOnItemTouchIntercept(e)) {
2208            cancelTouch();
2209            return true;
2210        }
2211
2212        if (mLayout == null) {
2213            return false;
2214        }
2215
2216        final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
2217        final boolean canScrollVertically = mLayout.canScrollVertically();
2218
2219        if (mVelocityTracker == null) {
2220            mVelocityTracker = VelocityTracker.obtain();
2221        }
2222        mVelocityTracker.addMovement(e);
2223
2224        final int action = MotionEventCompat.getActionMasked(e);
2225        final int actionIndex = MotionEventCompat.getActionIndex(e);
2226
2227        switch (action) {
2228            case MotionEvent.ACTION_DOWN:
2229                if (mIgnoreMotionEventTillDown) {
2230                    mIgnoreMotionEventTillDown = false;
2231                }
2232                mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
2233                mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
2234                mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
2235
2236                if (mScrollState == SCROLL_STATE_SETTLING) {
2237                    getParent().requestDisallowInterceptTouchEvent(true);
2238                    setScrollState(SCROLL_STATE_DRAGGING);
2239                }
2240
2241                // Clear the nested offsets
2242                mNestedOffsets[0] = mNestedOffsets[1] = 0;
2243
2244                int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE;
2245                if (canScrollHorizontally) {
2246                    nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;
2247                }
2248                if (canScrollVertically) {
2249                    nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;
2250                }
2251                startNestedScroll(nestedScrollAxis);
2252                break;
2253
2254            case MotionEventCompat.ACTION_POINTER_DOWN:
2255                mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
2256                mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
2257                mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
2258                break;
2259
2260            case MotionEvent.ACTION_MOVE: {
2261                final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
2262                if (index < 0) {
2263                    Log.e(TAG, "Error processing scroll; pointer index for id " +
2264                            mScrollPointerId + " not found. Did any MotionEvents get skipped?");
2265                    return false;
2266                }
2267
2268                final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
2269                final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
2270                if (mScrollState != SCROLL_STATE_DRAGGING) {
2271                    final int dx = x - mInitialTouchX;
2272                    final int dy = y - mInitialTouchY;
2273                    boolean startScroll = false;
2274                    if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
2275                        mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1);
2276                        startScroll = true;
2277                    }
2278                    if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
2279                        mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1);
2280                        startScroll = true;
2281                    }
2282                    if (startScroll) {
2283                        setScrollState(SCROLL_STATE_DRAGGING);
2284                    }
2285                }
2286            } break;
2287
2288            case MotionEventCompat.ACTION_POINTER_UP: {
2289                onPointerUp(e);
2290            } break;
2291
2292            case MotionEvent.ACTION_UP: {
2293                mVelocityTracker.clear();
2294                stopNestedScroll();
2295            } break;
2296
2297            case MotionEvent.ACTION_CANCEL: {
2298                cancelTouch();
2299            }
2300        }
2301        return mScrollState == SCROLL_STATE_DRAGGING;
2302    }
2303
2304    @Override
2305    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
2306        final int listenerCount = mOnItemTouchListeners.size();
2307        for (int i = 0; i < listenerCount; i++) {
2308            final OnItemTouchListener listener = mOnItemTouchListeners.get(i);
2309            listener.onRequestDisallowInterceptTouchEvent(disallowIntercept);
2310        }
2311        super.requestDisallowInterceptTouchEvent(disallowIntercept);
2312    }
2313
2314    @Override
2315    public boolean onTouchEvent(MotionEvent e) {
2316        if (mLayoutFrozen || mIgnoreMotionEventTillDown) {
2317            return false;
2318        }
2319        if (dispatchOnItemTouch(e)) {
2320            cancelTouch();
2321            return true;
2322        }
2323
2324        if (mLayout == null) {
2325            return false;
2326        }
2327
2328        final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
2329        final boolean canScrollVertically = mLayout.canScrollVertically();
2330
2331        if (mVelocityTracker == null) {
2332            mVelocityTracker = VelocityTracker.obtain();
2333        }
2334        boolean eventAddedToVelocityTracker = false;
2335
2336        final MotionEvent vtev = MotionEvent.obtain(e);
2337        final int action = MotionEventCompat.getActionMasked(e);
2338        final int actionIndex = MotionEventCompat.getActionIndex(e);
2339
2340        if (action == MotionEvent.ACTION_DOWN) {
2341            mNestedOffsets[0] = mNestedOffsets[1] = 0;
2342        }
2343        vtev.offsetLocation(mNestedOffsets[0], mNestedOffsets[1]);
2344
2345        switch (action) {
2346            case MotionEvent.ACTION_DOWN: {
2347                mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
2348                mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
2349                mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
2350
2351                int nestedScrollAxis = ViewCompat.SCROLL_AXIS_NONE;
2352                if (canScrollHorizontally) {
2353                    nestedScrollAxis |= ViewCompat.SCROLL_AXIS_HORIZONTAL;
2354                }
2355                if (canScrollVertically) {
2356                    nestedScrollAxis |= ViewCompat.SCROLL_AXIS_VERTICAL;
2357                }
2358                startNestedScroll(nestedScrollAxis);
2359            } break;
2360
2361            case MotionEventCompat.ACTION_POINTER_DOWN: {
2362                mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
2363                mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
2364                mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
2365            } break;
2366
2367            case MotionEvent.ACTION_MOVE: {
2368                final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
2369                if (index < 0) {
2370                    Log.e(TAG, "Error processing scroll; pointer index for id " +
2371                            mScrollPointerId + " not found. Did any MotionEvents get skipped?");
2372                    return false;
2373                }
2374
2375                final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
2376                final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
2377                int dx = mLastTouchX - x;
2378                int dy = mLastTouchY - y;
2379
2380                if (dispatchNestedPreScroll(dx, dy, mScrollConsumed, mScrollOffset)) {
2381                    dx -= mScrollConsumed[0];
2382                    dy -= mScrollConsumed[1];
2383                    vtev.offsetLocation(mScrollOffset[0], mScrollOffset[1]);
2384                    // Updated the nested offsets
2385                    mNestedOffsets[0] += mScrollOffset[0];
2386                    mNestedOffsets[1] += mScrollOffset[1];
2387                }
2388
2389                if (mScrollState != SCROLL_STATE_DRAGGING) {
2390                    boolean startScroll = false;
2391                    if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
2392                        if (dx > 0) {
2393                            dx -= mTouchSlop;
2394                        } else {
2395                            dx += mTouchSlop;
2396                        }
2397                        startScroll = true;
2398                    }
2399                    if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
2400                        if (dy > 0) {
2401                            dy -= mTouchSlop;
2402                        } else {
2403                            dy += mTouchSlop;
2404                        }
2405                        startScroll = true;
2406                    }
2407                    if (startScroll) {
2408                        setScrollState(SCROLL_STATE_DRAGGING);
2409                    }
2410                }
2411
2412                if (mScrollState == SCROLL_STATE_DRAGGING) {
2413                    mLastTouchX = x - mScrollOffset[0];
2414                    mLastTouchY = y - mScrollOffset[1];
2415
2416                    if (scrollByInternal(
2417                            canScrollHorizontally ? dx : 0,
2418                            canScrollVertically ? dy : 0,
2419                            vtev)) {
2420                        getParent().requestDisallowInterceptTouchEvent(true);
2421                    }
2422                }
2423            } break;
2424
2425            case MotionEventCompat.ACTION_POINTER_UP: {
2426                onPointerUp(e);
2427            } break;
2428
2429            case MotionEvent.ACTION_UP: {
2430                mVelocityTracker.addMovement(vtev);
2431                eventAddedToVelocityTracker = true;
2432                mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);
2433                final float xvel = canScrollHorizontally ?
2434                        -VelocityTrackerCompat.getXVelocity(mVelocityTracker, mScrollPointerId) : 0;
2435                final float yvel = canScrollVertically ?
2436                        -VelocityTrackerCompat.getYVelocity(mVelocityTracker, mScrollPointerId) : 0;
2437                if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {
2438                    setScrollState(SCROLL_STATE_IDLE);
2439                }
2440                resetTouch();
2441            } break;
2442
2443            case MotionEvent.ACTION_CANCEL: {
2444                cancelTouch();
2445            } break;
2446        }
2447
2448        if (!eventAddedToVelocityTracker) {
2449            mVelocityTracker.addMovement(vtev);
2450        }
2451        vtev.recycle();
2452
2453        return true;
2454    }
2455
2456    private void resetTouch() {
2457        if (mVelocityTracker != null) {
2458            mVelocityTracker.clear();
2459        }
2460        stopNestedScroll();
2461        releaseGlows();
2462    }
2463
2464    private void cancelTouch() {
2465        resetTouch();
2466        setScrollState(SCROLL_STATE_IDLE);
2467    }
2468
2469    private void onPointerUp(MotionEvent e) {
2470        final int actionIndex = MotionEventCompat.getActionIndex(e);
2471        if (MotionEventCompat.getPointerId(e, actionIndex) == mScrollPointerId) {
2472            // Pick a new pointer to pick up the slack.
2473            final int newIndex = actionIndex == 0 ? 1 : 0;
2474            mScrollPointerId = MotionEventCompat.getPointerId(e, newIndex);
2475            mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, newIndex) + 0.5f);
2476            mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, newIndex) + 0.5f);
2477        }
2478    }
2479
2480    // @Override
2481    public boolean onGenericMotionEvent(MotionEvent event) {
2482        if (mLayout == null) {
2483            return false;
2484        }
2485        if (mLayoutFrozen) {
2486            return false;
2487        }
2488        if ((MotionEventCompat.getSource(event) & InputDeviceCompat.SOURCE_CLASS_POINTER) != 0) {
2489            if (event.getAction() == MotionEventCompat.ACTION_SCROLL) {
2490                final float vScroll, hScroll;
2491                if (mLayout.canScrollVertically()) {
2492                    // Inverse the sign of the vertical scroll to align the scroll orientation
2493                    // with AbsListView.
2494                    vScroll = -MotionEventCompat
2495                            .getAxisValue(event, MotionEventCompat.AXIS_VSCROLL);
2496                } else {
2497                    vScroll = 0f;
2498                }
2499                if (mLayout.canScrollHorizontally()) {
2500                    hScroll = MotionEventCompat
2501                            .getAxisValue(event, MotionEventCompat.AXIS_HSCROLL);
2502                } else {
2503                    hScroll = 0f;
2504                }
2505
2506                if (vScroll != 0 || hScroll != 0) {
2507                    final float scrollFactor = getScrollFactor();
2508                    scrollByInternal((int) (hScroll * scrollFactor),
2509                            (int) (vScroll * scrollFactor), event);
2510                }
2511            }
2512        }
2513        return false;
2514    }
2515
2516    /**
2517     * Ported from View.getVerticalScrollFactor.
2518     */
2519    private float getScrollFactor() {
2520        if (mScrollFactor == Float.MIN_VALUE) {
2521            TypedValue outValue = new TypedValue();
2522            if (getContext().getTheme().resolveAttribute(
2523                    android.R.attr.listPreferredItemHeight, outValue, true)) {
2524                mScrollFactor = outValue.getDimension(
2525                        getContext().getResources().getDisplayMetrics());
2526            } else {
2527                return 0; //listPreferredItemHeight is not defined, no generic scrolling
2528            }
2529
2530        }
2531        return mScrollFactor;
2532    }
2533
2534    @Override
2535    protected void onMeasure(int widthSpec, int heightSpec) {
2536        if (mAdapterUpdateDuringMeasure) {
2537            eatRequestLayout();
2538            processAdapterUpdatesAndSetAnimationFlags();
2539
2540            if (mState.mRunPredictiveAnimations) {
2541                // TODO: try to provide a better approach.
2542                // When RV decides to run predictive animations, we need to measure in pre-layout
2543                // state so that pre-layout pass results in correct layout.
2544                // On the other hand, this will prevent the layout manager from resizing properly.
2545                mState.mInPreLayout = true;
2546            } else {
2547                // consume remaining updates to provide a consistent state with the layout pass.
2548                mAdapterHelper.consumeUpdatesInOnePass();
2549                mState.mInPreLayout = false;
2550            }
2551            mAdapterUpdateDuringMeasure = false;
2552            resumeRequestLayout(false);
2553        }
2554
2555        if (mAdapter != null) {
2556            mState.mItemCount = mAdapter.getItemCount();
2557        } else {
2558            mState.mItemCount = 0;
2559        }
2560        if (mLayout == null) {
2561            defaultOnMeasure(widthSpec, heightSpec);
2562        } else {
2563            mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
2564        }
2565
2566        mState.mInPreLayout = false; // clear
2567    }
2568
2569    /**
2570     * Used when onMeasure is called before layout manager is set
2571     */
2572    private void defaultOnMeasure(int widthSpec, int heightSpec) {
2573        final int widthMode = MeasureSpec.getMode(widthSpec);
2574        final int heightMode = MeasureSpec.getMode(heightSpec);
2575        final int widthSize = MeasureSpec.getSize(widthSpec);
2576        final int heightSize = MeasureSpec.getSize(heightSpec);
2577
2578        int width = 0;
2579        int height = 0;
2580
2581        switch (widthMode) {
2582            case MeasureSpec.EXACTLY:
2583            case MeasureSpec.AT_MOST:
2584                width = widthSize;
2585                break;
2586            case MeasureSpec.UNSPECIFIED:
2587            default:
2588                width = ViewCompat.getMinimumWidth(this);
2589                break;
2590        }
2591
2592        switch (heightMode) {
2593            case MeasureSpec.EXACTLY:
2594            case MeasureSpec.AT_MOST:
2595                height = heightSize;
2596                break;
2597            case MeasureSpec.UNSPECIFIED:
2598            default:
2599                height = ViewCompat.getMinimumHeight(this);
2600                break;
2601        }
2602
2603        setMeasuredDimension(width, height);
2604    }
2605
2606    @Override
2607    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
2608        super.onSizeChanged(w, h, oldw, oldh);
2609        if (w != oldw || h != oldh) {
2610            invalidateGlows();
2611        }
2612    }
2613
2614    /**
2615     * Sets the {@link ItemAnimator} that will handle animations involving changes
2616     * to the items in this RecyclerView. By default, RecyclerView instantiates and
2617     * uses an instance of {@link DefaultItemAnimator}. Whether item animations are
2618     * enabled for the RecyclerView depends on the ItemAnimator and whether
2619     * the LayoutManager {@link LayoutManager#supportsPredictiveItemAnimations()
2620     * supports item animations}.
2621     *
2622     * @param animator The ItemAnimator being set. If null, no animations will occur
2623     * when changes occur to the items in this RecyclerView.
2624     */
2625    public void setItemAnimator(ItemAnimator animator) {
2626        if (mItemAnimator != null) {
2627            mItemAnimator.endAnimations();
2628            mItemAnimator.setListener(null);
2629        }
2630        mItemAnimator = animator;
2631        if (mItemAnimator != null) {
2632            mItemAnimator.setListener(mItemAnimatorListener);
2633        }
2634    }
2635
2636    private void onEnterLayoutOrScroll() {
2637        mLayoutOrScrollCounter ++;
2638    }
2639
2640    private void onExitLayoutOrScroll() {
2641        mLayoutOrScrollCounter --;
2642        if (mLayoutOrScrollCounter < 1) {
2643            if (DEBUG && mLayoutOrScrollCounter < 0) {
2644                throw new IllegalStateException("layout or scroll counter cannot go below zero."
2645                        + "Some calls are not matching");
2646            }
2647            mLayoutOrScrollCounter = 0;
2648            dispatchContentChangedIfNecessary();
2649        }
2650    }
2651
2652    boolean isAccessibilityEnabled() {
2653        return mAccessibilityManager != null && mAccessibilityManager.isEnabled();
2654    }
2655
2656    private void dispatchContentChangedIfNecessary() {
2657        final int flags = mEatenAccessibilityChangeFlags;
2658        mEatenAccessibilityChangeFlags = 0;
2659        if (flags != 0 && isAccessibilityEnabled()) {
2660            final AccessibilityEvent event = AccessibilityEvent.obtain();
2661            event.setEventType(AccessibilityEventCompat.TYPE_WINDOW_CONTENT_CHANGED);
2662            AccessibilityEventCompat.setContentChangeTypes(event, flags);
2663            sendAccessibilityEventUnchecked(event);
2664        }
2665    }
2666
2667    /**
2668     * Returns whether RecyclerView is currently computing a layout.
2669     * <p>
2670     * If this method returns true, it means that RecyclerView is in a lockdown state and any
2671     * attempt to update adapter contents will result in an exception because adapter contents
2672     * cannot be changed while RecyclerView is trying to compute the layout.
2673     * <p>
2674     * It is very unlikely that your code will be running during this state as it is
2675     * called by the framework when a layout traversal happens or RecyclerView starts to scroll
2676     * in response to system events (touch, accessibility etc).
2677     * <p>
2678     * This case may happen if you have some custom logic to change adapter contents in
2679     * response to a View callback (e.g. focus change callback) which might be triggered during a
2680     * layout calculation. In these cases, you should just postpone the change using a Handler or a
2681     * similar mechanism.
2682     *
2683     * @return <code>true</code> if RecyclerView is currently computing a layout, <code>false</code>
2684     *         otherwise
2685     */
2686    public boolean isComputingLayout() {
2687        return mLayoutOrScrollCounter > 0;
2688    }
2689
2690    /**
2691     * Returns true if an accessibility event should not be dispatched now. This happens when an
2692     * accessibility request arrives while RecyclerView does not have a stable state which is very
2693     * hard to handle for a LayoutManager. Instead, this method records necessary information about
2694     * the event and dispatches a window change event after the critical section is finished.
2695     *
2696     * @return True if the accessibility event should be postponed.
2697     */
2698    boolean shouldDeferAccessibilityEvent(AccessibilityEvent event) {
2699        if (isComputingLayout()) {
2700            int type = 0;
2701            if (event != null) {
2702                type = AccessibilityEventCompat.getContentChangeTypes(event);
2703            }
2704            if (type == 0) {
2705                type = AccessibilityEventCompat.CONTENT_CHANGE_TYPE_UNDEFINED;
2706            }
2707            mEatenAccessibilityChangeFlags |= type;
2708            return true;
2709        }
2710        return false;
2711    }
2712
2713    @Override
2714    public void sendAccessibilityEventUnchecked(AccessibilityEvent event) {
2715        if (shouldDeferAccessibilityEvent(event)) {
2716            return;
2717        }
2718        super.sendAccessibilityEventUnchecked(event);
2719    }
2720
2721    /**
2722     * Gets the current ItemAnimator for this RecyclerView. A null return value
2723     * indicates that there is no animator and that item changes will happen without
2724     * any animations. By default, RecyclerView instantiates and
2725     * uses an instance of {@link DefaultItemAnimator}.
2726     *
2727     * @return ItemAnimator The current ItemAnimator. If null, no animations will occur
2728     * when changes occur to the items in this RecyclerView.
2729     */
2730    public ItemAnimator getItemAnimator() {
2731        return mItemAnimator;
2732    }
2733
2734    /**
2735     * Post a runnable to the next frame to run pending item animations. Only the first such
2736     * request will be posted, governed by the mPostedAnimatorRunner flag.
2737     */
2738    private void postAnimationRunner() {
2739        if (!mPostedAnimatorRunner && mIsAttached) {
2740            ViewCompat.postOnAnimation(this, mItemAnimatorRunner);
2741            mPostedAnimatorRunner = true;
2742        }
2743    }
2744
2745    private boolean predictiveItemAnimationsEnabled() {
2746        return (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations());
2747    }
2748
2749    /**
2750     * Consumes adapter updates and calculates which type of animations we want to run.
2751     * Called in onMeasure and dispatchLayout.
2752     * <p>
2753     * This method may process only the pre-layout state of updates or all of them.
2754     */
2755    private void processAdapterUpdatesAndSetAnimationFlags() {
2756        if (mDataSetHasChangedAfterLayout) {
2757            // Processing these items have no value since data set changed unexpectedly.
2758            // Instead, we just reset it.
2759            mAdapterHelper.reset();
2760            markKnownViewsInvalid();
2761            mLayout.onItemsChanged(this);
2762        }
2763        // simple animations are a subset of advanced animations (which will cause a
2764        // pre-layout step)
2765        // If layout supports predictive animations, pre-process to decide if we want to run them
2766        if (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations()) {
2767            mAdapterHelper.preProcess();
2768        } else {
2769            mAdapterHelper.consumeUpdatesInOnePass();
2770        }
2771        boolean animationTypeSupported = mItemsAddedOrRemoved || mItemsChanged;
2772        mState.mRunSimpleAnimations = mFirstLayoutComplete && mItemAnimator != null &&
2773                (mDataSetHasChangedAfterLayout || animationTypeSupported ||
2774                        mLayout.mRequestedSimpleAnimations) &&
2775                (!mDataSetHasChangedAfterLayout || mAdapter.hasStableIds());
2776        mState.mRunPredictiveAnimations = mState.mRunSimpleAnimations &&
2777                animationTypeSupported && !mDataSetHasChangedAfterLayout &&
2778                predictiveItemAnimationsEnabled();
2779    }
2780
2781    /**
2782     * Wrapper around layoutChildren() that handles animating changes caused by layout.
2783     * Animations work on the assumption that there are five different kinds of items
2784     * in play:
2785     * PERSISTENT: items are visible before and after layout
2786     * REMOVED: items were visible before layout and were removed by the app
2787     * ADDED: items did not exist before layout and were added by the app
2788     * DISAPPEARING: items exist in the data set before/after, but changed from
2789     * visible to non-visible in the process of layout (they were moved off
2790     * screen as a side-effect of other changes)
2791     * APPEARING: items exist in the data set before/after, but changed from
2792     * non-visible to visible in the process of layout (they were moved on
2793     * screen as a side-effect of other changes)
2794     * The overall approach figures out what items exist before/after layout and
2795     * infers one of the five above states for each of the items. Then the animations
2796     * are set up accordingly:
2797     * PERSISTENT views are animated via
2798     * {@link ItemAnimator#animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)}
2799     * DISAPPEARING views are animated via
2800     * {@link ItemAnimator#animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)}
2801     * APPEARING views are animated via
2802     * {@link ItemAnimator#animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)}
2803     * and changed views are animated via
2804     * {@link ItemAnimator#animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)}.
2805     */
2806    void dispatchLayout() {
2807        if (mAdapter == null) {
2808            Log.e(TAG, "No adapter attached; skipping layout");
2809            return;
2810        }
2811        if (mLayout == null) {
2812            Log.e(TAG, "No layout manager attached; skipping layout");
2813            return;
2814        }
2815        mViewInfoStore.clear();
2816        eatRequestLayout();
2817        onEnterLayoutOrScroll();
2818
2819        processAdapterUpdatesAndSetAnimationFlags();
2820        mState.mTrackOldChangeHolders = mState.mRunSimpleAnimations && mItemsChanged;
2821        mItemsAddedOrRemoved = mItemsChanged = false;
2822        mState.mInPreLayout = mState.mRunPredictiveAnimations;
2823        mState.mItemCount = mAdapter.getItemCount();
2824        findMinMaxChildLayoutPositions(mMinMaxLayoutPositions);
2825
2826        if (mState.mRunSimpleAnimations) {
2827            // Step 0: Find out where all non-removed items are, pre-layout
2828            int count = mChildHelper.getChildCount();
2829            for (int i = 0; i < count; ++i) {
2830                final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
2831                if (holder.shouldIgnore() || (holder.isInvalid() && !mAdapter.hasStableIds())) {
2832                    continue;
2833                }
2834                final ItemHolderInfo animationInfo = mItemAnimator
2835                        .recordPreLayoutInformation(mState, holder,
2836                                ItemAnimator.buildAdapterChangeFlagsForAnimations(holder),
2837                                holder.getUnmodifiedPayloads());
2838                mViewInfoStore.addToPreLayout(holder, animationInfo);
2839                if (mState.mTrackOldChangeHolders && holder.isUpdated() && !holder.isRemoved()
2840                        && !holder.shouldIgnore() && !holder.isInvalid()) {
2841                    long key = getChangedHolderKey(holder);
2842                    // This is NOT the only place where a ViewHolder is added to old change holders
2843                    // list. There is another case where:
2844                    //    * A VH is currently hidden but not deleted
2845                    //    * The hidden item is changed in the adapter
2846                    //    * Layout manager decides to layout the item in the pre-Layout pass (step1)
2847                    // When this case is detected, RV will un-hide that view and add to the old
2848                    // change holders list.
2849                    mViewInfoStore.addToOldChangeHolders(key, holder);
2850                }
2851            }
2852        }
2853        if (mState.mRunPredictiveAnimations) {
2854            // Step 1: run prelayout: This will use the old positions of items. The layout manager
2855            // is expected to layout everything, even removed items (though not to add removed
2856            // items back to the container). This gives the pre-layout position of APPEARING views
2857            // which come into existence as part of the real layout.
2858
2859            // Save old positions so that LayoutManager can run its mapping logic.
2860            saveOldPositions();
2861            final boolean didStructureChange = mState.mStructureChanged;
2862            mState.mStructureChanged = false;
2863            // temporarily disable flag because we are asking for previous layout
2864            mLayout.onLayoutChildren(mRecycler, mState);
2865            mState.mStructureChanged = didStructureChange;
2866
2867            for (int i = 0; i < mChildHelper.getChildCount(); ++i) {
2868                final View child = mChildHelper.getChildAt(i);
2869                final ViewHolder viewHolder = getChildViewHolderInt(child);
2870                if (viewHolder.shouldIgnore()) {
2871                    continue;
2872                }
2873                if (!mViewInfoStore.isInPreLayout(viewHolder)) {
2874                    int flags = ItemAnimator.buildAdapterChangeFlagsForAnimations(viewHolder);
2875                    boolean wasHidden = viewHolder
2876                            .hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
2877                    if (!wasHidden) {
2878                        flags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT;
2879                    }
2880                    final ItemHolderInfo animationInfo = mItemAnimator.recordPreLayoutInformation(
2881                            mState, viewHolder, flags, viewHolder.getUnmodifiedPayloads());
2882                    if (wasHidden) {
2883                        recordAnimationInfoIfBouncedHiddenView(viewHolder, animationInfo);
2884                    } else {
2885                        mViewInfoStore.addToAppearedInPreLayoutHolders(viewHolder, animationInfo);
2886                    }
2887                }
2888            }
2889            // we don't process disappearing list because they may re-appear in post layout pass.
2890            clearOldPositions();
2891            mAdapterHelper.consumePostponedUpdates();
2892        } else {
2893            clearOldPositions();
2894        }
2895        mState.mItemCount = mAdapter.getItemCount();
2896        mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;
2897
2898        // Step 2: Run layout
2899        mState.mInPreLayout = false;
2900        mLayout.onLayoutChildren(mRecycler, mState);
2901
2902        mState.mStructureChanged = false;
2903        mPendingSavedState = null;
2904
2905        // onLayoutChildren may have caused client code to disable item animations; re-check
2906        mState.mRunSimpleAnimations = mState.mRunSimpleAnimations && mItemAnimator != null;
2907
2908        if (mState.mRunSimpleAnimations) {
2909            // Step 3: Find out where things are now, and process change animations.
2910            int count = mChildHelper.getChildCount();
2911            for (int i = 0; i < count; ++i) {
2912                ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
2913                if (holder.shouldIgnore()) {
2914                    continue;
2915                }
2916                long key = getChangedHolderKey(holder);
2917                final ItemHolderInfo animationInfo = mItemAnimator
2918                        .recordPostLayoutInformation(mState, holder);
2919                ViewHolder oldChangeViewHolder = mViewInfoStore.getFromOldChangeHolders(key);
2920                if (oldChangeViewHolder != null && !oldChangeViewHolder.shouldIgnore()) {
2921                    // run a change animation
2922                    final ItemHolderInfo preInfo = mViewInfoStore.popFromPreLayout(
2923                            oldChangeViewHolder);
2924                    animateChange(oldChangeViewHolder, holder, preInfo, animationInfo);
2925                } else {
2926                    mViewInfoStore.addToPostLayout(holder, animationInfo);
2927                }
2928            }
2929
2930            // Step 4: Process view info lists and trigger animations
2931            mViewInfoStore.process(mViewInfoProcessCallback);
2932        }
2933        resumeRequestLayout(false);
2934        mLayout.removeAndRecycleScrapInt(mRecycler);
2935        mState.mPreviousLayoutItemCount = mState.mItemCount;
2936        mDataSetHasChangedAfterLayout = false;
2937        mState.mRunSimpleAnimations = false;
2938
2939        mState.mRunPredictiveAnimations = false;
2940        onExitLayoutOrScroll();
2941        mLayout.mRequestedSimpleAnimations = false;
2942        if (mRecycler.mChangedScrap != null) {
2943            mRecycler.mChangedScrap.clear();
2944        }
2945        mViewInfoStore.clear();
2946        if (didChildRangeChange(mMinMaxLayoutPositions[0], mMinMaxLayoutPositions[1])) {
2947            dispatchOnScrolled(0, 0);
2948        }
2949    }
2950
2951    /**
2952     * Records the animation information for a view holder that was bounced from hidden list. It
2953     * also clears the bounce back flag.
2954     */
2955    private void recordAnimationInfoIfBouncedHiddenView(ViewHolder viewHolder,
2956            ItemHolderInfo animationInfo) {
2957        // looks like this view bounced back from hidden list!
2958        viewHolder.setFlags(0, ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
2959        if (mState.mTrackOldChangeHolders && viewHolder.isUpdated()
2960                && !viewHolder.isRemoved() && !viewHolder.shouldIgnore()) {
2961            long key = getChangedHolderKey(viewHolder);
2962            mViewInfoStore.addToOldChangeHolders(key, viewHolder);
2963        }
2964        mViewInfoStore.addToPreLayout(viewHolder, animationInfo);
2965    }
2966
2967    private void findMinMaxChildLayoutPositions(int[] into) {
2968        final int count = mChildHelper.getChildCount();
2969        if (count == 0) {
2970            into[0] = 0;
2971            into[1] = 0;
2972            return;
2973        }
2974        int minPositionPreLayout = Integer.MAX_VALUE;
2975        int maxPositionPreLayout = Integer.MIN_VALUE;
2976        for (int i = 0; i < count; ++i) {
2977            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
2978            if (holder.shouldIgnore()) {
2979                continue;
2980            }
2981            final int pos = holder.getLayoutPosition();
2982            if (pos < minPositionPreLayout) {
2983                minPositionPreLayout = pos;
2984            }
2985            if (pos > maxPositionPreLayout) {
2986                maxPositionPreLayout = pos;
2987            }
2988        }
2989        into[0] = minPositionPreLayout;
2990        into[1] = maxPositionPreLayout;
2991    }
2992
2993    private boolean didChildRangeChange(int minPositionPreLayout, int maxPositionPreLayout) {
2994        int count = mChildHelper.getChildCount();
2995        if (count == 0) {
2996            return minPositionPreLayout != 0 || maxPositionPreLayout != 0;
2997        }
2998        for (int i = 0; i < count; ++i) {
2999            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getChildAt(i));
3000            if (holder.shouldIgnore()) {
3001                continue;
3002            }
3003            final int pos = holder.getLayoutPosition();
3004            if (pos < minPositionPreLayout || pos > maxPositionPreLayout) {
3005                return true;
3006            }
3007        }
3008        return false;
3009    }
3010
3011    @Override
3012    protected void removeDetachedView(View child, boolean animate) {
3013        ViewHolder vh = getChildViewHolderInt(child);
3014        if (vh != null) {
3015            if (vh.isTmpDetached()) {
3016                vh.clearTmpDetachFlag();
3017            } else if (!vh.shouldIgnore()) {
3018                throw new IllegalArgumentException("Called removeDetachedView with a view which"
3019                        + " is not flagged as tmp detached." + vh);
3020            }
3021        }
3022        dispatchChildDetached(child);
3023        super.removeDetachedView(child, animate);
3024    }
3025
3026    /**
3027     * Returns a unique key to be used while handling change animations.
3028     * It might be child's position or stable id depending on the adapter type.
3029     */
3030    long getChangedHolderKey(ViewHolder holder) {
3031        return mAdapter.hasStableIds() ? holder.getItemId() : holder.mPosition;
3032    }
3033
3034    private void animateAppearance(@NonNull ViewHolder itemHolder,
3035            @Nullable ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo) {
3036        itemHolder.setIsRecyclable(false);
3037        if (mItemAnimator.animateAppearance(itemHolder, preLayoutInfo, postLayoutInfo)) {
3038            postAnimationRunner();
3039        }
3040    }
3041
3042    private void animateDisappearance(@NonNull ViewHolder holder,
3043            @NonNull ItemHolderInfo preLayoutInfo, @Nullable ItemHolderInfo postLayoutInfo) {
3044        addAnimatingView(holder);
3045        holder.setIsRecyclable(false);
3046        if (mItemAnimator.animateDisappearance(holder, preLayoutInfo, postLayoutInfo)) {
3047            postAnimationRunner();
3048        }
3049    }
3050
3051    private void animateChange(@NonNull ViewHolder oldHolder, @NonNull ViewHolder newHolder,
3052            @NonNull ItemHolderInfo preInfo, @NonNull ItemHolderInfo postInfo) {
3053        oldHolder.setIsRecyclable(false);
3054        if (oldHolder != newHolder) {
3055            oldHolder.mShadowedHolder = newHolder;
3056            // old holder should disappear after animation ends
3057            addAnimatingView(oldHolder);
3058            mRecycler.unscrapView(oldHolder);
3059            newHolder.setIsRecyclable(false);
3060            newHolder.mShadowingHolder = oldHolder;
3061        }
3062        if (mItemAnimator.animateChange(oldHolder, newHolder, preInfo, postInfo)) {
3063            postAnimationRunner();
3064        }
3065    }
3066
3067    @Override
3068    protected void onLayout(boolean changed, int l, int t, int r, int b) {
3069        eatRequestLayout();
3070        TraceCompat.beginSection(TRACE_ON_LAYOUT_TAG);
3071        dispatchLayout();
3072        TraceCompat.endSection();
3073        resumeRequestLayout(false);
3074        mFirstLayoutComplete = true;
3075    }
3076
3077    @Override
3078    public void requestLayout() {
3079        if (!mEatRequestLayout && !mLayoutFrozen) {
3080            super.requestLayout();
3081        } else {
3082            mLayoutRequestEaten = true;
3083        }
3084    }
3085
3086    void markItemDecorInsetsDirty() {
3087        final int childCount = mChildHelper.getUnfilteredChildCount();
3088        for (int i = 0; i < childCount; i++) {
3089            final View child = mChildHelper.getUnfilteredChildAt(i);
3090            ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
3091        }
3092        mRecycler.markItemDecorInsetsDirty();
3093    }
3094
3095    @Override
3096    public void draw(Canvas c) {
3097        super.draw(c);
3098
3099        final int count = mItemDecorations.size();
3100        for (int i = 0; i < count; i++) {
3101            mItemDecorations.get(i).onDrawOver(c, this, mState);
3102        }
3103        // TODO If padding is not 0 and chilChildrenToPadding is false, to draw glows properly, we
3104        // need find children closest to edges. Not sure if it is worth the effort.
3105        boolean needsInvalidate = false;
3106        if (mLeftGlow != null && !mLeftGlow.isFinished()) {
3107            final int restore = c.save();
3108            final int padding = mClipToPadding ? getPaddingBottom() : 0;
3109            c.rotate(270);
3110            c.translate(-getHeight() + padding, 0);
3111            needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
3112            c.restoreToCount(restore);
3113        }
3114        if (mTopGlow != null && !mTopGlow.isFinished()) {
3115            final int restore = c.save();
3116            if (mClipToPadding) {
3117                c.translate(getPaddingLeft(), getPaddingTop());
3118            }
3119            needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
3120            c.restoreToCount(restore);
3121        }
3122        if (mRightGlow != null && !mRightGlow.isFinished()) {
3123            final int restore = c.save();
3124            final int width = getWidth();
3125            final int padding = mClipToPadding ? getPaddingTop() : 0;
3126            c.rotate(90);
3127            c.translate(-padding, -width);
3128            needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
3129            c.restoreToCount(restore);
3130        }
3131        if (mBottomGlow != null && !mBottomGlow.isFinished()) {
3132            final int restore = c.save();
3133            c.rotate(180);
3134            if (mClipToPadding) {
3135                c.translate(-getWidth() + getPaddingRight(), -getHeight() + getPaddingBottom());
3136            } else {
3137                c.translate(-getWidth(), -getHeight());
3138            }
3139            needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
3140            c.restoreToCount(restore);
3141        }
3142
3143        // If some views are animating, ItemDecorators are likely to move/change with them.
3144        // Invalidate RecyclerView to re-draw decorators. This is still efficient because children's
3145        // display lists are not invalidated.
3146        if (!needsInvalidate && mItemAnimator != null && mItemDecorations.size() > 0 &&
3147                mItemAnimator.isRunning()) {
3148            needsInvalidate = true;
3149        }
3150
3151        if (needsInvalidate) {
3152            ViewCompat.postInvalidateOnAnimation(this);
3153        }
3154    }
3155
3156    @Override
3157    public void onDraw(Canvas c) {
3158        super.onDraw(c);
3159
3160        final int count = mItemDecorations.size();
3161        for (int i = 0; i < count; i++) {
3162            mItemDecorations.get(i).onDraw(c, this, mState);
3163        }
3164    }
3165
3166    @Override
3167    protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
3168        return p instanceof LayoutParams && mLayout.checkLayoutParams((LayoutParams) p);
3169    }
3170
3171    @Override
3172    protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
3173        if (mLayout == null) {
3174            throw new IllegalStateException("RecyclerView has no LayoutManager");
3175        }
3176        return mLayout.generateDefaultLayoutParams();
3177    }
3178
3179    @Override
3180    public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
3181        if (mLayout == null) {
3182            throw new IllegalStateException("RecyclerView has no LayoutManager");
3183        }
3184        return mLayout.generateLayoutParams(getContext(), attrs);
3185    }
3186
3187    @Override
3188    protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
3189        if (mLayout == null) {
3190            throw new IllegalStateException("RecyclerView has no LayoutManager");
3191        }
3192        return mLayout.generateLayoutParams(p);
3193    }
3194
3195    /**
3196     * Returns true if RecyclerView is currently running some animations.
3197     * <p>
3198     * If you want to be notified when animations are finished, use
3199     * {@link ItemAnimator#isRunning(ItemAnimator.ItemAnimatorFinishedListener)}.
3200     *
3201     * @return True if there are some item animations currently running or waiting to be started.
3202     */
3203    public boolean isAnimating() {
3204        return mItemAnimator != null && mItemAnimator.isRunning();
3205    }
3206
3207    void saveOldPositions() {
3208        final int childCount = mChildHelper.getUnfilteredChildCount();
3209        for (int i = 0; i < childCount; i++) {
3210            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3211            if (DEBUG && holder.mPosition == -1 && !holder.isRemoved()) {
3212                throw new IllegalStateException("view holder cannot have position -1 unless it"
3213                        + " is removed");
3214            }
3215            if (!holder.shouldIgnore()) {
3216                holder.saveOldPosition();
3217            }
3218        }
3219    }
3220
3221    void clearOldPositions() {
3222        final int childCount = mChildHelper.getUnfilteredChildCount();
3223        for (int i = 0; i < childCount; i++) {
3224            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3225            if (!holder.shouldIgnore()) {
3226                holder.clearOldPosition();
3227            }
3228        }
3229        mRecycler.clearOldPositions();
3230    }
3231
3232    void offsetPositionRecordsForMove(int from, int to) {
3233        final int childCount = mChildHelper.getUnfilteredChildCount();
3234        final int start, end, inBetweenOffset;
3235        if (from < to) {
3236            start = from;
3237            end = to;
3238            inBetweenOffset = -1;
3239        } else {
3240            start = to;
3241            end = from;
3242            inBetweenOffset = 1;
3243        }
3244
3245        for (int i = 0; i < childCount; i++) {
3246            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3247            if (holder == null || holder.mPosition < start || holder.mPosition > end) {
3248                continue;
3249            }
3250            if (DEBUG) {
3251                Log.d(TAG, "offsetPositionRecordsForMove attached child " + i + " holder " +
3252                        holder);
3253            }
3254            if (holder.mPosition == from) {
3255                holder.offsetPosition(to - from, false);
3256            } else {
3257                holder.offsetPosition(inBetweenOffset, false);
3258            }
3259
3260            mState.mStructureChanged = true;
3261        }
3262        mRecycler.offsetPositionRecordsForMove(from, to);
3263        requestLayout();
3264    }
3265
3266    void offsetPositionRecordsForInsert(int positionStart, int itemCount) {
3267        final int childCount = mChildHelper.getUnfilteredChildCount();
3268        for (int i = 0; i < childCount; i++) {
3269            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3270            if (holder != null && !holder.shouldIgnore() && holder.mPosition >= positionStart) {
3271                if (DEBUG) {
3272                    Log.d(TAG, "offsetPositionRecordsForInsert attached child " + i + " holder " +
3273                            holder + " now at position " + (holder.mPosition + itemCount));
3274                }
3275                holder.offsetPosition(itemCount, false);
3276                mState.mStructureChanged = true;
3277            }
3278        }
3279        mRecycler.offsetPositionRecordsForInsert(positionStart, itemCount);
3280        requestLayout();
3281    }
3282
3283    void offsetPositionRecordsForRemove(int positionStart, int itemCount,
3284            boolean applyToPreLayout) {
3285        final int positionEnd = positionStart + itemCount;
3286        final int childCount = mChildHelper.getUnfilteredChildCount();
3287        for (int i = 0; i < childCount; i++) {
3288            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3289            if (holder != null && !holder.shouldIgnore()) {
3290                if (holder.mPosition >= positionEnd) {
3291                    if (DEBUG) {
3292                        Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
3293                                " holder " + holder + " now at position " +
3294                                (holder.mPosition - itemCount));
3295                    }
3296                    holder.offsetPosition(-itemCount, applyToPreLayout);
3297                    mState.mStructureChanged = true;
3298                } else if (holder.mPosition >= positionStart) {
3299                    if (DEBUG) {
3300                        Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
3301                                " holder " + holder + " now REMOVED");
3302                    }
3303                    holder.flagRemovedAndOffsetPosition(positionStart - 1, -itemCount,
3304                            applyToPreLayout);
3305                    mState.mStructureChanged = true;
3306                }
3307            }
3308        }
3309        mRecycler.offsetPositionRecordsForRemove(positionStart, itemCount, applyToPreLayout);
3310        requestLayout();
3311    }
3312
3313    /**
3314     * Rebind existing views for the given range, or create as needed.
3315     *
3316     * @param positionStart Adapter position to start at
3317     * @param itemCount Number of views that must explicitly be rebound
3318     */
3319    void viewRangeUpdate(int positionStart, int itemCount, Object payload) {
3320        final int childCount = mChildHelper.getUnfilteredChildCount();
3321        final int positionEnd = positionStart + itemCount;
3322
3323        for (int i = 0; i < childCount; i++) {
3324            final View child = mChildHelper.getUnfilteredChildAt(i);
3325            final ViewHolder holder = getChildViewHolderInt(child);
3326            if (holder == null || holder.shouldIgnore()) {
3327                continue;
3328            }
3329            if (holder.mPosition >= positionStart && holder.mPosition < positionEnd) {
3330                // We re-bind these view holders after pre-processing is complete so that
3331                // ViewHolders have their final positions assigned.
3332                holder.addFlags(ViewHolder.FLAG_UPDATE);
3333                holder.addChangePayload(payload);
3334                // lp cannot be null since we get ViewHolder from it.
3335                ((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
3336            }
3337        }
3338        mRecycler.viewRangeUpdate(positionStart, itemCount);
3339    }
3340
3341    private boolean canReuseUpdatedViewHolder(ViewHolder viewHolder) {
3342        return mItemAnimator == null || mItemAnimator.canReuseUpdatedViewHolder(viewHolder);
3343    }
3344
3345    private void setDataSetChangedAfterLayout() {
3346        if (mDataSetHasChangedAfterLayout) {
3347            return;
3348        }
3349        mDataSetHasChangedAfterLayout = true;
3350        final int childCount = mChildHelper.getUnfilteredChildCount();
3351        for (int i = 0; i < childCount; i++) {
3352            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3353            if (holder != null && !holder.shouldIgnore()) {
3354                holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
3355            }
3356        }
3357        mRecycler.setAdapterPositionsAsUnknown();
3358    }
3359
3360    /**
3361     * Mark all known views as invalid. Used in response to a, "the whole world might have changed"
3362     * data change event.
3363     */
3364    void markKnownViewsInvalid() {
3365        final int childCount = mChildHelper.getUnfilteredChildCount();
3366        for (int i = 0; i < childCount; i++) {
3367            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3368            if (holder != null && !holder.shouldIgnore()) {
3369                holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
3370            }
3371        }
3372        markItemDecorInsetsDirty();
3373        mRecycler.markKnownViewsInvalid();
3374    }
3375
3376    /**
3377     * Invalidates all ItemDecorations. If RecyclerView has item decorations, calling this method
3378     * will trigger a {@link #requestLayout()} call.
3379     */
3380    public void invalidateItemDecorations() {
3381        if (mItemDecorations.size() == 0) {
3382            return;
3383        }
3384        if (mLayout != null) {
3385            mLayout.assertNotInLayoutOrScroll("Cannot invalidate item decorations during a scroll"
3386                    + " or layout");
3387        }
3388        markItemDecorInsetsDirty();
3389        requestLayout();
3390    }
3391
3392    /**
3393     * Retrieve the {@link ViewHolder} for the given child view.
3394     *
3395     * @param child Child of this RecyclerView to query for its ViewHolder
3396     * @return The child view's ViewHolder
3397     */
3398    public ViewHolder getChildViewHolder(View child) {
3399        final ViewParent parent = child.getParent();
3400        if (parent != null && parent != this) {
3401            throw new IllegalArgumentException("View " + child + " is not a direct child of " +
3402                    this);
3403        }
3404        return getChildViewHolderInt(child);
3405    }
3406
3407    static ViewHolder getChildViewHolderInt(View child) {
3408        if (child == null) {
3409            return null;
3410        }
3411        return ((LayoutParams) child.getLayoutParams()).mViewHolder;
3412    }
3413
3414    /**
3415     * @deprecated use {@link #getChildAdapterPosition(View)} or
3416     * {@link #getChildLayoutPosition(View)}.
3417     */
3418    @Deprecated
3419    public int getChildPosition(View child) {
3420        return getChildAdapterPosition(child);
3421    }
3422
3423    /**
3424     * Return the adapter position that the given child view corresponds to.
3425     *
3426     * @param child Child View to query
3427     * @return Adapter position corresponding to the given view or {@link #NO_POSITION}
3428     */
3429    public int getChildAdapterPosition(View child) {
3430        final ViewHolder holder = getChildViewHolderInt(child);
3431        return holder != null ? holder.getAdapterPosition() : NO_POSITION;
3432    }
3433
3434    /**
3435     * Return the adapter position of the given child view as of the latest completed layout pass.
3436     * <p>
3437     * This position may not be equal to Item's adapter position if there are pending changes
3438     * in the adapter which have not been reflected to the layout yet.
3439     *
3440     * @param child Child View to query
3441     * @return Adapter position of the given View as of last layout pass or {@link #NO_POSITION} if
3442     * the View is representing a removed item.
3443     */
3444    public int getChildLayoutPosition(View child) {
3445        final ViewHolder holder = getChildViewHolderInt(child);
3446        return holder != null ? holder.getLayoutPosition() : NO_POSITION;
3447    }
3448
3449    /**
3450     * Return the stable item id that the given child view corresponds to.
3451     *
3452     * @param child Child View to query
3453     * @return Item id corresponding to the given view or {@link #NO_ID}
3454     */
3455    public long getChildItemId(View child) {
3456        if (mAdapter == null || !mAdapter.hasStableIds()) {
3457            return NO_ID;
3458        }
3459        final ViewHolder holder = getChildViewHolderInt(child);
3460        return holder != null ? holder.getItemId() : NO_ID;
3461    }
3462
3463    /**
3464     * @deprecated use {@link #findViewHolderForLayoutPosition(int)} or
3465     * {@link #findViewHolderForAdapterPosition(int)}
3466     */
3467    @Deprecated
3468    public ViewHolder findViewHolderForPosition(int position) {
3469        return findViewHolderForPosition(position, false);
3470    }
3471
3472    /**
3473     * Return the ViewHolder for the item in the given position of the data set as of the latest
3474     * layout pass.
3475     * <p>
3476     * This method checks only the children of RecyclerView. If the item at the given
3477     * <code>position</code> is not laid out, it <em>will not</em> create a new one.
3478     * <p>
3479     * Note that when Adapter contents change, ViewHolder positions are not updated until the
3480     * next layout calculation. If there are pending adapter updates, the return value of this
3481     * method may not match your adapter contents. You can use
3482     * #{@link ViewHolder#getAdapterPosition()} to get the current adapter position of a ViewHolder.
3483     *
3484     * @param position The position of the item in the data set of the adapter
3485     * @return The ViewHolder at <code>position</code> or null if there is no such item
3486     */
3487    public ViewHolder findViewHolderForLayoutPosition(int position) {
3488        return findViewHolderForPosition(position, false);
3489    }
3490
3491    /**
3492     * Return the ViewHolder for the item in the given position of the data set. Unlike
3493     * {@link #findViewHolderForLayoutPosition(int)} this method takes into account any pending
3494     * adapter changes that may not be reflected to the layout yet. On the other hand, if
3495     * {@link Adapter#notifyDataSetChanged()} has been called but the new layout has not been
3496     * calculated yet, this method will return <code>null</code> since the new positions of views
3497     * are unknown until the layout is calculated.
3498     * <p>
3499     * This method checks only the children of RecyclerView. If the item at the given
3500     * <code>position</code> is not laid out, it <em>will not</em> create a new one.
3501     *
3502     * @param position The position of the item in the data set of the adapter
3503     * @return The ViewHolder at <code>position</code> or null if there is no such item
3504     */
3505    public ViewHolder findViewHolderForAdapterPosition(int position) {
3506        if (mDataSetHasChangedAfterLayout) {
3507            return null;
3508        }
3509        final int childCount = mChildHelper.getUnfilteredChildCount();
3510        for (int i = 0; i < childCount; i++) {
3511            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3512            if (holder != null && !holder.isRemoved() && getAdapterPositionFor(holder) == position) {
3513                return holder;
3514            }
3515        }
3516        return null;
3517    }
3518
3519    ViewHolder findViewHolderForPosition(int position, boolean checkNewPosition) {
3520        final int childCount = mChildHelper.getUnfilteredChildCount();
3521        for (int i = 0; i < childCount; i++) {
3522            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3523            if (holder != null && !holder.isRemoved()) {
3524                if (checkNewPosition) {
3525                    if (holder.mPosition == position) {
3526                        return holder;
3527                    }
3528                } else if (holder.getLayoutPosition() == position) {
3529                    return holder;
3530                }
3531            }
3532        }
3533        // This method should not query cached views. It creates a problem during adapter updates
3534        // when we are dealing with already laid out views. Also, for the public method, it is more
3535        // reasonable to return null if position is not laid out.
3536        return null;
3537    }
3538
3539    /**
3540     * Return the ViewHolder for the item with the given id. The RecyclerView must
3541     * use an Adapter with {@link Adapter#setHasStableIds(boolean) stableIds} to
3542     * return a non-null value.
3543     * <p>
3544     * This method checks only the children of RecyclerView. If the item with the given
3545     * <code>id</code> is not laid out, it <em>will not</em> create a new one.
3546     *
3547     * @param id The id for the requested item
3548     * @return The ViewHolder with the given <code>id</code> or null if there is no such item
3549     */
3550    public ViewHolder findViewHolderForItemId(long id) {
3551        final int childCount = mChildHelper.getUnfilteredChildCount();
3552        for (int i = 0; i < childCount; i++) {
3553            final ViewHolder holder = getChildViewHolderInt(mChildHelper.getUnfilteredChildAt(i));
3554            if (holder != null && holder.getItemId() == id) {
3555                return holder;
3556            }
3557        }
3558        // this method should not query cached views. They are not children so they
3559        // should not be returned in this public method
3560        return null;
3561    }
3562
3563    /**
3564     * Find the topmost view under the given point.
3565     *
3566     * @param x Horizontal position in pixels to search
3567     * @param y Vertical position in pixels to search
3568     * @return The child view under (x, y) or null if no matching child is found
3569     */
3570    public View findChildViewUnder(float x, float y) {
3571        final int count = mChildHelper.getChildCount();
3572        for (int i = count - 1; i >= 0; i--) {
3573            final View child = mChildHelper.getChildAt(i);
3574            final float translationX = ViewCompat.getTranslationX(child);
3575            final float translationY = ViewCompat.getTranslationY(child);
3576            if (x >= child.getLeft() + translationX &&
3577                    x <= child.getRight() + translationX &&
3578                    y >= child.getTop() + translationY &&
3579                    y <= child.getBottom() + translationY) {
3580                return child;
3581            }
3582        }
3583        return null;
3584    }
3585
3586    @Override
3587    public boolean drawChild(Canvas canvas, View child, long drawingTime) {
3588        return super.drawChild(canvas, child, drawingTime);
3589    }
3590
3591    /**
3592     * Offset the bounds of all child views by <code>dy</code> pixels.
3593     * Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
3594     *
3595     * @param dy Vertical pixel offset to apply to the bounds of all child views
3596     */
3597    public void offsetChildrenVertical(int dy) {
3598        final int childCount = mChildHelper.getChildCount();
3599        for (int i = 0; i < childCount; i++) {
3600            mChildHelper.getChildAt(i).offsetTopAndBottom(dy);
3601        }
3602    }
3603
3604    /**
3605     * Called when an item view is attached to this RecyclerView.
3606     *
3607     * <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
3608     * of child views as they become attached. This will be called before a
3609     * {@link LayoutManager} measures or lays out the view and is a good time to perform these
3610     * changes.</p>
3611     *
3612     * @param child Child view that is now attached to this RecyclerView and its associated window
3613     */
3614    public void onChildAttachedToWindow(View child) {
3615    }
3616
3617    /**
3618     * Called when an item view is detached from this RecyclerView.
3619     *
3620     * <p>Subclasses of RecyclerView may want to perform extra bookkeeping or modifications
3621     * of child views as they become detached. This will be called as a
3622     * {@link LayoutManager} fully detaches the child view from the parent and its window.</p>
3623     *
3624     * @param child Child view that is now detached from this RecyclerView and its associated window
3625     */
3626    public void onChildDetachedFromWindow(View child) {
3627    }
3628
3629    /**
3630     * Offset the bounds of all child views by <code>dx</code> pixels.
3631     * Useful for implementing simple scrolling in {@link LayoutManager LayoutManagers}.
3632     *
3633     * @param dx Horizontal pixel offset to apply to the bounds of all child views
3634     */
3635    public void offsetChildrenHorizontal(int dx) {
3636        final int childCount = mChildHelper.getChildCount();
3637        for (int i = 0; i < childCount; i++) {
3638            mChildHelper.getChildAt(i).offsetLeftAndRight(dx);
3639        }
3640    }
3641
3642    Rect getItemDecorInsetsForChild(View child) {
3643        final LayoutParams lp = (LayoutParams) child.getLayoutParams();
3644        if (!lp.mInsetsDirty) {
3645            return lp.mDecorInsets;
3646        }
3647
3648        final Rect insets = lp.mDecorInsets;
3649        insets.set(0, 0, 0, 0);
3650        final int decorCount = mItemDecorations.size();
3651        for (int i = 0; i < decorCount; i++) {
3652            mTempRect.set(0, 0, 0, 0);
3653            mItemDecorations.get(i).getItemOffsets(mTempRect, child, this, mState);
3654            insets.left += mTempRect.left;
3655            insets.top += mTempRect.top;
3656            insets.right += mTempRect.right;
3657            insets.bottom += mTempRect.bottom;
3658        }
3659        lp.mInsetsDirty = false;
3660        return insets;
3661    }
3662
3663    /**
3664     * Called when the scroll position of this RecyclerView changes. Subclasses should use
3665     * this method to respond to scrolling within the adapter's data set instead of an explicit
3666     * listener.
3667     *
3668     * <p>This method will always be invoked before listeners. If a subclass needs to perform
3669     * any additional upkeep or bookkeeping after scrolling but before listeners run,
3670     * this is a good place to do so.</p>
3671     *
3672     * <p>This differs from {@link View#onScrollChanged(int, int, int, int)} in that it receives
3673     * the distance scrolled in either direction within the adapter's data set instead of absolute
3674     * scroll coordinates. Since RecyclerView cannot compute the absolute scroll position from
3675     * any arbitrary point in the data set, <code>onScrollChanged</code> will always receive
3676     * the current {@link View#getScrollX()} and {@link View#getScrollY()} values which
3677     * do not correspond to the data set scroll position. However, some subclasses may choose
3678     * to use these fields as special offsets.</p>
3679     *
3680     * @param dx horizontal distance scrolled in pixels
3681     * @param dy vertical distance scrolled in pixels
3682     */
3683    public void onScrolled(int dx, int dy) {
3684        // Do nothing
3685    }
3686
3687    void dispatchOnScrolled(int hresult, int vresult) {
3688        // Pass the current scrollX/scrollY values; no actual change in these properties occurred
3689        // but some general-purpose code may choose to respond to changes this way.
3690        final int scrollX = getScrollX();
3691        final int scrollY = getScrollY();
3692        onScrollChanged(scrollX, scrollY, scrollX, scrollY);
3693
3694        // Pass the real deltas to onScrolled, the RecyclerView-specific method.
3695        onScrolled(hresult, vresult);
3696
3697        // Invoke listeners last. Subclassed view methods always handle the event first.
3698        // All internal state is consistent by the time listeners are invoked.
3699        if (mScrollListener != null) {
3700            mScrollListener.onScrolled(this, hresult, vresult);
3701        }
3702        if (mScrollListeners != null) {
3703            for (int i = mScrollListeners.size() - 1; i >= 0; i--) {
3704                mScrollListeners.get(i).onScrolled(this, hresult, vresult);
3705            }
3706        }
3707    }
3708
3709    /**
3710     * Called when the scroll state of this RecyclerView changes. Subclasses should use this
3711     * method to respond to state changes instead of an explicit listener.
3712     *
3713     * <p>This method will always be invoked before listeners, but after the LayoutManager
3714     * responds to the scroll state change.</p>
3715     *
3716     * @param state the new scroll state, one of {@link #SCROLL_STATE_IDLE},
3717     *              {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}
3718     */
3719    public void onScrollStateChanged(int state) {
3720        // Do nothing
3721    }
3722
3723    void dispatchOnScrollStateChanged(int state) {
3724        // Let the LayoutManager go first; this allows it to bring any properties into
3725        // a consistent state before the RecyclerView subclass responds.
3726        if (mLayout != null) {
3727            mLayout.onScrollStateChanged(state);
3728        }
3729
3730        // Let the RecyclerView subclass handle this event next; any LayoutManager property
3731        // changes will be reflected by this time.
3732        onScrollStateChanged(state);
3733
3734        // Listeners go last. All other internal state is consistent by this point.
3735        if (mScrollListener != null) {
3736            mScrollListener.onScrollStateChanged(this, state);
3737        }
3738        if (mScrollListeners != null) {
3739            for (int i = mScrollListeners.size() - 1; i >= 0; i--) {
3740                mScrollListeners.get(i).onScrollStateChanged(this, state);
3741            }
3742        }
3743    }
3744
3745    /**
3746     * Returns whether there are pending adapter updates which are not yet applied to the layout.
3747     * <p>
3748     * If this method returns <code>true</code>, it means that what user is currently seeing may not
3749     * reflect them adapter contents (depending on what has changed).
3750     * You may use this information to defer or cancel some operations.
3751     * <p>
3752     * This method returns true if RecyclerView has not yet calculated the first layout after it is
3753     * attached to the Window or the Adapter has been replaced.
3754     *
3755     * @return True if there are some adapter updates which are not yet reflected to layout or false
3756     * if layout is up to date.
3757     */
3758    public boolean hasPendingAdapterUpdates() {
3759        return !mFirstLayoutComplete || mDataSetHasChangedAfterLayout
3760                || mAdapterHelper.hasPendingUpdates();
3761    }
3762
3763    private class ViewFlinger implements Runnable {
3764        private int mLastFlingX;
3765        private int mLastFlingY;
3766        private ScrollerCompat mScroller;
3767        private Interpolator mInterpolator = sQuinticInterpolator;
3768
3769
3770        // When set to true, postOnAnimation callbacks are delayed until the run method completes
3771        private boolean mEatRunOnAnimationRequest = false;
3772
3773        // Tracks if postAnimationCallback should be re-attached when it is done
3774        private boolean mReSchedulePostAnimationCallback = false;
3775
3776        public ViewFlinger() {
3777            mScroller = ScrollerCompat.create(getContext(), sQuinticInterpolator);
3778        }
3779
3780        @Override
3781        public void run() {
3782            disableRunOnAnimationRequests();
3783            consumePendingUpdateOperations();
3784            // keep a local reference so that if it is changed during onAnimation method, it won't
3785            // cause unexpected behaviors
3786            final ScrollerCompat scroller = mScroller;
3787            final SmoothScroller smoothScroller = mLayout.mSmoothScroller;
3788            if (scroller.computeScrollOffset()) {
3789                final int x = scroller.getCurrX();
3790                final int y = scroller.getCurrY();
3791                final int dx = x - mLastFlingX;
3792                final int dy = y - mLastFlingY;
3793                int hresult = 0;
3794                int vresult = 0;
3795                mLastFlingX = x;
3796                mLastFlingY = y;
3797                int overscrollX = 0, overscrollY = 0;
3798                if (mAdapter != null) {
3799                    eatRequestLayout();
3800                    onEnterLayoutOrScroll();
3801                    TraceCompat.beginSection(TRACE_SCROLL_TAG);
3802                    if (dx != 0) {
3803                        hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);
3804                        overscrollX = dx - hresult;
3805                    }
3806                    if (dy != 0) {
3807                        vresult = mLayout.scrollVerticallyBy(dy, mRecycler, mState);
3808                        overscrollY = dy - vresult;
3809                    }
3810                    TraceCompat.endSection();
3811                    repositionShadowingViews();
3812
3813                    onExitLayoutOrScroll();
3814                    resumeRequestLayout(false);
3815
3816                    if (smoothScroller != null && !smoothScroller.isPendingInitialRun() &&
3817                            smoothScroller.isRunning()) {
3818                        final int adapterSize = mState.getItemCount();
3819                        if (adapterSize == 0) {
3820                            smoothScroller.stop();
3821                        } else if (smoothScroller.getTargetPosition() >= adapterSize) {
3822                            smoothScroller.setTargetPosition(adapterSize - 1);
3823                            smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
3824                        } else {
3825                            smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
3826                        }
3827                    }
3828                }
3829                if (!mItemDecorations.isEmpty()) {
3830                    invalidate();
3831                }
3832                if (ViewCompat.getOverScrollMode(RecyclerView.this) !=
3833                        ViewCompat.OVER_SCROLL_NEVER) {
3834                    considerReleasingGlowsOnScroll(dx, dy);
3835                }
3836                if (overscrollX != 0 || overscrollY != 0) {
3837                    final int vel = (int) scroller.getCurrVelocity();
3838
3839                    int velX = 0;
3840                    if (overscrollX != x) {
3841                        velX = overscrollX < 0 ? -vel : overscrollX > 0 ? vel : 0;
3842                    }
3843
3844                    int velY = 0;
3845                    if (overscrollY != y) {
3846                        velY = overscrollY < 0 ? -vel : overscrollY > 0 ? vel : 0;
3847                    }
3848
3849                    if (ViewCompat.getOverScrollMode(RecyclerView.this) !=
3850                            ViewCompat.OVER_SCROLL_NEVER) {
3851                        absorbGlows(velX, velY);
3852                    }
3853                    if ((velX != 0 || overscrollX == x || scroller.getFinalX() == 0) &&
3854                            (velY != 0 || overscrollY == y || scroller.getFinalY() == 0)) {
3855                        scroller.abortAnimation();
3856                    }
3857                }
3858                if (hresult != 0 || vresult != 0) {
3859                    dispatchOnScrolled(hresult, vresult);
3860                }
3861
3862                if (!awakenScrollBars()) {
3863                    invalidate();
3864                }
3865
3866                final boolean fullyConsumedVertical = dy != 0 && mLayout.canScrollVertically()
3867                        && vresult == dy;
3868                final boolean fullyConsumedHorizontal = dx != 0 && mLayout.canScrollHorizontally()
3869                        && hresult == dx;
3870                final boolean fullyConsumedAny = (dx == 0 && dy == 0) || fullyConsumedHorizontal
3871                        || fullyConsumedVertical;
3872
3873                if (scroller.isFinished() || !fullyConsumedAny) {
3874                    setScrollState(SCROLL_STATE_IDLE); // setting state to idle will stop this.
3875                } else {
3876                    postOnAnimation();
3877                }
3878            }
3879            // call this after the onAnimation is complete not to have inconsistent callbacks etc.
3880            if (smoothScroller != null) {
3881                if (smoothScroller.isPendingInitialRun()) {
3882                    smoothScroller.onAnimation(0, 0);
3883                }
3884                if (!mReSchedulePostAnimationCallback) {
3885                    smoothScroller.stop(); //stop if it does not trigger any scroll
3886                }
3887            }
3888            enableRunOnAnimationRequests();
3889        }
3890
3891        private void disableRunOnAnimationRequests() {
3892            mReSchedulePostAnimationCallback = false;
3893            mEatRunOnAnimationRequest = true;
3894        }
3895
3896        private void enableRunOnAnimationRequests() {
3897            mEatRunOnAnimationRequest = false;
3898            if (mReSchedulePostAnimationCallback) {
3899                postOnAnimation();
3900            }
3901        }
3902
3903        void postOnAnimation() {
3904            if (mEatRunOnAnimationRequest) {
3905                mReSchedulePostAnimationCallback = true;
3906            } else {
3907                removeCallbacks(this);
3908                ViewCompat.postOnAnimation(RecyclerView.this, this);
3909            }
3910        }
3911
3912        public void fling(int velocityX, int velocityY) {
3913            setScrollState(SCROLL_STATE_SETTLING);
3914            mLastFlingX = mLastFlingY = 0;
3915            mScroller.fling(0, 0, velocityX, velocityY,
3916                    Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
3917            postOnAnimation();
3918        }
3919
3920        public void smoothScrollBy(int dx, int dy) {
3921            smoothScrollBy(dx, dy, 0, 0);
3922        }
3923
3924        public void smoothScrollBy(int dx, int dy, int vx, int vy) {
3925            smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, vx, vy));
3926        }
3927
3928        private float distanceInfluenceForSnapDuration(float f) {
3929            f -= 0.5f; // center the values about 0.
3930            f *= 0.3f * Math.PI / 2.0f;
3931            return (float) Math.sin(f);
3932        }
3933
3934        private int computeScrollDuration(int dx, int dy, int vx, int vy) {
3935            final int absDx = Math.abs(dx);
3936            final int absDy = Math.abs(dy);
3937            final boolean horizontal = absDx > absDy;
3938            final int velocity = (int) Math.sqrt(vx * vx + vy * vy);
3939            final int delta = (int) Math.sqrt(dx * dx + dy * dy);
3940            final int containerSize = horizontal ? getWidth() : getHeight();
3941            final int halfContainerSize = containerSize / 2;
3942            final float distanceRatio = Math.min(1.f, 1.f * delta / containerSize);
3943            final float distance = halfContainerSize + halfContainerSize *
3944                    distanceInfluenceForSnapDuration(distanceRatio);
3945
3946            final int duration;
3947            if (velocity > 0) {
3948                duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
3949            } else {
3950                float absDelta = (float) (horizontal ? absDx : absDy);
3951                duration = (int) (((absDelta / containerSize) + 1) * 300);
3952            }
3953            return Math.min(duration, MAX_SCROLL_DURATION);
3954        }
3955
3956        public void smoothScrollBy(int dx, int dy, int duration) {
3957            smoothScrollBy(dx, dy, duration, sQuinticInterpolator);
3958        }
3959
3960        public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) {
3961            if (mInterpolator != interpolator) {
3962                mInterpolator = interpolator;
3963                mScroller = ScrollerCompat.create(getContext(), interpolator);
3964            }
3965            setScrollState(SCROLL_STATE_SETTLING);
3966            mLastFlingX = mLastFlingY = 0;
3967            mScroller.startScroll(0, 0, dx, dy, duration);
3968            postOnAnimation();
3969        }
3970
3971        public void stop() {
3972            removeCallbacks(this);
3973            mScroller.abortAnimation();
3974        }
3975
3976    }
3977
3978    private void repositionShadowingViews() {
3979        // Fix up shadow views used by change animations
3980        int count = mChildHelper.getChildCount();
3981        for (int i = 0; i < count; i++) {
3982            View view = mChildHelper.getChildAt(i);
3983            ViewHolder holder = getChildViewHolder(view);
3984            if (holder != null && holder.mShadowingHolder != null) {
3985                View shadowingView = holder.mShadowingHolder.itemView;
3986                int left = view.getLeft();
3987                int top = view.getTop();
3988                if (left != shadowingView.getLeft() ||
3989                        top != shadowingView.getTop()) {
3990                    shadowingView.layout(left, top,
3991                            left + shadowingView.getWidth(),
3992                            top + shadowingView.getHeight());
3993                }
3994            }
3995        }
3996    }
3997
3998    private class RecyclerViewDataObserver extends AdapterDataObserver {
3999        @Override
4000        public void onChanged() {
4001            assertNotInLayoutOrScroll(null);
4002            if (mAdapter.hasStableIds()) {
4003                // TODO Determine what actually changed.
4004                // This is more important to implement now since this callback will disable all
4005                // animations because we cannot rely on positions.
4006                mState.mStructureChanged = true;
4007                setDataSetChangedAfterLayout();
4008            } else {
4009                mState.mStructureChanged = true;
4010                setDataSetChangedAfterLayout();
4011            }
4012            if (!mAdapterHelper.hasPendingUpdates()) {
4013                requestLayout();
4014            }
4015        }
4016
4017        @Override
4018        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
4019            assertNotInLayoutOrScroll(null);
4020            if (mAdapterHelper.onItemRangeChanged(positionStart, itemCount, payload)) {
4021                triggerUpdateProcessor();
4022            }
4023        }
4024
4025        @Override
4026        public void onItemRangeInserted(int positionStart, int itemCount) {
4027            assertNotInLayoutOrScroll(null);
4028            if (mAdapterHelper.onItemRangeInserted(positionStart, itemCount)) {
4029                triggerUpdateProcessor();
4030            }
4031        }
4032
4033        @Override
4034        public void onItemRangeRemoved(int positionStart, int itemCount) {
4035            assertNotInLayoutOrScroll(null);
4036            if (mAdapterHelper.onItemRangeRemoved(positionStart, itemCount)) {
4037                triggerUpdateProcessor();
4038            }
4039        }
4040
4041        @Override
4042        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
4043            assertNotInLayoutOrScroll(null);
4044            if (mAdapterHelper.onItemRangeMoved(fromPosition, toPosition, itemCount)) {
4045                triggerUpdateProcessor();
4046            }
4047        }
4048
4049        void triggerUpdateProcessor() {
4050            if (mPostUpdatesOnAnimation && mHasFixedSize && mIsAttached) {
4051                ViewCompat.postOnAnimation(RecyclerView.this, mUpdateChildViewsRunnable);
4052            } else {
4053                mAdapterUpdateDuringMeasure = true;
4054                requestLayout();
4055            }
4056        }
4057    }
4058
4059    /**
4060     * RecycledViewPool lets you share Views between multiple RecyclerViews.
4061     * <p>
4062     * If you want to recycle views across RecyclerViews, create an instance of RecycledViewPool
4063     * and use {@link RecyclerView#setRecycledViewPool(RecycledViewPool)}.
4064     * <p>
4065     * RecyclerView automatically creates a pool for itself if you don't provide one.
4066     *
4067     */
4068    public static class RecycledViewPool {
4069        private SparseArray<ArrayList<ViewHolder>> mScrap =
4070                new SparseArray<ArrayList<ViewHolder>>();
4071        private SparseIntArray mMaxScrap = new SparseIntArray();
4072        private int mAttachCount = 0;
4073
4074        private static final int DEFAULT_MAX_SCRAP = 5;
4075
4076        public void clear() {
4077            mScrap.clear();
4078        }
4079
4080        public void setMaxRecycledViews(int viewType, int max) {
4081            mMaxScrap.put(viewType, max);
4082            final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
4083            if (scrapHeap != null) {
4084                while (scrapHeap.size() > max) {
4085                    scrapHeap.remove(scrapHeap.size() - 1);
4086                }
4087            }
4088        }
4089
4090        public ViewHolder getRecycledView(int viewType) {
4091            final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
4092            if (scrapHeap != null && !scrapHeap.isEmpty()) {
4093                final int index = scrapHeap.size() - 1;
4094                final ViewHolder scrap = scrapHeap.get(index);
4095                scrapHeap.remove(index);
4096                return scrap;
4097            }
4098            return null;
4099        }
4100
4101        int size() {
4102            int count = 0;
4103            for (int i = 0; i < mScrap.size(); i ++) {
4104                ArrayList<ViewHolder> viewHolders = mScrap.valueAt(i);
4105                if (viewHolders != null) {
4106                    count += viewHolders.size();
4107                }
4108            }
4109            return count;
4110        }
4111
4112        public void putRecycledView(ViewHolder scrap) {
4113            final int viewType = scrap.getItemViewType();
4114            final ArrayList scrapHeap = getScrapHeapForType(viewType);
4115            if (mMaxScrap.get(viewType) <= scrapHeap.size()) {
4116                return;
4117            }
4118            if (DEBUG && scrapHeap.contains(scrap)) {
4119                throw new IllegalArgumentException("this scrap item already exists");
4120            }
4121            scrap.resetInternal();
4122            scrapHeap.add(scrap);
4123        }
4124
4125        void attach(Adapter adapter) {
4126            mAttachCount++;
4127        }
4128
4129        void detach() {
4130            mAttachCount--;
4131        }
4132
4133
4134        /**
4135         * Detaches the old adapter and attaches the new one.
4136         * <p>
4137         * RecycledViewPool will clear its cache if it has only one adapter attached and the new
4138         * adapter uses a different ViewHolder than the oldAdapter.
4139         *
4140         * @param oldAdapter The previous adapter instance. Will be detached.
4141         * @param newAdapter The new adapter instance. Will be attached.
4142         * @param compatibleWithPrevious True if both oldAdapter and newAdapter are using the same
4143         *                               ViewHolder and view types.
4144         */
4145        void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
4146                boolean compatibleWithPrevious) {
4147            if (oldAdapter != null) {
4148                detach();
4149            }
4150            if (!compatibleWithPrevious && mAttachCount == 0) {
4151                clear();
4152            }
4153            if (newAdapter != null) {
4154                attach(newAdapter);
4155            }
4156        }
4157
4158        private ArrayList<ViewHolder> getScrapHeapForType(int viewType) {
4159            ArrayList<ViewHolder> scrap = mScrap.get(viewType);
4160            if (scrap == null) {
4161                scrap = new ArrayList<ViewHolder>();
4162                mScrap.put(viewType, scrap);
4163                if (mMaxScrap.indexOfKey(viewType) < 0) {
4164                    mMaxScrap.put(viewType, DEFAULT_MAX_SCRAP);
4165                }
4166            }
4167            return scrap;
4168        }
4169    }
4170
4171    /**
4172     * A Recycler is responsible for managing scrapped or detached item views for reuse.
4173     *
4174     * <p>A "scrapped" view is a view that is still attached to its parent RecyclerView but
4175     * that has been marked for removal or reuse.</p>
4176     *
4177     * <p>Typical use of a Recycler by a {@link LayoutManager} will be to obtain views for
4178     * an adapter's data set representing the data at a given position or item ID.
4179     * If the view to be reused is considered "dirty" the adapter will be asked to rebind it.
4180     * If not, the view can be quickly reused by the LayoutManager with no further work.
4181     * Clean views that have not {@link android.view.View#isLayoutRequested() requested layout}
4182     * may be repositioned by a LayoutManager without remeasurement.</p>
4183     */
4184    public final class Recycler {
4185        final ArrayList<ViewHolder> mAttachedScrap = new ArrayList<ViewHolder>();
4186        private ArrayList<ViewHolder> mChangedScrap = null;
4187
4188        final ArrayList<ViewHolder> mCachedViews = new ArrayList<ViewHolder>();
4189
4190        private final List<ViewHolder>
4191                mUnmodifiableAttachedScrap = Collections.unmodifiableList(mAttachedScrap);
4192
4193        private int mViewCacheMax = DEFAULT_CACHE_SIZE;
4194
4195        private RecycledViewPool mRecyclerPool;
4196
4197        private ViewCacheExtension mViewCacheExtension;
4198
4199        private static final int DEFAULT_CACHE_SIZE = 2;
4200
4201        /**
4202         * Clear scrap views out of this recycler. Detached views contained within a
4203         * recycled view pool will remain.
4204         */
4205        public void clear() {
4206            mAttachedScrap.clear();
4207            recycleAndClearCachedViews();
4208        }
4209
4210        /**
4211         * Set the maximum number of detached, valid views we should retain for later use.
4212         *
4213         * @param viewCount Number of views to keep before sending views to the shared pool
4214         */
4215        public void setViewCacheSize(int viewCount) {
4216            mViewCacheMax = viewCount;
4217            // first, try the views that can be recycled
4218            for (int i = mCachedViews.size() - 1; i >= 0 && mCachedViews.size() > viewCount; i--) {
4219                recycleCachedViewAt(i);
4220            }
4221        }
4222
4223        /**
4224         * Returns an unmodifiable list of ViewHolders that are currently in the scrap list.
4225         *
4226         * @return List of ViewHolders in the scrap list.
4227         */
4228        public List<ViewHolder> getScrapList() {
4229            return mUnmodifiableAttachedScrap;
4230        }
4231
4232        /**
4233         * Helper method for getViewForPosition.
4234         * <p>
4235         * Checks whether a given view holder can be used for the provided position.
4236         *
4237         * @param holder ViewHolder
4238         * @return true if ViewHolder matches the provided position, false otherwise
4239         */
4240        boolean validateViewHolderForOffsetPosition(ViewHolder holder) {
4241            // if it is a removed holder, nothing to verify since we cannot ask adapter anymore
4242            // if it is not removed, verify the type and id.
4243            if (holder.isRemoved()) {
4244                if (DEBUG && !mState.isPreLayout()) {
4245                    throw new IllegalStateException("should not receive a removed view unelss it"
4246                            + " is pre layout");
4247                }
4248                return mState.isPreLayout();
4249            }
4250            if (holder.mPosition < 0 || holder.mPosition >= mAdapter.getItemCount()) {
4251                throw new IndexOutOfBoundsException("Inconsistency detected. Invalid view holder "
4252                        + "adapter position" + holder);
4253            }
4254            if (!mState.isPreLayout()) {
4255                // don't check type if it is pre-layout.
4256                final int type = mAdapter.getItemViewType(holder.mPosition);
4257                if (type != holder.getItemViewType()) {
4258                    return false;
4259                }
4260            }
4261            if (mAdapter.hasStableIds()) {
4262                return holder.getItemId() == mAdapter.getItemId(holder.mPosition);
4263            }
4264            return true;
4265        }
4266
4267        /**
4268         * Binds the given View to the position. The View can be a View previously retrieved via
4269         * {@link #getViewForPosition(int)} or created by
4270         * {@link Adapter#onCreateViewHolder(ViewGroup, int)}.
4271         * <p>
4272         * Generally, a LayoutManager should acquire its views via {@link #getViewForPosition(int)}
4273         * and let the RecyclerView handle caching. This is a helper method for LayoutManager who
4274         * wants to handle its own recycling logic.
4275         * <p>
4276         * Note that, {@link #getViewForPosition(int)} already binds the View to the position so
4277         * you don't need to call this method unless you want to bind this View to another position.
4278         *
4279         * @param view The view to update.
4280         * @param position The position of the item to bind to this View.
4281         */
4282        public void bindViewToPosition(View view, int position) {
4283            ViewHolder holder = getChildViewHolderInt(view);
4284            if (holder == null) {
4285                throw new IllegalArgumentException("The view does not have a ViewHolder. You cannot"
4286                        + " pass arbitrary views to this method, they should be created by the "
4287                        + "Adapter");
4288            }
4289            final int offsetPosition = mAdapterHelper.findPositionOffset(position);
4290            if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
4291                throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
4292                        + "position " + position + "(offset:" + offsetPosition + ")."
4293                        + "state:" + mState.getItemCount());
4294            }
4295            holder.mOwnerRecyclerView = RecyclerView.this;
4296            mAdapter.bindViewHolder(holder, offsetPosition);
4297            attachAccessibilityDelegate(view);
4298            if (mState.isPreLayout()) {
4299                holder.mPreLayoutPosition = position;
4300            }
4301
4302            final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
4303            final LayoutParams rvLayoutParams;
4304            if (lp == null) {
4305                rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
4306                holder.itemView.setLayoutParams(rvLayoutParams);
4307            } else if (!checkLayoutParams(lp)) {
4308                rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
4309                holder.itemView.setLayoutParams(rvLayoutParams);
4310            } else {
4311                rvLayoutParams = (LayoutParams) lp;
4312            }
4313
4314            rvLayoutParams.mInsetsDirty = true;
4315            rvLayoutParams.mViewHolder = holder;
4316            rvLayoutParams.mPendingInvalidate = holder.itemView.getParent() == null;
4317        }
4318
4319        /**
4320         * RecyclerView provides artificial position range (item count) in pre-layout state and
4321         * automatically maps these positions to {@link Adapter} positions when
4322         * {@link #getViewForPosition(int)} or {@link #bindViewToPosition(View, int)} is called.
4323         * <p>
4324         * Usually, LayoutManager does not need to worry about this. However, in some cases, your
4325         * LayoutManager may need to call some custom component with item positions in which
4326         * case you need the actual adapter position instead of the pre layout position. You
4327         * can use this method to convert a pre-layout position to adapter (post layout) position.
4328         * <p>
4329         * Note that if the provided position belongs to a deleted ViewHolder, this method will
4330         * return -1.
4331         * <p>
4332         * Calling this method in post-layout state returns the same value back.
4333         *
4334         * @param position The pre-layout position to convert. Must be greater or equal to 0 and
4335         *                 less than {@link State#getItemCount()}.
4336         */
4337        public int convertPreLayoutPositionToPostLayout(int position) {
4338            if (position < 0 || position >= mState.getItemCount()) {
4339                throw new IndexOutOfBoundsException("invalid position " + position + ". State "
4340                        + "item count is " + mState.getItemCount());
4341            }
4342            if (!mState.isPreLayout()) {
4343                return position;
4344            }
4345            return mAdapterHelper.findPositionOffset(position);
4346        }
4347
4348        /**
4349         * Obtain a view initialized for the given position.
4350         *
4351         * This method should be used by {@link LayoutManager} implementations to obtain
4352         * views to represent data from an {@link Adapter}.
4353         * <p>
4354         * The Recycler may reuse a scrap or detached view from a shared pool if one is
4355         * available for the correct view type. If the adapter has not indicated that the
4356         * data at the given position has changed, the Recycler will attempt to hand back
4357         * a scrap view that was previously initialized for that data without rebinding.
4358         *
4359         * @param position Position to obtain a view for
4360         * @return A view representing the data at <code>position</code> from <code>adapter</code>
4361         */
4362        public View getViewForPosition(int position) {
4363            return getViewForPosition(position, false);
4364        }
4365
4366        View getViewForPosition(int position, boolean dryRun) {
4367            if (position < 0 || position >= mState.getItemCount()) {
4368                throw new IndexOutOfBoundsException("Invalid item position " + position
4369                        + "(" + position + "). Item count:" + mState.getItemCount());
4370            }
4371            boolean fromScrap = false;
4372            ViewHolder holder = null;
4373            // 0) If there is a changed scrap, try to find from there
4374            if (mState.isPreLayout()) {
4375                holder = getChangedScrapViewForPosition(position);
4376                fromScrap = holder != null;
4377            }
4378            // 1) Find from scrap by position
4379            if (holder == null) {
4380                holder = getScrapViewForPosition(position, INVALID_TYPE, dryRun);
4381                if (holder != null) {
4382                    if (!validateViewHolderForOffsetPosition(holder)) {
4383                        // recycle this scrap
4384                        if (!dryRun) {
4385                            // we would like to recycle this but need to make sure it is not used by
4386                            // animation logic etc.
4387                            holder.addFlags(ViewHolder.FLAG_INVALID);
4388                            if (holder.isScrap()) {
4389                                removeDetachedView(holder.itemView, false);
4390                                holder.unScrap();
4391                            } else if (holder.wasReturnedFromScrap()) {
4392                                holder.clearReturnedFromScrapFlag();
4393                            }
4394                            recycleViewHolderInternal(holder);
4395                        }
4396                        holder = null;
4397                    } else {
4398                        fromScrap = true;
4399                    }
4400                }
4401            }
4402            if (holder == null) {
4403                final int offsetPosition = mAdapterHelper.findPositionOffset(position);
4404                if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
4405                    throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
4406                            + "position " + position + "(offset:" + offsetPosition + ")."
4407                            + "state:" + mState.getItemCount());
4408                }
4409
4410                final int type = mAdapter.getItemViewType(offsetPosition);
4411                // 2) Find from scrap via stable ids, if exists
4412                if (mAdapter.hasStableIds()) {
4413                    holder = getScrapViewForId(mAdapter.getItemId(offsetPosition), type, dryRun);
4414                    if (holder != null) {
4415                        // update position
4416                        holder.mPosition = offsetPosition;
4417                        fromScrap = true;
4418                    }
4419                }
4420                if (holder == null && mViewCacheExtension != null) {
4421                    // We are NOT sending the offsetPosition because LayoutManager does not
4422                    // know it.
4423                    final View view = mViewCacheExtension
4424                            .getViewForPositionAndType(this, position, type);
4425                    if (view != null) {
4426                        holder = getChildViewHolder(view);
4427                        if (holder == null) {
4428                            throw new IllegalArgumentException("getViewForPositionAndType returned"
4429                                    + " a view which does not have a ViewHolder");
4430                        } else if (holder.shouldIgnore()) {
4431                            throw new IllegalArgumentException("getViewForPositionAndType returned"
4432                                    + " a view that is ignored. You must call stopIgnoring before"
4433                                    + " returning this view.");
4434                        }
4435                    }
4436                }
4437                if (holder == null) { // fallback to recycler
4438                    // try recycler.
4439                    // Head to the shared pool.
4440                    if (DEBUG) {
4441                        Log.d(TAG, "getViewForPosition(" + position + ") fetching from shared "
4442                                + "pool");
4443                    }
4444                    holder = getRecycledViewPool().getRecycledView(type);
4445                    if (holder != null) {
4446                        holder.resetInternal();
4447                        if (FORCE_INVALIDATE_DISPLAY_LIST) {
4448                            invalidateDisplayListInt(holder);
4449                        }
4450                    }
4451                }
4452                if (holder == null) {
4453                    holder = mAdapter.createViewHolder(RecyclerView.this, type);
4454                    if (DEBUG) {
4455                        Log.d(TAG, "getViewForPosition created new ViewHolder");
4456                    }
4457                }
4458            }
4459
4460            // This is very ugly but the only place we can grab this information
4461            // before the View is rebound and returned to the LayoutManager for post layout ops.
4462            // We don't need this in pre-layout since the VH is not updated by the LM.
4463            if (fromScrap && !mState.isPreLayout() && holder
4464                    .hasAnyOfTheFlags(ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST)) {
4465                holder.setFlags(0, ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
4466                if (mState.mRunSimpleAnimations) {
4467                    int changeFlags = ItemAnimator
4468                            .buildAdapterChangeFlagsForAnimations(holder);
4469                    changeFlags |= ItemAnimator.FLAG_APPEARED_IN_PRE_LAYOUT;
4470                    final ItemHolderInfo info = mItemAnimator.recordPreLayoutInformation(mState,
4471                            holder, changeFlags, holder.getUnmodifiedPayloads());
4472                    recordAnimationInfoIfBouncedHiddenView(holder, info);
4473                }
4474            }
4475
4476            boolean bound = false;
4477            if (mState.isPreLayout() && holder.isBound()) {
4478                // do not update unless we absolutely have to.
4479                holder.mPreLayoutPosition = position;
4480            } else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {
4481                if (DEBUG && holder.isRemoved()) {
4482                    throw new IllegalStateException("Removed holder should be bound and it should"
4483                            + " come here only in pre-layout. Holder: " + holder);
4484                }
4485                final int offsetPosition = mAdapterHelper.findPositionOffset(position);
4486                holder.mOwnerRecyclerView = RecyclerView.this;
4487                mAdapter.bindViewHolder(holder, offsetPosition);
4488                attachAccessibilityDelegate(holder.itemView);
4489                bound = true;
4490                if (mState.isPreLayout()) {
4491                    holder.mPreLayoutPosition = position;
4492                }
4493            }
4494
4495            final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
4496            final LayoutParams rvLayoutParams;
4497            if (lp == null) {
4498                rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
4499                holder.itemView.setLayoutParams(rvLayoutParams);
4500            } else if (!checkLayoutParams(lp)) {
4501                rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
4502                holder.itemView.setLayoutParams(rvLayoutParams);
4503            } else {
4504                rvLayoutParams = (LayoutParams) lp;
4505            }
4506            rvLayoutParams.mViewHolder = holder;
4507            rvLayoutParams.mPendingInvalidate = fromScrap && bound;
4508            return holder.itemView;
4509        }
4510
4511        private void attachAccessibilityDelegate(View itemView) {
4512            if (isAccessibilityEnabled()) {
4513                if (ViewCompat.getImportantForAccessibility(itemView) ==
4514                        ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
4515                    ViewCompat.setImportantForAccessibility(itemView,
4516                            ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_YES);
4517                }
4518                if (!ViewCompat.hasAccessibilityDelegate(itemView)) {
4519                    ViewCompat.setAccessibilityDelegate(itemView,
4520                            mAccessibilityDelegate.getItemDelegate());
4521                }
4522            }
4523        }
4524
4525        private void invalidateDisplayListInt(ViewHolder holder) {
4526            if (holder.itemView instanceof ViewGroup) {
4527                invalidateDisplayListInt((ViewGroup) holder.itemView, false);
4528            }
4529        }
4530
4531        private void invalidateDisplayListInt(ViewGroup viewGroup, boolean invalidateThis) {
4532            for (int i = viewGroup.getChildCount() - 1; i >= 0; i--) {
4533                final View view = viewGroup.getChildAt(i);
4534                if (view instanceof ViewGroup) {
4535                    invalidateDisplayListInt((ViewGroup) view, true);
4536                }
4537            }
4538            if (!invalidateThis) {
4539                return;
4540            }
4541            // we need to force it to become invisible
4542            if (viewGroup.getVisibility() == View.INVISIBLE) {
4543                viewGroup.setVisibility(View.VISIBLE);
4544                viewGroup.setVisibility(View.INVISIBLE);
4545            } else {
4546                final int visibility = viewGroup.getVisibility();
4547                viewGroup.setVisibility(View.INVISIBLE);
4548                viewGroup.setVisibility(visibility);
4549            }
4550        }
4551
4552        /**
4553         * Recycle a detached view. The specified view will be added to a pool of views
4554         * for later rebinding and reuse.
4555         *
4556         * <p>A view must be fully detached (removed from parent) before it may be recycled. If the
4557         * View is scrapped, it will be removed from scrap list.</p>
4558         *
4559         * @param view Removed view for recycling
4560         * @see LayoutManager#removeAndRecycleView(View, Recycler)
4561         */
4562        public void recycleView(View view) {
4563            // This public recycle method tries to make view recycle-able since layout manager
4564            // intended to recycle this view (e.g. even if it is in scrap or change cache)
4565            ViewHolder holder = getChildViewHolderInt(view);
4566            if (holder.isTmpDetached()) {
4567                removeDetachedView(view, false);
4568            }
4569            if (holder.isScrap()) {
4570                holder.unScrap();
4571            } else if (holder.wasReturnedFromScrap()){
4572                holder.clearReturnedFromScrapFlag();
4573            }
4574            recycleViewHolderInternal(holder);
4575        }
4576
4577        /**
4578         * Internally, use this method instead of {@link #recycleView(android.view.View)} to
4579         * catch potential bugs.
4580         * @param view
4581         */
4582        void recycleViewInternal(View view) {
4583            recycleViewHolderInternal(getChildViewHolderInt(view));
4584        }
4585
4586        void recycleAndClearCachedViews() {
4587            final int count = mCachedViews.size();
4588            for (int i = count - 1; i >= 0; i--) {
4589                recycleCachedViewAt(i);
4590            }
4591            mCachedViews.clear();
4592        }
4593
4594        /**
4595         * Recycles a cached view and removes the view from the list. Views are added to cache
4596         * if and only if they are recyclable, so this method does not check it again.
4597         * <p>
4598         * A small exception to this rule is when the view does not have an animator reference
4599         * but transient state is true (due to animations created outside ItemAnimator). In that
4600         * case, adapter may choose to recycle it. From RecyclerView's perspective, the view is
4601         * still recyclable since Adapter wants to do so.
4602         *
4603         * @param cachedViewIndex The index of the view in cached views list
4604         */
4605        void recycleCachedViewAt(int cachedViewIndex) {
4606            if (DEBUG) {
4607                Log.d(TAG, "Recycling cached view at index " + cachedViewIndex);
4608            }
4609            ViewHolder viewHolder = mCachedViews.get(cachedViewIndex);
4610            if (DEBUG) {
4611                Log.d(TAG, "CachedViewHolder to be recycled: " + viewHolder);
4612            }
4613            addViewHolderToRecycledViewPool(viewHolder);
4614            mCachedViews.remove(cachedViewIndex);
4615        }
4616
4617        /**
4618         * internal implementation checks if view is scrapped or attached and throws an exception
4619         * if so.
4620         * Public version un-scraps before calling recycle.
4621         */
4622        void recycleViewHolderInternal(ViewHolder holder) {
4623            if (holder.isScrap() || holder.itemView.getParent() != null) {
4624                throw new IllegalArgumentException(
4625                        "Scrapped or attached views may not be recycled. isScrap:"
4626                                + holder.isScrap() + " isAttached:"
4627                                + (holder.itemView.getParent() != null));
4628            }
4629
4630            if (holder.isTmpDetached()) {
4631                throw new IllegalArgumentException("Tmp detached view should be removed "
4632                        + "from RecyclerView before it can be recycled: " + holder);
4633            }
4634
4635            if (holder.shouldIgnore()) {
4636                throw new IllegalArgumentException("Trying to recycle an ignored view holder. You"
4637                        + " should first call stopIgnoringView(view) before calling recycle.");
4638            }
4639            //noinspection unchecked
4640            final boolean transientStatePreventsRecycling = holder
4641                    .doesTransientStatePreventRecycling();
4642            final boolean forceRecycle = mAdapter != null
4643                    && transientStatePreventsRecycling
4644                    && mAdapter.onFailedToRecycleView(holder);
4645            boolean cached = false;
4646            boolean recycled = false;
4647            if (DEBUG && mCachedViews.contains(holder)) {
4648                throw new IllegalArgumentException("cached view received recycle internal? " +
4649                        holder);
4650            }
4651            if (forceRecycle || holder.isRecyclable()) {
4652                if (!holder.hasAnyOfTheFlags(ViewHolder.FLAG_INVALID | ViewHolder.FLAG_REMOVED
4653                        | ViewHolder.FLAG_UPDATE)) {
4654                    // Retire oldest cached view
4655                    final int cachedViewSize = mCachedViews.size();
4656                    if (cachedViewSize == mViewCacheMax && cachedViewSize > 0) {
4657                        recycleCachedViewAt(0);
4658                    }
4659                    if (cachedViewSize < mViewCacheMax) {
4660                        mCachedViews.add(holder);
4661                        cached = true;
4662                    }
4663                }
4664                if (!cached) {
4665                    addViewHolderToRecycledViewPool(holder);
4666                    recycled = true;
4667                }
4668            } else if (DEBUG) {
4669                Log.d(TAG, "trying to recycle a non-recycleable holder. Hopefully, it will "
4670                        + "re-visit here. We are still removing it from animation lists");
4671            }
4672            // even if the holder is not removed, we still call this method so that it is removed
4673            // from view holder lists.
4674            mViewInfoStore.removeViewHolder(holder);
4675            if (!cached && !recycled && transientStatePreventsRecycling) {
4676                holder.mOwnerRecyclerView = null;
4677            }
4678        }
4679
4680        void addViewHolderToRecycledViewPool(ViewHolder holder) {
4681            ViewCompat.setAccessibilityDelegate(holder.itemView, null);
4682            dispatchViewRecycled(holder);
4683            holder.mOwnerRecyclerView = null;
4684            getRecycledViewPool().putRecycledView(holder);
4685        }
4686
4687        /**
4688         * Used as a fast path for unscrapping and recycling a view during a bulk operation.
4689         * The caller must call {@link #clearScrap()} when it's done to update the recycler's
4690         * internal bookkeeping.
4691         */
4692        void quickRecycleScrapView(View view) {
4693            final ViewHolder holder = getChildViewHolderInt(view);
4694            holder.mScrapContainer = null;
4695            holder.mInChangeScrap = false;
4696            holder.clearReturnedFromScrapFlag();
4697            recycleViewHolderInternal(holder);
4698        }
4699
4700        /**
4701         * Mark an attached view as scrap.
4702         *
4703         * <p>"Scrap" views are still attached to their parent RecyclerView but are eligible
4704         * for rebinding and reuse. Requests for a view for a given position may return a
4705         * reused or rebound scrap view instance.</p>
4706         *
4707         * @param view View to scrap
4708         */
4709        void scrapView(View view) {
4710            final ViewHolder holder = getChildViewHolderInt(view);
4711            if (holder.hasAnyOfTheFlags(ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_INVALID)
4712                    || !holder.isUpdated() || canReuseUpdatedViewHolder(holder)) {
4713                if (holder.isInvalid() && !holder.isRemoved() && !mAdapter.hasStableIds()) {
4714                    throw new IllegalArgumentException("Called scrap view with an invalid view."
4715                            + " Invalid views cannot be reused from scrap, they should rebound from"
4716                            + " recycler pool.");
4717                }
4718                holder.setScrapContainer(this, false);
4719                mAttachedScrap.add(holder);
4720            } else {
4721                if (mChangedScrap == null) {
4722                    mChangedScrap = new ArrayList<ViewHolder>();
4723                }
4724                holder.setScrapContainer(this, true);
4725                mChangedScrap.add(holder);
4726            }
4727        }
4728
4729        /**
4730         * Remove a previously scrapped view from the pool of eligible scrap.
4731         *
4732         * <p>This view will no longer be eligible for reuse until re-scrapped or
4733         * until it is explicitly removed and recycled.</p>
4734         */
4735        void unscrapView(ViewHolder holder) {
4736            if (holder.mInChangeScrap) {
4737                mChangedScrap.remove(holder);
4738            } else {
4739                mAttachedScrap.remove(holder);
4740            }
4741            holder.mScrapContainer = null;
4742            holder.mInChangeScrap = false;
4743            holder.clearReturnedFromScrapFlag();
4744        }
4745
4746        int getScrapCount() {
4747            return mAttachedScrap.size();
4748        }
4749
4750        View getScrapViewAt(int index) {
4751            return mAttachedScrap.get(index).itemView;
4752        }
4753
4754        void clearScrap() {
4755            mAttachedScrap.clear();
4756            if (mChangedScrap != null) {
4757                mChangedScrap.clear();
4758            }
4759        }
4760
4761        ViewHolder getChangedScrapViewForPosition(int position) {
4762            // If pre-layout, check the changed scrap for an exact match.
4763            final int changedScrapSize;
4764            if (mChangedScrap == null || (changedScrapSize = mChangedScrap.size()) == 0) {
4765                return null;
4766            }
4767            // find by position
4768            for (int i = 0; i < changedScrapSize; i++) {
4769                final ViewHolder holder = mChangedScrap.get(i);
4770                if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position) {
4771                    holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
4772                    return holder;
4773                }
4774            }
4775            // find by id
4776            if (mAdapter.hasStableIds()) {
4777                final int offsetPosition = mAdapterHelper.findPositionOffset(position);
4778                if (offsetPosition > 0 && offsetPosition < mAdapter.getItemCount()) {
4779                    final long id = mAdapter.getItemId(offsetPosition);
4780                    for (int i = 0; i < changedScrapSize; i++) {
4781                        final ViewHolder holder = mChangedScrap.get(i);
4782                        if (!holder.wasReturnedFromScrap() && holder.getItemId() == id) {
4783                            holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
4784                            return holder;
4785                        }
4786                    }
4787                }
4788            }
4789            return null;
4790        }
4791
4792        /**
4793         * Returns a scrap view for the position. If type is not INVALID_TYPE, it also checks if
4794         * ViewHolder's type matches the provided type.
4795         *
4796         * @param position Item position
4797         * @param type View type
4798         * @param dryRun  Does a dry run, finds the ViewHolder but does not remove
4799         * @return a ViewHolder that can be re-used for this position.
4800         */
4801        ViewHolder getScrapViewForPosition(int position, int type, boolean dryRun) {
4802            final int scrapCount = mAttachedScrap.size();
4803
4804            // Try first for an exact, non-invalid match from scrap.
4805            for (int i = 0; i < scrapCount; i++) {
4806                final ViewHolder holder = mAttachedScrap.get(i);
4807                if (!holder.wasReturnedFromScrap() && holder.getLayoutPosition() == position
4808                        && !holder.isInvalid() && (mState.mInPreLayout || !holder.isRemoved())) {
4809                    if (type != INVALID_TYPE && holder.getItemViewType() != type) {
4810                        Log.e(TAG, "Scrap view for position " + position + " isn't dirty but has" +
4811                                " wrong view type! (found " + holder.getItemViewType() +
4812                                " but expected " + type + ")");
4813                        break;
4814                    }
4815                    holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
4816                    return holder;
4817                }
4818            }
4819
4820            if (!dryRun) {
4821                View view = mChildHelper.findHiddenNonRemovedView(position, type);
4822                if (view != null) {
4823                    // This View is good to be used. We just need to unhide, detach and move to the
4824                    // scrap list.
4825                    final ViewHolder vh = getChildViewHolderInt(view);
4826                    mChildHelper.unhide(view);
4827                    int layoutIndex = mChildHelper.indexOfChild(view);
4828                    if (layoutIndex == RecyclerView.NO_POSITION) {
4829                        throw new IllegalStateException("layout index should not be -1 after "
4830                                + "unhiding a view:" + vh);
4831                    }
4832                    mChildHelper.detachViewFromParent(layoutIndex);
4833                    scrapView(view);
4834                    vh.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP
4835                            | ViewHolder.FLAG_BOUNCED_FROM_HIDDEN_LIST);
4836                    return vh;
4837                }
4838            }
4839
4840            // Search in our first-level recycled view cache.
4841            final int cacheSize = mCachedViews.size();
4842            for (int i = 0; i < cacheSize; i++) {
4843                final ViewHolder holder = mCachedViews.get(i);
4844                // invalid view holders may be in cache if adapter has stable ids as they can be
4845                // retrieved via getScrapViewForId
4846                if (!holder.isInvalid() && holder.getLayoutPosition() == position) {
4847                    if (!dryRun) {
4848                        mCachedViews.remove(i);
4849                    }
4850                    if (DEBUG) {
4851                        Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
4852                                ") found match in cache: " + holder);
4853                    }
4854                    return holder;
4855                }
4856            }
4857            return null;
4858        }
4859
4860        ViewHolder getScrapViewForId(long id, int type, boolean dryRun) {
4861            // Look in our attached views first
4862            final int count = mAttachedScrap.size();
4863            for (int i = count - 1; i >= 0; i--) {
4864                final ViewHolder holder = mAttachedScrap.get(i);
4865                if (holder.getItemId() == id && !holder.wasReturnedFromScrap()) {
4866                    if (type == holder.getItemViewType()) {
4867                        holder.addFlags(ViewHolder.FLAG_RETURNED_FROM_SCRAP);
4868                        if (holder.isRemoved()) {
4869                            // this might be valid in two cases:
4870                            // > item is removed but we are in pre-layout pass
4871                            // >> do nothing. return as is. make sure we don't rebind
4872                            // > item is removed then added to another position and we are in
4873                            // post layout.
4874                            // >> remove removed and invalid flags, add update flag to rebind
4875                            // because item was invisible to us and we don't know what happened in
4876                            // between.
4877                            if (!mState.isPreLayout()) {
4878                                holder.setFlags(ViewHolder.FLAG_UPDATE, ViewHolder.FLAG_UPDATE |
4879                                        ViewHolder.FLAG_INVALID | ViewHolder.FLAG_REMOVED);
4880                            }
4881                        }
4882                        return holder;
4883                    } else if (!dryRun) {
4884                        // if we are running animations, it is actually better to keep it in scrap
4885                        // but this would force layout manager to lay it out which would be bad.
4886                        // Recycle this scrap. Type mismatch.
4887                        mAttachedScrap.remove(i);
4888                        removeDetachedView(holder.itemView, false);
4889                        quickRecycleScrapView(holder.itemView);
4890                    }
4891                }
4892            }
4893
4894            // Search the first-level cache
4895            final int cacheSize = mCachedViews.size();
4896            for (int i = cacheSize - 1; i >= 0; i--) {
4897                final ViewHolder holder = mCachedViews.get(i);
4898                if (holder.getItemId() == id) {
4899                    if (type == holder.getItemViewType()) {
4900                        if (!dryRun) {
4901                            mCachedViews.remove(i);
4902                        }
4903                        return holder;
4904                    } else if (!dryRun) {
4905                        recycleCachedViewAt(i);
4906                    }
4907                }
4908            }
4909            return null;
4910        }
4911
4912        void dispatchViewRecycled(ViewHolder holder) {
4913            if (mRecyclerListener != null) {
4914                mRecyclerListener.onViewRecycled(holder);
4915            }
4916            if (mAdapter != null) {
4917                mAdapter.onViewRecycled(holder);
4918            }
4919            if (mState != null) {
4920                mViewInfoStore.removeViewHolder(holder);
4921            }
4922            if (DEBUG) Log.d(TAG, "dispatchViewRecycled: " + holder);
4923        }
4924
4925        void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter,
4926                boolean compatibleWithPrevious) {
4927            clear();
4928            getRecycledViewPool().onAdapterChanged(oldAdapter, newAdapter, compatibleWithPrevious);
4929        }
4930
4931        void offsetPositionRecordsForMove(int from, int to) {
4932            final int start, end, inBetweenOffset;
4933            if (from < to) {
4934                start = from;
4935                end = to;
4936                inBetweenOffset = -1;
4937            } else {
4938                start = to;
4939                end = from;
4940                inBetweenOffset = 1;
4941            }
4942            final int cachedCount = mCachedViews.size();
4943            for (int i = 0; i < cachedCount; i++) {
4944                final ViewHolder holder = mCachedViews.get(i);
4945                if (holder == null || holder.mPosition < start || holder.mPosition > end) {
4946                    continue;
4947                }
4948                if (holder.mPosition == from) {
4949                    holder.offsetPosition(to - from, false);
4950                } else {
4951                    holder.offsetPosition(inBetweenOffset, false);
4952                }
4953                if (DEBUG) {
4954                    Log.d(TAG, "offsetPositionRecordsForMove cached child " + i + " holder " +
4955                            holder);
4956                }
4957            }
4958        }
4959
4960        void offsetPositionRecordsForInsert(int insertedAt, int count) {
4961            final int cachedCount = mCachedViews.size();
4962            for (int i = 0; i < cachedCount; i++) {
4963                final ViewHolder holder = mCachedViews.get(i);
4964                if (holder != null && holder.getLayoutPosition() >= insertedAt) {
4965                    if (DEBUG) {
4966                        Log.d(TAG, "offsetPositionRecordsForInsert cached " + i + " holder " +
4967                                holder + " now at position " + (holder.mPosition + count));
4968                    }
4969                    holder.offsetPosition(count, true);
4970                }
4971            }
4972        }
4973
4974        /**
4975         * @param removedFrom Remove start index
4976         * @param count Remove count
4977         * @param applyToPreLayout If true, changes will affect ViewHolder's pre-layout position, if
4978         *                         false, they'll be applied before the second layout pass
4979         */
4980        void offsetPositionRecordsForRemove(int removedFrom, int count, boolean applyToPreLayout) {
4981            final int removedEnd = removedFrom + count;
4982            final int cachedCount = mCachedViews.size();
4983            for (int i = cachedCount - 1; i >= 0; i--) {
4984                final ViewHolder holder = mCachedViews.get(i);
4985                if (holder != null) {
4986                    if (holder.getLayoutPosition() >= removedEnd) {
4987                        if (DEBUG) {
4988                            Log.d(TAG, "offsetPositionRecordsForRemove cached " + i +
4989                                    " holder " + holder + " now at position " +
4990                                    (holder.mPosition - count));
4991                        }
4992                        holder.offsetPosition(-count, applyToPreLayout);
4993                    } else if (holder.getLayoutPosition() >= removedFrom) {
4994                        // Item for this view was removed. Dump it from the cache.
4995                        holder.addFlags(ViewHolder.FLAG_REMOVED);
4996                        recycleCachedViewAt(i);
4997                    }
4998                }
4999            }
5000        }
5001
5002        void setViewCacheExtension(ViewCacheExtension extension) {
5003            mViewCacheExtension = extension;
5004        }
5005
5006        void setRecycledViewPool(RecycledViewPool pool) {
5007            if (mRecyclerPool != null) {
5008                mRecyclerPool.detach();
5009            }
5010            mRecyclerPool = pool;
5011            if (pool != null) {
5012                mRecyclerPool.attach(getAdapter());
5013            }
5014        }
5015
5016        RecycledViewPool getRecycledViewPool() {
5017            if (mRecyclerPool == null) {
5018                mRecyclerPool = new RecycledViewPool();
5019            }
5020            return mRecyclerPool;
5021        }
5022
5023        void viewRangeUpdate(int positionStart, int itemCount) {
5024            final int positionEnd = positionStart + itemCount;
5025            final int cachedCount = mCachedViews.size();
5026            for (int i = cachedCount - 1; i >= 0; i--) {
5027                final ViewHolder holder = mCachedViews.get(i);
5028                if (holder == null) {
5029                    continue;
5030                }
5031
5032                final int pos = holder.getLayoutPosition();
5033                if (pos >= positionStart && pos < positionEnd) {
5034                    holder.addFlags(ViewHolder.FLAG_UPDATE);
5035                    recycleCachedViewAt(i);
5036                    // cached views should not be flagged as changed because this will cause them
5037                    // to animate when they are returned from cache.
5038                }
5039            }
5040        }
5041
5042        void setAdapterPositionsAsUnknown() {
5043            final int cachedCount = mCachedViews.size();
5044            for (int i = 0; i < cachedCount; i++) {
5045                final ViewHolder holder = mCachedViews.get(i);
5046                if (holder != null) {
5047                    holder.addFlags(ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
5048                }
5049            }
5050        }
5051
5052        void markKnownViewsInvalid() {
5053            if (mAdapter != null && mAdapter.hasStableIds()) {
5054                final int cachedCount = mCachedViews.size();
5055                for (int i = 0; i < cachedCount; i++) {
5056                    final ViewHolder holder = mCachedViews.get(i);
5057                    if (holder != null) {
5058                        holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
5059                        holder.addChangePayload(null);
5060                    }
5061                }
5062            } else {
5063                // we cannot re-use cached views in this case. Recycle them all
5064                recycleAndClearCachedViews();
5065            }
5066        }
5067
5068        void clearOldPositions() {
5069            final int cachedCount = mCachedViews.size();
5070            for (int i = 0; i < cachedCount; i++) {
5071                final ViewHolder holder = mCachedViews.get(i);
5072                holder.clearOldPosition();
5073            }
5074            final int scrapCount = mAttachedScrap.size();
5075            for (int i = 0; i < scrapCount; i++) {
5076                mAttachedScrap.get(i).clearOldPosition();
5077            }
5078            if (mChangedScrap != null) {
5079                final int changedScrapCount = mChangedScrap.size();
5080                for (int i = 0; i < changedScrapCount; i++) {
5081                    mChangedScrap.get(i).clearOldPosition();
5082                }
5083            }
5084        }
5085
5086        void markItemDecorInsetsDirty() {
5087            final int cachedCount = mCachedViews.size();
5088            for (int i = 0; i < cachedCount; i++) {
5089                final ViewHolder holder = mCachedViews.get(i);
5090                LayoutParams layoutParams = (LayoutParams) holder.itemView.getLayoutParams();
5091                if (layoutParams != null) {
5092                    layoutParams.mInsetsDirty = true;
5093                }
5094            }
5095        }
5096    }
5097
5098    /**
5099     * ViewCacheExtension is a helper class to provide an additional layer of view caching that can
5100     * ben controlled by the developer.
5101     * <p>
5102     * When {@link Recycler#getViewForPosition(int)} is called, Recycler checks attached scrap and
5103     * first level cache to find a matching View. If it cannot find a suitable View, Recycler will
5104     * call the {@link #getViewForPositionAndType(Recycler, int, int)} before checking
5105     * {@link RecycledViewPool}.
5106     * <p>
5107     * Note that, Recycler never sends Views to this method to be cached. It is developers
5108     * responsibility to decide whether they want to keep their Views in this custom cache or let
5109     * the default recycling policy handle it.
5110     */
5111    public abstract static class ViewCacheExtension {
5112
5113        /**
5114         * Returns a View that can be binded to the given Adapter position.
5115         * <p>
5116         * This method should <b>not</b> create a new View. Instead, it is expected to return
5117         * an already created View that can be re-used for the given type and position.
5118         * If the View is marked as ignored, it should first call
5119         * {@link LayoutManager#stopIgnoringView(View)} before returning the View.
5120         * <p>
5121         * RecyclerView will re-bind the returned View to the position if necessary.
5122         *
5123         * @param recycler The Recycler that can be used to bind the View
5124         * @param position The adapter position
5125         * @param type     The type of the View, defined by adapter
5126         * @return A View that is bound to the given position or NULL if there is no View to re-use
5127         * @see LayoutManager#ignoreView(View)
5128         */
5129        abstract public View getViewForPositionAndType(Recycler recycler, int position, int type);
5130    }
5131
5132    /**
5133     * Base class for an Adapter
5134     *
5135     * <p>Adapters provide a binding from an app-specific data set to views that are displayed
5136     * within a {@link RecyclerView}.</p>
5137     */
5138    public static abstract class Adapter<VH extends ViewHolder> {
5139        private final AdapterDataObservable mObservable = new AdapterDataObservable();
5140        private boolean mHasStableIds = false;
5141
5142        /**
5143         * Called when RecyclerView needs a new {@link ViewHolder} of the given type to represent
5144         * an item.
5145         * <p>
5146         * This new ViewHolder should be constructed with a new View that can represent the items
5147         * of the given type. You can either create a new View manually or inflate it from an XML
5148         * layout file.
5149         * <p>
5150         * The new ViewHolder will be used to display items of the adapter using
5151         * {@link #onBindViewHolder(ViewHolder, int, List)}. Since it will be re-used to display
5152         * different items in the data set, it is a good idea to cache references to sub views of
5153         * the View to avoid unnecessary {@link View#findViewById(int)} calls.
5154         *
5155         * @param parent The ViewGroup into which the new View will be added after it is bound to
5156         *               an adapter position.
5157         * @param viewType The view type of the new View.
5158         *
5159         * @return A new ViewHolder that holds a View of the given view type.
5160         * @see #getItemViewType(int)
5161         * @see #onBindViewHolder(ViewHolder, int)
5162         */
5163        public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);
5164
5165        /**
5166         * Called by RecyclerView to display the data at the specified position. This method should
5167         * update the contents of the {@link ViewHolder#itemView} to reflect the item at the given
5168         * position.
5169         * <p>
5170         * Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method
5171         * again if the position of the item changes in the data set unless the item itself is
5172         * invalidated or the new position cannot be determined. For this reason, you should only
5173         * use the <code>position</code> parameter while acquiring the related data item inside
5174         * this method and should not keep a copy of it. If you need the position of an item later
5175         * on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
5176         * have the updated adapter position.
5177         *
5178         * Override {@link #onBindViewHolder(ViewHolder, int, List)} instead if Adapter can
5179         * handle effcient partial bind.
5180         *
5181         * @param holder The ViewHolder which should be updated to represent the contents of the
5182         *        item at the given position in the data set.
5183         * @param position The position of the item within the adapter's data set.
5184         */
5185        public abstract void onBindViewHolder(VH holder, int position);
5186
5187        /**
5188         * Called by RecyclerView to display the data at the specified position. This method
5189         * should update the contents of the {@link ViewHolder#itemView} to reflect the item at
5190         * the given position.
5191         * <p>
5192         * Note that unlike {@link android.widget.ListView}, RecyclerView will not call this method
5193         * again if the position of the item changes in the data set unless the item itself is
5194         * invalidated or the new position cannot be determined. For this reason, you should only
5195         * use the <code>position</code> parameter while acquiring the related data item inside
5196         * this method and should not keep a copy of it. If you need the position of an item later
5197         * on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
5198         * have the updated adapter position.
5199         * <p>
5200         * Partial bind vs full bind:
5201         * <p>
5202         * The payloads parameter is a merge list from {@link #notifyItemChanged(int, Object)} or
5203         * {@link #notifyItemRangeChanged(int, int, Object)}.  If the payloads list is not empty,
5204         * the ViewHolder is currently bound to old data and Adapter may run an efficient partial
5205         * update using the payload info.  If the payload is empty,  Adapter must run a full bind.
5206         * Adapter should not assume that the payload passed in notify methods will be received by
5207         * onBindViewHolder().  For example when the view is not attached to the screen, the
5208         * payload in notifyItemChange() will be simply dropped.
5209         *
5210         * @param holder The ViewHolder which should be updated to represent the contents of the
5211         *               item at the given position in the data set.
5212         * @param position The position of the item within the adapter's data set.
5213         * @param payloads A non-null list of merged payloads. Can be empty list if requires full
5214         *                 update.
5215         */
5216        public void onBindViewHolder(VH holder, int position, List<Object> payloads) {
5217            onBindViewHolder(holder, position);
5218        }
5219
5220        /**
5221         * This method calls {@link #onCreateViewHolder(ViewGroup, int)} to create a new
5222         * {@link ViewHolder} and initializes some private fields to be used by RecyclerView.
5223         *
5224         * @see #onCreateViewHolder(ViewGroup, int)
5225         */
5226        public final VH createViewHolder(ViewGroup parent, int viewType) {
5227            TraceCompat.beginSection(TRACE_CREATE_VIEW_TAG);
5228            final VH holder = onCreateViewHolder(parent, viewType);
5229            holder.mItemViewType = viewType;
5230            TraceCompat.endSection();
5231            return holder;
5232        }
5233
5234        /**
5235         * This method internally calls {@link #onBindViewHolder(ViewHolder, int)} to update the
5236         * {@link ViewHolder} contents with the item at the given position and also sets up some
5237         * private fields to be used by RecyclerView.
5238         *
5239         * @see #onBindViewHolder(ViewHolder, int)
5240         */
5241        public final void bindViewHolder(VH holder, int position) {
5242            holder.mPosition = position;
5243            if (hasStableIds()) {
5244                holder.mItemId = getItemId(position);
5245            }
5246            holder.setFlags(ViewHolder.FLAG_BOUND,
5247                    ViewHolder.FLAG_BOUND | ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID
5248                            | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN);
5249            TraceCompat.beginSection(TRACE_BIND_VIEW_TAG);
5250            onBindViewHolder(holder, position, holder.getUnmodifiedPayloads());
5251            holder.clearPayload();
5252            TraceCompat.endSection();
5253        }
5254
5255        /**
5256         * Return the view type of the item at <code>position</code> for the purposes
5257         * of view recycling.
5258         *
5259         * <p>The default implementation of this method returns 0, making the assumption of
5260         * a single view type for the adapter. Unlike ListView adapters, types need not
5261         * be contiguous. Consider using id resources to uniquely identify item view types.
5262         *
5263         * @param position position to query
5264         * @return integer value identifying the type of the view needed to represent the item at
5265         *                 <code>position</code>. Type codes need not be contiguous.
5266         */
5267        public int getItemViewType(int position) {
5268            return 0;
5269        }
5270
5271        /**
5272         * Indicates whether each item in the data set can be represented with a unique identifier
5273         * of type {@link java.lang.Long}.
5274         *
5275         * @param hasStableIds Whether items in data set have unique identifiers or not.
5276         * @see #hasStableIds()
5277         * @see #getItemId(int)
5278         */
5279        public void setHasStableIds(boolean hasStableIds) {
5280            if (hasObservers()) {
5281                throw new IllegalStateException("Cannot change whether this adapter has " +
5282                        "stable IDs while the adapter has registered observers.");
5283            }
5284            mHasStableIds = hasStableIds;
5285        }
5286
5287        /**
5288         * Return the stable ID for the item at <code>position</code>. If {@link #hasStableIds()}
5289         * would return false this method should return {@link #NO_ID}. The default implementation
5290         * of this method returns {@link #NO_ID}.
5291         *
5292         * @param position Adapter position to query
5293         * @return the stable ID of the item at position
5294         */
5295        public long getItemId(int position) {
5296            return NO_ID;
5297        }
5298
5299        /**
5300         * Returns the total number of items in the data set hold by the adapter.
5301         *
5302         * @return The total number of items in this adapter.
5303         */
5304        public abstract int getItemCount();
5305
5306        /**
5307         * Returns true if this adapter publishes a unique <code>long</code> value that can
5308         * act as a key for the item at a given position in the data set. If that item is relocated
5309         * in the data set, the ID returned for that item should be the same.
5310         *
5311         * @return true if this adapter's items have stable IDs
5312         */
5313        public final boolean hasStableIds() {
5314            return mHasStableIds;
5315        }
5316
5317        /**
5318         * Called when a view created by this adapter has been recycled.
5319         *
5320         * <p>A view is recycled when a {@link LayoutManager} decides that it no longer
5321         * needs to be attached to its parent {@link RecyclerView}. This can be because it has
5322         * fallen out of visibility or a set of cached views represented by views still
5323         * attached to the parent RecyclerView. If an item view has large or expensive data
5324         * bound to it such as large bitmaps, this may be a good place to release those
5325         * resources.</p>
5326         * <p>
5327         * RecyclerView calls this method right before clearing ViewHolder's internal data and
5328         * sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
5329         * before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
5330         * its adapter position.
5331         *
5332         * @param holder The ViewHolder for the view being recycled
5333         */
5334        public void onViewRecycled(VH holder) {
5335        }
5336
5337        /**
5338         * Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled
5339         * due to its transient state. Upon receiving this callback, Adapter can clear the
5340         * animation(s) that effect the View's transient state and return <code>true</code> so that
5341         * the View can be recycled. Keep in mind that the View in question is already removed from
5342         * the RecyclerView.
5343         * <p>
5344         * In some cases, it is acceptable to recycle a View although it has transient state. Most
5345         * of the time, this is a case where the transient state will be cleared in
5346         * {@link #onBindViewHolder(ViewHolder, int)} call when View is rebound to a new position.
5347         * For this reason, RecyclerView leaves the decision to the Adapter and uses the return
5348         * value of this method to decide whether the View should be recycled or not.
5349         * <p>
5350         * Note that when all animations are created by {@link RecyclerView.ItemAnimator}, you
5351         * should never receive this callback because RecyclerView keeps those Views as children
5352         * until their animations are complete. This callback is useful when children of the item
5353         * views create animations which may not be easy to implement using an {@link ItemAnimator}.
5354         * <p>
5355         * You should <em>never</em> fix this issue by calling
5356         * <code>holder.itemView.setHasTransientState(false);</code> unless you've previously called
5357         * <code>holder.itemView.setHasTransientState(true);</code>. Each
5358         * <code>View.setHasTransientState(true)</code> call must be matched by a
5359         * <code>View.setHasTransientState(false)</code> call, otherwise, the state of the View
5360         * may become inconsistent. You should always prefer to end or cancel animations that are
5361         * triggering the transient state instead of handling it manually.
5362         *
5363         * @param holder The ViewHolder containing the View that could not be recycled due to its
5364         *               transient state.
5365         * @return True if the View should be recycled, false otherwise. Note that if this method
5366         * returns <code>true</code>, RecyclerView <em>will ignore</em> the transient state of
5367         * the View and recycle it regardless. If this method returns <code>false</code>,
5368         * RecyclerView will check the View's transient state again before giving a final decision.
5369         * Default implementation returns false.
5370         */
5371        public boolean onFailedToRecycleView(VH holder) {
5372            return false;
5373        }
5374
5375        /**
5376         * Called when a view created by this adapter has been attached to a window.
5377         *
5378         * <p>This can be used as a reasonable signal that the view is about to be seen
5379         * by the user. If the adapter previously freed any resources in
5380         * {@link #onViewDetachedFromWindow(RecyclerView.ViewHolder) onViewDetachedFromWindow}
5381         * those resources should be restored here.</p>
5382         *
5383         * @param holder Holder of the view being attached
5384         */
5385        public void onViewAttachedToWindow(VH holder) {
5386        }
5387
5388        /**
5389         * Called when a view created by this adapter has been detached from its window.
5390         *
5391         * <p>Becoming detached from the window is not necessarily a permanent condition;
5392         * the consumer of an Adapter's views may choose to cache views offscreen while they
5393         * are not visible, attaching and detaching them as appropriate.</p>
5394         *
5395         * @param holder Holder of the view being detached
5396         */
5397        public void onViewDetachedFromWindow(VH holder) {
5398        }
5399
5400        /**
5401         * Returns true if one or more observers are attached to this adapter.
5402         *
5403         * @return true if this adapter has observers
5404         */
5405        public final boolean hasObservers() {
5406            return mObservable.hasObservers();
5407        }
5408
5409        /**
5410         * Register a new observer to listen for data changes.
5411         *
5412         * <p>The adapter may publish a variety of events describing specific changes.
5413         * Not all adapters may support all change types and some may fall back to a generic
5414         * {@link android.support.v7.widget.RecyclerView.AdapterDataObserver#onChanged()
5415         * "something changed"} event if more specific data is not available.</p>
5416         *
5417         * <p>Components registering observers with an adapter are responsible for
5418         * {@link #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
5419         * unregistering} those observers when finished.</p>
5420         *
5421         * @param observer Observer to register
5422         *
5423         * @see #unregisterAdapterDataObserver(RecyclerView.AdapterDataObserver)
5424         */
5425        public void registerAdapterDataObserver(AdapterDataObserver observer) {
5426            mObservable.registerObserver(observer);
5427        }
5428
5429        /**
5430         * Unregister an observer currently listening for data changes.
5431         *
5432         * <p>The unregistered observer will no longer receive events about changes
5433         * to the adapter.</p>
5434         *
5435         * @param observer Observer to unregister
5436         *
5437         * @see #registerAdapterDataObserver(RecyclerView.AdapterDataObserver)
5438         */
5439        public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
5440            mObservable.unregisterObserver(observer);
5441        }
5442
5443        /**
5444         * Called by RecyclerView when it starts observing this Adapter.
5445         * <p>
5446         * Keep in mind that same adapter may be observed by multiple RecyclerViews.
5447         *
5448         * @param recyclerView The RecyclerView instance which started observing this adapter.
5449         * @see #onDetachedFromRecyclerView(RecyclerView)
5450         */
5451        public void onAttachedToRecyclerView(RecyclerView recyclerView) {
5452        }
5453
5454        /**
5455         * Called by RecyclerView when it stops observing this Adapter.
5456         *
5457         * @param recyclerView The RecyclerView instance which stopped observing this adapter.
5458         * @see #onAttachedToRecyclerView(RecyclerView)
5459         */
5460        public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
5461        }
5462
5463        /**
5464         * Notify any registered observers that the data set has changed.
5465         *
5466         * <p>There are two different classes of data change events, item changes and structural
5467         * changes. Item changes are when a single item has its data updated but no positional
5468         * changes have occurred. Structural changes are when items are inserted, removed or moved
5469         * within the data set.</p>
5470         *
5471         * <p>This event does not specify what about the data set has changed, forcing
5472         * any observers to assume that all existing items and structure may no longer be valid.
5473         * LayoutManagers will be forced to fully rebind and relayout all visible views.</p>
5474         *
5475         * <p><code>RecyclerView</code> will attempt to synthesize visible structural change events
5476         * for adapters that report that they have {@link #hasStableIds() stable IDs} when
5477         * this method is used. This can help for the purposes of animation and visual
5478         * object persistence but individual item views will still need to be rebound
5479         * and relaid out.</p>
5480         *
5481         * <p>If you are writing an adapter it will always be more efficient to use the more
5482         * specific change events if you can. Rely on <code>notifyDataSetChanged()</code>
5483         * as a last resort.</p>
5484         *
5485         * @see #notifyItemChanged(int)
5486         * @see #notifyItemInserted(int)
5487         * @see #notifyItemRemoved(int)
5488         * @see #notifyItemRangeChanged(int, int)
5489         * @see #notifyItemRangeInserted(int, int)
5490         * @see #notifyItemRangeRemoved(int, int)
5491         */
5492        public final void notifyDataSetChanged() {
5493            mObservable.notifyChanged();
5494        }
5495
5496        /**
5497         * Notify any registered observers that the item at <code>position</code> has changed.
5498         * Equivalent to calling <code>notifyItemChanged(position, null);</code>.
5499         *
5500         * <p>This is an item change event, not a structural change event. It indicates that any
5501         * reflection of the data at <code>position</code> is out of date and should be updated.
5502         * The item at <code>position</code> retains the same identity.</p>
5503         *
5504         * @param position Position of the item that has changed
5505         *
5506         * @see #notifyItemRangeChanged(int, int)
5507         */
5508        public final void notifyItemChanged(int position) {
5509            mObservable.notifyItemRangeChanged(position, 1);
5510        }
5511
5512        /**
5513         * Notify any registered observers that the item at <code>position</code> has changed with an
5514         * optional payload object.
5515         *
5516         * <p>This is an item change event, not a structural change event. It indicates that any
5517         * reflection of the data at <code>position</code> is out of date and should be updated.
5518         * The item at <code>position</code> retains the same identity.
5519         * </p>
5520         *
5521         * <p>
5522         * Client can optionally pass a payload for partial change. These payloads will be merged
5523         * and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the
5524         * item is already represented by a ViewHolder and it will be rebound to the same
5525         * ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing
5526         * payloads on that item and prevent future payload until
5527         * {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume
5528         * that the payload will always be passed to onBindViewHolder(), e.g. when the view is not
5529         * attached, the payload will be simply dropped.
5530         *
5531         * @param position Position of the item that has changed
5532         * @param payload Optional parameter, use null to identify a "full" update
5533         *
5534         * @see #notifyItemRangeChanged(int, int)
5535         */
5536        public final void notifyItemChanged(int position, Object payload) {
5537            mObservable.notifyItemRangeChanged(position, 1, payload);
5538        }
5539
5540        /**
5541         * Notify any registered observers that the <code>itemCount</code> items starting at
5542         * position <code>positionStart</code> have changed.
5543         * Equivalent to calling <code>notifyItemRangeChanged(position, itemCount, null);</code>.
5544         *
5545         * <p>This is an item change event, not a structural change event. It indicates that
5546         * any reflection of the data in the given position range is out of date and should
5547         * be updated. The items in the given range retain the same identity.</p>
5548         *
5549         * @param positionStart Position of the first item that has changed
5550         * @param itemCount Number of items that have changed
5551         *
5552         * @see #notifyItemChanged(int)
5553         */
5554        public final void notifyItemRangeChanged(int positionStart, int itemCount) {
5555            mObservable.notifyItemRangeChanged(positionStart, itemCount);
5556        }
5557
5558        /**
5559         * Notify any registered observers that the <code>itemCount</code> items starting at
5560         * position<code>positionStart</code> have changed. An optional payload can be
5561         * passed to each changed item.
5562         *
5563         * <p>This is an item change event, not a structural change event. It indicates that any
5564         * reflection of the data in the given position range is out of date and should be updated.
5565         * The items in the given range retain the same identity.
5566         * </p>
5567         *
5568         * <p>
5569         * Client can optionally pass a payload for partial change. These payloads will be merged
5570         * and may be passed to adapter's {@link #onBindViewHolder(ViewHolder, int, List)} if the
5571         * item is already represented by a ViewHolder and it will be rebound to the same
5572         * ViewHolder. A notifyItemRangeChanged() with null payload will clear all existing
5573         * payloads on that item and prevent future payload until
5574         * {@link #onBindViewHolder(ViewHolder, int, List)} is called. Adapter should not assume
5575         * that the payload will always be passed to onBindViewHolder(), e.g. when the view is not
5576         * attached, the payload will be simply dropped.
5577         *
5578         * @param positionStart Position of the first item that has changed
5579         * @param itemCount Number of items that have changed
5580         * @param payload  Optional parameter, use null to identify a "full" update
5581         *
5582         * @see #notifyItemChanged(int)
5583         */
5584        public final void notifyItemRangeChanged(int positionStart, int itemCount, Object payload) {
5585            mObservable.notifyItemRangeChanged(positionStart, itemCount, payload);
5586        }
5587
5588        /**
5589         * Notify any registered observers that the item reflected at <code>position</code>
5590         * has been newly inserted. The item previously at <code>position</code> is now at
5591         * position <code>position + 1</code>.
5592         *
5593         * <p>This is a structural change event. Representations of other existing items in the
5594         * data set are still considered up to date and will not be rebound, though their
5595         * positions may be altered.</p>
5596         *
5597         * @param position Position of the newly inserted item in the data set
5598         *
5599         * @see #notifyItemRangeInserted(int, int)
5600         */
5601        public final void notifyItemInserted(int position) {
5602            mObservable.notifyItemRangeInserted(position, 1);
5603        }
5604
5605        /**
5606         * Notify any registered observers that the item reflected at <code>fromPosition</code>
5607         * has been moved to <code>toPosition</code>.
5608         *
5609         * <p>This is a structural change event. Representations of other existing items in the
5610         * data set are still considered up to date and will not be rebound, though their
5611         * positions may be altered.</p>
5612         *
5613         * @param fromPosition Previous position of the item.
5614         * @param toPosition New position of the item.
5615         */
5616        public final void notifyItemMoved(int fromPosition, int toPosition) {
5617            mObservable.notifyItemMoved(fromPosition, toPosition);
5618        }
5619
5620        /**
5621         * Notify any registered observers that the currently reflected <code>itemCount</code>
5622         * items starting at <code>positionStart</code> have been newly inserted. The items
5623         * previously located at <code>positionStart</code> and beyond can now be found starting
5624         * at position <code>positionStart + itemCount</code>.
5625         *
5626         * <p>This is a structural change event. Representations of other existing items in the
5627         * data set are still considered up to date and will not be rebound, though their positions
5628         * may be altered.</p>
5629         *
5630         * @param positionStart Position of the first item that was inserted
5631         * @param itemCount Number of items inserted
5632         *
5633         * @see #notifyItemInserted(int)
5634         */
5635        public final void notifyItemRangeInserted(int positionStart, int itemCount) {
5636            mObservable.notifyItemRangeInserted(positionStart, itemCount);
5637        }
5638
5639        /**
5640         * Notify any registered observers that the item previously located at <code>position</code>
5641         * has been removed from the data set. The items previously located at and after
5642         * <code>position</code> may now be found at <code>oldPosition - 1</code>.
5643         *
5644         * <p>This is a structural change event. Representations of other existing items in the
5645         * data set are still considered up to date and will not be rebound, though their positions
5646         * may be altered.</p>
5647         *
5648         * @param position Position of the item that has now been removed
5649         *
5650         * @see #notifyItemRangeRemoved(int, int)
5651         */
5652        public final void notifyItemRemoved(int position) {
5653            mObservable.notifyItemRangeRemoved(position, 1);
5654        }
5655
5656        /**
5657         * Notify any registered observers that the <code>itemCount</code> items previously
5658         * located at <code>positionStart</code> have been removed from the data set. The items
5659         * previously located at and after <code>positionStart + itemCount</code> may now be found
5660         * at <code>oldPosition - itemCount</code>.
5661         *
5662         * <p>This is a structural change event. Representations of other existing items in the data
5663         * set are still considered up to date and will not be rebound, though their positions
5664         * may be altered.</p>
5665         *
5666         * @param positionStart Previous position of the first item that was removed
5667         * @param itemCount Number of items removed from the data set
5668         */
5669        public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
5670            mObservable.notifyItemRangeRemoved(positionStart, itemCount);
5671        }
5672    }
5673
5674    private void dispatchChildDetached(View child) {
5675        final ViewHolder viewHolder = getChildViewHolderInt(child);
5676        onChildDetachedFromWindow(child);
5677        if (mAdapter != null && viewHolder != null) {
5678            mAdapter.onViewDetachedFromWindow(viewHolder);
5679        }
5680        if (mOnChildAttachStateListeners != null) {
5681            final int cnt = mOnChildAttachStateListeners.size();
5682            for (int i = cnt - 1; i >= 0; i--) {
5683                mOnChildAttachStateListeners.get(i).onChildViewDetachedFromWindow(child);
5684            }
5685        }
5686    }
5687
5688    private void dispatchChildAttached(View child) {
5689        final ViewHolder viewHolder = getChildViewHolderInt(child);
5690        onChildAttachedToWindow(child);
5691        if (mAdapter != null && viewHolder != null) {
5692            mAdapter.onViewAttachedToWindow(viewHolder);
5693        }
5694        if (mOnChildAttachStateListeners != null) {
5695            final int cnt = mOnChildAttachStateListeners.size();
5696            for (int i = cnt - 1; i >= 0; i--) {
5697                mOnChildAttachStateListeners.get(i).onChildViewAttachedToWindow(child);
5698            }
5699        }
5700
5701    }
5702
5703    /**
5704     * A <code>LayoutManager</code> is responsible for measuring and positioning item views
5705     * within a <code>RecyclerView</code> as well as determining the policy for when to recycle
5706     * item views that are no longer visible to the user. By changing the <code>LayoutManager</code>
5707     * a <code>RecyclerView</code> can be used to implement a standard vertically scrolling list,
5708     * a uniform grid, staggered grids, horizontally scrolling collections and more. Several stock
5709     * layout managers are provided for general use.
5710     * <p/>
5711     * If the LayoutManager specifies a default constructor or one with the signature
5712     * ({@link Context}, {@link AttributeSet}, {@code int}, {@code int}), RecyclerView will
5713     * instantiate and set the LayoutManager when being inflated. Most used properties can
5714     * be then obtained from {@link #getProperties(Context, AttributeSet, int, int)}. In case
5715     * a LayoutManager specifies both constructors, the non-default constructor will take
5716     * precedence.
5717     *
5718     */
5719    public static abstract class LayoutManager {
5720        ChildHelper mChildHelper;
5721        RecyclerView mRecyclerView;
5722
5723        @Nullable
5724        SmoothScroller mSmoothScroller;
5725
5726        private boolean mRequestedSimpleAnimations = false;
5727
5728        private boolean mIsAttachedToWindow = false;
5729
5730        void setRecyclerView(RecyclerView recyclerView) {
5731            if (recyclerView == null) {
5732                mRecyclerView = null;
5733                mChildHelper = null;
5734            } else {
5735                mRecyclerView = recyclerView;
5736                mChildHelper = recyclerView.mChildHelper;
5737            }
5738
5739        }
5740
5741        /**
5742         * Calls {@code RecyclerView#requestLayout} on the underlying RecyclerView
5743         */
5744        public void requestLayout() {
5745            if(mRecyclerView != null) {
5746                mRecyclerView.requestLayout();
5747            }
5748        }
5749
5750        /**
5751         * Checks if RecyclerView is in the middle of a layout or scroll and throws an
5752         * {@link IllegalStateException} if it <b>is not</b>.
5753         *
5754         * @param message The message for the exception. Can be null.
5755         * @see #assertNotInLayoutOrScroll(String)
5756         */
5757        public void assertInLayoutOrScroll(String message) {
5758            if (mRecyclerView != null) {
5759                mRecyclerView.assertInLayoutOrScroll(message);
5760            }
5761        }
5762
5763        /**
5764         * Checks if RecyclerView is in the middle of a layout or scroll and throws an
5765         * {@link IllegalStateException} if it <b>is</b>.
5766         *
5767         * @param message The message for the exception. Can be null.
5768         * @see #assertInLayoutOrScroll(String)
5769         */
5770        public void assertNotInLayoutOrScroll(String message) {
5771            if (mRecyclerView != null) {
5772                mRecyclerView.assertNotInLayoutOrScroll(message);
5773            }
5774        }
5775
5776        /**
5777         * Returns whether this LayoutManager supports automatic item animations.
5778         * A LayoutManager wishing to support item animations should obey certain
5779         * rules as outlined in {@link #onLayoutChildren(Recycler, State)}.
5780         * The default return value is <code>false</code>, so subclasses of LayoutManager
5781         * will not get predictive item animations by default.
5782         *
5783         * <p>Whether item animations are enabled in a RecyclerView is determined both
5784         * by the return value from this method and the
5785         * {@link RecyclerView#setItemAnimator(ItemAnimator) ItemAnimator} set on the
5786         * RecyclerView itself. If the RecyclerView has a non-null ItemAnimator but this
5787         * method returns false, then simple item animations will be enabled, in which
5788         * views that are moving onto or off of the screen are simply faded in/out. If
5789         * the RecyclerView has a non-null ItemAnimator and this method returns true,
5790         * then there will be two calls to {@link #onLayoutChildren(Recycler, State)} to
5791         * setup up the information needed to more intelligently predict where appearing
5792         * and disappearing views should be animated from/to.</p>
5793         *
5794         * @return true if predictive item animations should be enabled, false otherwise
5795         */
5796        public boolean supportsPredictiveItemAnimations() {
5797            return false;
5798        }
5799
5800        void dispatchAttachedToWindow(RecyclerView view) {
5801            mIsAttachedToWindow = true;
5802            onAttachedToWindow(view);
5803        }
5804
5805        void dispatchDetachedFromWindow(RecyclerView view, Recycler recycler) {
5806            mIsAttachedToWindow = false;
5807            onDetachedFromWindow(view, recycler);
5808        }
5809
5810        /**
5811         * Returns whether LayoutManager is currently attached to a RecyclerView which is attached
5812         * to a window.
5813         *
5814         * @return True if this LayoutManager is controlling a RecyclerView and the RecyclerView
5815         * is attached to window.
5816         */
5817        public boolean isAttachedToWindow() {
5818            return mIsAttachedToWindow;
5819        }
5820
5821        /**
5822         * Causes the Runnable to execute on the next animation time step.
5823         * The runnable will be run on the user interface thread.
5824         * <p>
5825         * Calling this method when LayoutManager is not attached to a RecyclerView has no effect.
5826         *
5827         * @param action The Runnable that will be executed.
5828         *
5829         * @see #removeCallbacks
5830         */
5831        public void postOnAnimation(Runnable action) {
5832            if (mRecyclerView != null) {
5833                ViewCompat.postOnAnimation(mRecyclerView, action);
5834            }
5835        }
5836
5837        /**
5838         * Removes the specified Runnable from the message queue.
5839         * <p>
5840         * Calling this method when LayoutManager is not attached to a RecyclerView has no effect.
5841         *
5842         * @param action The Runnable to remove from the message handling queue
5843         *
5844         * @return true if RecyclerView could ask the Handler to remove the Runnable,
5845         *         false otherwise. When the returned value is true, the Runnable
5846         *         may or may not have been actually removed from the message queue
5847         *         (for instance, if the Runnable was not in the queue already.)
5848         *
5849         * @see #postOnAnimation
5850         */
5851        public boolean removeCallbacks(Runnable action) {
5852            if (mRecyclerView != null) {
5853                return mRecyclerView.removeCallbacks(action);
5854            }
5855            return false;
5856        }
5857        /**
5858         * Called when this LayoutManager is both attached to a RecyclerView and that RecyclerView
5859         * is attached to a window.
5860         *
5861         * <p>Subclass implementations should always call through to the superclass implementation.
5862         * </p>
5863         *
5864         * @param view The RecyclerView this LayoutManager is bound to
5865         */
5866        @CallSuper
5867        public void onAttachedToWindow(RecyclerView view) {
5868        }
5869
5870        /**
5871         * @deprecated
5872         * override {@link #onDetachedFromWindow(RecyclerView, Recycler)}
5873         */
5874        @Deprecated
5875        public void onDetachedFromWindow(RecyclerView view) {
5876
5877        }
5878
5879        /**
5880         * Called when this LayoutManager is detached from its parent RecyclerView or when
5881         * its parent RecyclerView is detached from its window.
5882         *
5883         * <p>Subclass implementations should always call through to the superclass implementation.
5884         * </p>
5885         *
5886         * @param view The RecyclerView this LayoutManager is bound to
5887         * @param recycler The recycler to use if you prefer to recycle your children instead of
5888         *                 keeping them around.
5889         */
5890        @CallSuper
5891        public void onDetachedFromWindow(RecyclerView view, Recycler recycler) {
5892            onDetachedFromWindow(view);
5893        }
5894
5895        /**
5896         * Check if the RecyclerView is configured to clip child views to its padding.
5897         *
5898         * @return true if this RecyclerView clips children to its padding, false otherwise
5899         */
5900        public boolean getClipToPadding() {
5901            return mRecyclerView != null && mRecyclerView.mClipToPadding;
5902        }
5903
5904        /**
5905         * Lay out all relevant child views from the given adapter.
5906         *
5907         * The LayoutManager is in charge of the behavior of item animations. By default,
5908         * RecyclerView has a non-null {@link #getItemAnimator() ItemAnimator}, and simple
5909         * item animations are enabled. This means that add/remove operations on the
5910         * adapter will result in animations to add new or appearing items, removed or
5911         * disappearing items, and moved items. If a LayoutManager returns false from
5912         * {@link #supportsPredictiveItemAnimations()}, which is the default, and runs a
5913         * normal layout operation during {@link #onLayoutChildren(Recycler, State)}, the
5914         * RecyclerView will have enough information to run those animations in a simple
5915         * way. For example, the default ItemAnimator, {@link DefaultItemAnimator}, will
5916         * simply fade views in and out, whether they are actually added/removed or whether
5917         * they are moved on or off the screen due to other add/remove operations.
5918         *
5919         * <p>A LayoutManager wanting a better item animation experience, where items can be
5920         * animated onto and off of the screen according to where the items exist when they
5921         * are not on screen, then the LayoutManager should return true from
5922         * {@link #supportsPredictiveItemAnimations()} and add additional logic to
5923         * {@link #onLayoutChildren(Recycler, State)}. Supporting predictive animations
5924         * means that {@link #onLayoutChildren(Recycler, State)} will be called twice;
5925         * once as a "pre" layout step to determine where items would have been prior to
5926         * a real layout, and again to do the "real" layout. In the pre-layout phase,
5927         * items will remember their pre-layout positions to allow them to be laid out
5928         * appropriately. Also, {@link LayoutParams#isItemRemoved() removed} items will
5929         * be returned from the scrap to help determine correct placement of other items.
5930         * These removed items should not be added to the child list, but should be used
5931         * to help calculate correct positioning of other views, including views that
5932         * were not previously onscreen (referred to as APPEARING views), but whose
5933         * pre-layout offscreen position can be determined given the extra
5934         * information about the pre-layout removed views.</p>
5935         *
5936         * <p>The second layout pass is the real layout in which only non-removed views
5937         * will be used. The only additional requirement during this pass is, if
5938         * {@link #supportsPredictiveItemAnimations()} returns true, to note which
5939         * views exist in the child list prior to layout and which are not there after
5940         * layout (referred to as DISAPPEARING views), and to position/layout those views
5941         * appropriately, without regard to the actual bounds of the RecyclerView. This allows
5942         * the animation system to know the location to which to animate these disappearing
5943         * views.</p>
5944         *
5945         * <p>The default LayoutManager implementations for RecyclerView handle all of these
5946         * requirements for animations already. Clients of RecyclerView can either use one
5947         * of these layout managers directly or look at their implementations of
5948         * onLayoutChildren() to see how they account for the APPEARING and
5949         * DISAPPEARING views.</p>
5950         *
5951         * @param recycler         Recycler to use for fetching potentially cached views for a
5952         *                         position
5953         * @param state            Transient state of RecyclerView
5954         */
5955        public void onLayoutChildren(Recycler recycler, State state) {
5956            Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) ");
5957        }
5958
5959        /**
5960         * Create a default <code>LayoutParams</code> object for a child of the RecyclerView.
5961         *
5962         * <p>LayoutManagers will often want to use a custom <code>LayoutParams</code> type
5963         * to store extra information specific to the layout. Client code should subclass
5964         * {@link RecyclerView.LayoutParams} for this purpose.</p>
5965         *
5966         * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
5967         * you must also override
5968         * {@link #checkLayoutParams(LayoutParams)},
5969         * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
5970         * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
5971         *
5972         * @return A new LayoutParams for a child view
5973         */
5974        public abstract LayoutParams generateDefaultLayoutParams();
5975
5976        /**
5977         * Determines the validity of the supplied LayoutParams object.
5978         *
5979         * <p>This should check to make sure that the object is of the correct type
5980         * and all values are within acceptable ranges. The default implementation
5981         * returns <code>true</code> for non-null params.</p>
5982         *
5983         * @param lp LayoutParams object to check
5984         * @return true if this LayoutParams object is valid, false otherwise
5985         */
5986        public boolean checkLayoutParams(LayoutParams lp) {
5987            return lp != null;
5988        }
5989
5990        /**
5991         * Create a LayoutParams object suitable for this LayoutManager, copying relevant
5992         * values from the supplied LayoutParams object if possible.
5993         *
5994         * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
5995         * you must also override
5996         * {@link #checkLayoutParams(LayoutParams)},
5997         * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
5998         * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
5999         *
6000         * @param lp Source LayoutParams object to copy values from
6001         * @return a new LayoutParams object
6002         */
6003        public LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
6004            if (lp instanceof LayoutParams) {
6005                return new LayoutParams((LayoutParams) lp);
6006            } else if (lp instanceof MarginLayoutParams) {
6007                return new LayoutParams((MarginLayoutParams) lp);
6008            } else {
6009                return new LayoutParams(lp);
6010            }
6011        }
6012
6013        /**
6014         * Create a LayoutParams object suitable for this LayoutManager from
6015         * an inflated layout resource.
6016         *
6017         * <p><em>Important:</em> if you use your own custom <code>LayoutParams</code> type
6018         * you must also override
6019         * {@link #checkLayoutParams(LayoutParams)},
6020         * {@link #generateLayoutParams(android.view.ViewGroup.LayoutParams)} and
6021         * {@link #generateLayoutParams(android.content.Context, android.util.AttributeSet)}.</p>
6022         *
6023         * @param c Context for obtaining styled attributes
6024         * @param attrs AttributeSet describing the supplied arguments
6025         * @return a new LayoutParams object
6026         */
6027        public LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
6028            return new LayoutParams(c, attrs);
6029        }
6030
6031        /**
6032         * Scroll horizontally by dx pixels in screen coordinates and return the distance traveled.
6033         * The default implementation does nothing and returns 0.
6034         *
6035         * @param dx            distance to scroll by in pixels. X increases as scroll position
6036         *                      approaches the right.
6037         * @param recycler      Recycler to use for fetching potentially cached views for a
6038         *                      position
6039         * @param state         Transient state of RecyclerView
6040         * @return The actual distance scrolled. The return value will be negative if dx was
6041         * negative and scrolling proceeeded in that direction.
6042         * <code>Math.abs(result)</code> may be less than dx if a boundary was reached.
6043         */
6044        public int scrollHorizontallyBy(int dx, Recycler recycler, State state) {
6045            return 0;
6046        }
6047
6048        /**
6049         * Scroll vertically by dy pixels in screen coordinates and return the distance traveled.
6050         * The default implementation does nothing and returns 0.
6051         *
6052         * @param dy            distance to scroll in pixels. Y increases as scroll position
6053         *                      approaches the bottom.
6054         * @param recycler      Recycler to use for fetching potentially cached views for a
6055         *                      position
6056         * @param state         Transient state of RecyclerView
6057         * @return The actual distance scrolled. The return value will be negative if dy was
6058         * negative and scrolling proceeeded in that direction.
6059         * <code>Math.abs(result)</code> may be less than dy if a boundary was reached.
6060         */
6061        public int scrollVerticallyBy(int dy, Recycler recycler, State state) {
6062            return 0;
6063        }
6064
6065        /**
6066         * Query if horizontal scrolling is currently supported. The default implementation
6067         * returns false.
6068         *
6069         * @return True if this LayoutManager can scroll the current contents horizontally
6070         */
6071        public boolean canScrollHorizontally() {
6072            return false;
6073        }
6074
6075        /**
6076         * Query if vertical scrolling is currently supported. The default implementation
6077         * returns false.
6078         *
6079         * @return True if this LayoutManager can scroll the current contents vertically
6080         */
6081        public boolean canScrollVertically() {
6082            return false;
6083        }
6084
6085        /**
6086         * Scroll to the specified adapter position.
6087         *
6088         * Actual position of the item on the screen depends on the LayoutManager implementation.
6089         * @param position Scroll to this adapter position.
6090         */
6091        public void scrollToPosition(int position) {
6092            if (DEBUG) {
6093                Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract");
6094            }
6095        }
6096
6097        /**
6098         * <p>Smooth scroll to the specified adapter position.</p>
6099         * <p>To support smooth scrolling, override this method, create your {@link SmoothScroller}
6100         * instance and call {@link #startSmoothScroll(SmoothScroller)}.
6101         * </p>
6102         * @param recyclerView The RecyclerView to which this layout manager is attached
6103         * @param state    Current State of RecyclerView
6104         * @param position Scroll to this adapter position.
6105         */
6106        public void smoothScrollToPosition(RecyclerView recyclerView, State state,
6107                int position) {
6108            Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling");
6109        }
6110
6111        /**
6112         * <p>Starts a smooth scroll using the provided SmoothScroller.</p>
6113         * <p>Calling this method will cancel any previous smooth scroll request.</p>
6114         * @param smoothScroller Unstance which defines how smooth scroll should be animated
6115         */
6116        public void startSmoothScroll(SmoothScroller smoothScroller) {
6117            if (mSmoothScroller != null && smoothScroller != mSmoothScroller
6118                    && mSmoothScroller.isRunning()) {
6119                mSmoothScroller.stop();
6120            }
6121            mSmoothScroller = smoothScroller;
6122            mSmoothScroller.start(mRecyclerView, this);
6123        }
6124
6125        /**
6126         * @return true if RecycylerView is currently in the state of smooth scrolling.
6127         */
6128        public boolean isSmoothScrolling() {
6129            return mSmoothScroller != null && mSmoothScroller.isRunning();
6130        }
6131
6132
6133        /**
6134         * Returns the resolved layout direction for this RecyclerView.
6135         *
6136         * @return {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_RTL} if the layout
6137         * direction is RTL or returns
6138         * {@link android.support.v4.view.ViewCompat#LAYOUT_DIRECTION_LTR} if the layout direction
6139         * is not RTL.
6140         */
6141        public int getLayoutDirection() {
6142            return ViewCompat.getLayoutDirection(mRecyclerView);
6143        }
6144
6145        /**
6146         * Ends all animations on the view created by the {@link ItemAnimator}.
6147         *
6148         * @param view The View for which the animations should be ended.
6149         * @see RecyclerView.ItemAnimator#endAnimations()
6150         */
6151        public void endAnimation(View view) {
6152            if (mRecyclerView.mItemAnimator != null) {
6153                mRecyclerView.mItemAnimator.endAnimation(getChildViewHolderInt(view));
6154            }
6155        }
6156
6157        /**
6158         * To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
6159         * to the layout that is known to be going away, either because it has been
6160         * {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
6161         * visible portion of the container but is being laid out in order to inform RecyclerView
6162         * in how to animate the item out of view.
6163         * <p>
6164         * Views added via this method are going to be invisible to LayoutManager after the
6165         * dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
6166         * or won't be included in {@link #getChildCount()} method.
6167         *
6168         * @param child View to add and then remove with animation.
6169         */
6170        public void addDisappearingView(View child) {
6171            addDisappearingView(child, -1);
6172        }
6173
6174        /**
6175         * To be called only during {@link #onLayoutChildren(Recycler, State)} to add a view
6176         * to the layout that is known to be going away, either because it has been
6177         * {@link Adapter#notifyItemRemoved(int) removed} or because it is actually not in the
6178         * visible portion of the container but is being laid out in order to inform RecyclerView
6179         * in how to animate the item out of view.
6180         * <p>
6181         * Views added via this method are going to be invisible to LayoutManager after the
6182         * dispatchLayout pass is complete. They cannot be retrieved via {@link #getChildAt(int)}
6183         * or won't be included in {@link #getChildCount()} method.
6184         *
6185         * @param child View to add and then remove with animation.
6186         * @param index Index of the view.
6187         */
6188        public void addDisappearingView(View child, int index) {
6189            addViewInt(child, index, true);
6190        }
6191
6192        /**
6193         * Add a view to the currently attached RecyclerView if needed. LayoutManagers should
6194         * use this method to add views obtained from a {@link Recycler} using
6195         * {@link Recycler#getViewForPosition(int)}.
6196         *
6197         * @param child View to add
6198         */
6199        public void addView(View child) {
6200            addView(child, -1);
6201        }
6202
6203        /**
6204         * Add a view to the currently attached RecyclerView if needed. LayoutManagers should
6205         * use this method to add views obtained from a {@link Recycler} using
6206         * {@link Recycler#getViewForPosition(int)}.
6207         *
6208         * @param child View to add
6209         * @param index Index to add child at
6210         */
6211        public void addView(View child, int index) {
6212            addViewInt(child, index, false);
6213        }
6214
6215        private void addViewInt(View child, int index, boolean disappearing) {
6216            final ViewHolder holder = getChildViewHolderInt(child);
6217            if (disappearing || holder.isRemoved()) {
6218                // these views will be hidden at the end of the layout pass.
6219                mRecyclerView.mViewInfoStore.addToDisappearedInLayout(holder);
6220            } else {
6221                // This may look like unnecessary but may happen if layout manager supports
6222                // predictive layouts and adapter removed then re-added the same item.
6223                // In this case, added version will be visible in the post layout (because add is
6224                // deferred) but RV will still bind it to the same View.
6225                // So if a View re-appears in post layout pass, remove it from disappearing list.
6226                mRecyclerView.mViewInfoStore.removeFromDisappearedInLayout(holder);
6227            }
6228            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
6229            if (holder.wasReturnedFromScrap() || holder.isScrap()) {
6230                if (holder.isScrap()) {
6231                    holder.unScrap();
6232                } else {
6233                    holder.clearReturnedFromScrapFlag();
6234                }
6235                mChildHelper.attachViewToParent(child, index, child.getLayoutParams(), false);
6236                if (DISPATCH_TEMP_DETACH) {
6237                    ViewCompat.dispatchFinishTemporaryDetach(child);
6238                }
6239            } else if (child.getParent() == mRecyclerView) { // it was not a scrap but a valid child
6240                // ensure in correct position
6241                int currentIndex = mChildHelper.indexOfChild(child);
6242                if (index == -1) {
6243                    index = mChildHelper.getChildCount();
6244                }
6245                if (currentIndex == -1) {
6246                    throw new IllegalStateException("Added View has RecyclerView as parent but"
6247                            + " view is not a real child. Unfiltered index:"
6248                            + mRecyclerView.indexOfChild(child));
6249                }
6250                if (currentIndex != index) {
6251                    mRecyclerView.mLayout.moveView(currentIndex, index);
6252                }
6253            } else {
6254                mChildHelper.addView(child, index, false);
6255                lp.mInsetsDirty = true;
6256                if (mSmoothScroller != null && mSmoothScroller.isRunning()) {
6257                    mSmoothScroller.onChildAttachedToWindow(child);
6258                }
6259            }
6260            if (lp.mPendingInvalidate) {
6261                if (DEBUG) {
6262                    Log.d(TAG, "consuming pending invalidate on child " + lp.mViewHolder);
6263                }
6264                holder.itemView.invalidate();
6265                lp.mPendingInvalidate = false;
6266            }
6267        }
6268
6269        /**
6270         * Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
6271         * use this method to completely remove a child view that is no longer needed.
6272         * LayoutManagers should strongly consider recycling removed views using
6273         * {@link Recycler#recycleView(android.view.View)}.
6274         *
6275         * @param child View to remove
6276         */
6277        public void removeView(View child) {
6278            mChildHelper.removeView(child);
6279        }
6280
6281        /**
6282         * Remove a view from the currently attached RecyclerView if needed. LayoutManagers should
6283         * use this method to completely remove a child view that is no longer needed.
6284         * LayoutManagers should strongly consider recycling removed views using
6285         * {@link Recycler#recycleView(android.view.View)}.
6286         *
6287         * @param index Index of the child view to remove
6288         */
6289        public void removeViewAt(int index) {
6290            final View child = getChildAt(index);
6291            if (child != null) {
6292                mChildHelper.removeViewAt(index);
6293            }
6294        }
6295
6296        /**
6297         * Remove all views from the currently attached RecyclerView. This will not recycle
6298         * any of the affected views; the LayoutManager is responsible for doing so if desired.
6299         */
6300        public void removeAllViews() {
6301            // Only remove non-animating views
6302            final int childCount = getChildCount();
6303            for (int i = childCount - 1; i >= 0; i--) {
6304                mChildHelper.removeViewAt(i);
6305            }
6306        }
6307
6308        /**
6309         * Returns offset of the RecyclerView's text baseline from the its top boundary.
6310         *
6311         * @return The offset of the RecyclerView's text baseline from the its top boundary; -1 if
6312         * there is no baseline.
6313         */
6314        public int getBaseline() {
6315            return -1;
6316        }
6317
6318        /**
6319         * Returns the adapter position of the item represented by the given View. This does not
6320         * contain any adapter changes that might have happened after the last layout.
6321         *
6322         * @param view The view to query
6323         * @return The adapter position of the item which is rendered by this View.
6324         */
6325        public int getPosition(View view) {
6326            return ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition();
6327        }
6328
6329        /**
6330         * Returns the View type defined by the adapter.
6331         *
6332         * @param view The view to query
6333         * @return The type of the view assigned by the adapter.
6334         */
6335        public int getItemViewType(View view) {
6336            return getChildViewHolderInt(view).getItemViewType();
6337        }
6338
6339        /**
6340         * Finds the view which represents the given adapter position.
6341         * <p>
6342         * This method traverses each child since it has no information about child order.
6343         * Override this method to improve performance if your LayoutManager keeps data about
6344         * child views.
6345         * <p>
6346         * If a view is ignored via {@link #ignoreView(View)}, it is also ignored by this method.
6347         *
6348         * @param position Position of the item in adapter
6349         * @return The child view that represents the given position or null if the position is not
6350         * laid out
6351         */
6352        public View findViewByPosition(int position) {
6353            final int childCount = getChildCount();
6354            for (int i = 0; i < childCount; i++) {
6355                View child = getChildAt(i);
6356                ViewHolder vh = getChildViewHolderInt(child);
6357                if (vh == null) {
6358                    continue;
6359                }
6360                if (vh.getLayoutPosition() == position && !vh.shouldIgnore() &&
6361                        (mRecyclerView.mState.isPreLayout() || !vh.isRemoved())) {
6362                    return child;
6363                }
6364            }
6365            return null;
6366        }
6367
6368        /**
6369         * Temporarily detach a child view.
6370         *
6371         * <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
6372         * views currently attached to the RecyclerView. Generally LayoutManager implementations
6373         * will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
6374         * so that the detached view may be rebound and reused.</p>
6375         *
6376         * <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
6377         * {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
6378         * or {@link #removeDetachedView(android.view.View) fully remove} the detached view
6379         * before the LayoutManager entry point method called by RecyclerView returns.</p>
6380         *
6381         * @param child Child to detach
6382         */
6383        public void detachView(View child) {
6384            final int ind = mChildHelper.indexOfChild(child);
6385            if (ind >= 0) {
6386                detachViewInternal(ind, child);
6387            }
6388        }
6389
6390        /**
6391         * Temporarily detach a child view.
6392         *
6393         * <p>LayoutManagers may want to perform a lightweight detach operation to rearrange
6394         * views currently attached to the RecyclerView. Generally LayoutManager implementations
6395         * will want to use {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}
6396         * so that the detached view may be rebound and reused.</p>
6397         *
6398         * <p>If a LayoutManager uses this method to detach a view, it <em>must</em>
6399         * {@link #attachView(android.view.View, int, RecyclerView.LayoutParams) reattach}
6400         * or {@link #removeDetachedView(android.view.View) fully remove} the detached view
6401         * before the LayoutManager entry point method called by RecyclerView returns.</p>
6402         *
6403         * @param index Index of the child to detach
6404         */
6405        public void detachViewAt(int index) {
6406            detachViewInternal(index, getChildAt(index));
6407        }
6408
6409        private void detachViewInternal(int index, View view) {
6410            if (DISPATCH_TEMP_DETACH) {
6411                ViewCompat.dispatchStartTemporaryDetach(view);
6412            }
6413            mChildHelper.detachViewFromParent(index);
6414        }
6415
6416        /**
6417         * Reattach a previously {@link #detachView(android.view.View) detached} view.
6418         * This method should not be used to reattach views that were previously
6419         * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}  scrapped}.
6420         *
6421         * @param child Child to reattach
6422         * @param index Intended child index for child
6423         * @param lp LayoutParams for child
6424         */
6425        public void attachView(View child, int index, LayoutParams lp) {
6426            ViewHolder vh = getChildViewHolderInt(child);
6427            if (vh.isRemoved()) {
6428                mRecyclerView.mViewInfoStore.addToDisappearedInLayout(vh);
6429            } else {
6430                mRecyclerView.mViewInfoStore.removeFromDisappearedInLayout(vh);
6431            }
6432            mChildHelper.attachViewToParent(child, index, lp, vh.isRemoved());
6433            if (DISPATCH_TEMP_DETACH)  {
6434                ViewCompat.dispatchFinishTemporaryDetach(child);
6435            }
6436        }
6437
6438        /**
6439         * Reattach a previously {@link #detachView(android.view.View) detached} view.
6440         * This method should not be used to reattach views that were previously
6441         * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}  scrapped}.
6442         *
6443         * @param child Child to reattach
6444         * @param index Intended child index for child
6445         */
6446        public void attachView(View child, int index) {
6447            attachView(child, index, (LayoutParams) child.getLayoutParams());
6448        }
6449
6450        /**
6451         * Reattach a previously {@link #detachView(android.view.View) detached} view.
6452         * This method should not be used to reattach views that were previously
6453         * {@link #detachAndScrapView(android.view.View, RecyclerView.Recycler)}  scrapped}.
6454         *
6455         * @param child Child to reattach
6456         */
6457        public void attachView(View child) {
6458            attachView(child, -1);
6459        }
6460
6461        /**
6462         * Finish removing a view that was previously temporarily
6463         * {@link #detachView(android.view.View) detached}.
6464         *
6465         * @param child Detached child to remove
6466         */
6467        public void removeDetachedView(View child) {
6468            mRecyclerView.removeDetachedView(child, false);
6469        }
6470
6471        /**
6472         * Moves a View from one position to another.
6473         *
6474         * @param fromIndex The View's initial index
6475         * @param toIndex The View's target index
6476         */
6477        public void moveView(int fromIndex, int toIndex) {
6478            View view = getChildAt(fromIndex);
6479            if (view == null) {
6480                throw new IllegalArgumentException("Cannot move a child from non-existing index:"
6481                        + fromIndex);
6482            }
6483            detachViewAt(fromIndex);
6484            attachView(view, toIndex);
6485        }
6486
6487        /**
6488         * Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
6489         *
6490         * <p>Scrapping a view allows it to be rebound and reused to show updated or
6491         * different data.</p>
6492         *
6493         * @param child Child to detach and scrap
6494         * @param recycler Recycler to deposit the new scrap view into
6495         */
6496        public void detachAndScrapView(View child, Recycler recycler) {
6497            int index = mChildHelper.indexOfChild(child);
6498            scrapOrRecycleView(recycler, index, child);
6499        }
6500
6501        /**
6502         * Detach a child view and add it to a {@link Recycler Recycler's} scrap heap.
6503         *
6504         * <p>Scrapping a view allows it to be rebound and reused to show updated or
6505         * different data.</p>
6506         *
6507         * @param index Index of child to detach and scrap
6508         * @param recycler Recycler to deposit the new scrap view into
6509         */
6510        public void detachAndScrapViewAt(int index, Recycler recycler) {
6511            final View child = getChildAt(index);
6512            scrapOrRecycleView(recycler, index, child);
6513        }
6514
6515        /**
6516         * Remove a child view and recycle it using the given Recycler.
6517         *
6518         * @param child Child to remove and recycle
6519         * @param recycler Recycler to use to recycle child
6520         */
6521        public void removeAndRecycleView(View child, Recycler recycler) {
6522            removeView(child);
6523            recycler.recycleView(child);
6524        }
6525
6526        /**
6527         * Remove a child view and recycle it using the given Recycler.
6528         *
6529         * @param index Index of child to remove and recycle
6530         * @param recycler Recycler to use to recycle child
6531         */
6532        public void removeAndRecycleViewAt(int index, Recycler recycler) {
6533            final View view = getChildAt(index);
6534            removeViewAt(index);
6535            recycler.recycleView(view);
6536        }
6537
6538        /**
6539         * Return the current number of child views attached to the parent RecyclerView.
6540         * This does not include child views that were temporarily detached and/or scrapped.
6541         *
6542         * @return Number of attached children
6543         */
6544        public int getChildCount() {
6545            return mChildHelper != null ? mChildHelper.getChildCount() : 0;
6546        }
6547
6548        /**
6549         * Return the child view at the given index
6550         * @param index Index of child to return
6551         * @return Child view at index
6552         */
6553        public View getChildAt(int index) {
6554            return mChildHelper != null ? mChildHelper.getChildAt(index) : null;
6555        }
6556
6557        /**
6558         * Return the width of the parent RecyclerView
6559         *
6560         * @return Width in pixels
6561         */
6562        public int getWidth() {
6563            return mRecyclerView != null ? mRecyclerView.getWidth() : 0;
6564        }
6565
6566        /**
6567         * Return the height of the parent RecyclerView
6568         *
6569         * @return Height in pixels
6570         */
6571        public int getHeight() {
6572            return mRecyclerView != null ? mRecyclerView.getHeight() : 0;
6573        }
6574
6575        /**
6576         * Return the left padding of the parent RecyclerView
6577         *
6578         * @return Padding in pixels
6579         */
6580        public int getPaddingLeft() {
6581            return mRecyclerView != null ? mRecyclerView.getPaddingLeft() : 0;
6582        }
6583
6584        /**
6585         * Return the top padding of the parent RecyclerView
6586         *
6587         * @return Padding in pixels
6588         */
6589        public int getPaddingTop() {
6590            return mRecyclerView != null ? mRecyclerView.getPaddingTop() : 0;
6591        }
6592
6593        /**
6594         * Return the right padding of the parent RecyclerView
6595         *
6596         * @return Padding in pixels
6597         */
6598        public int getPaddingRight() {
6599            return mRecyclerView != null ? mRecyclerView.getPaddingRight() : 0;
6600        }
6601
6602        /**
6603         * Return the bottom padding of the parent RecyclerView
6604         *
6605         * @return Padding in pixels
6606         */
6607        public int getPaddingBottom() {
6608            return mRecyclerView != null ? mRecyclerView.getPaddingBottom() : 0;
6609        }
6610
6611        /**
6612         * Return the start padding of the parent RecyclerView
6613         *
6614         * @return Padding in pixels
6615         */
6616        public int getPaddingStart() {
6617            return mRecyclerView != null ? ViewCompat.getPaddingStart(mRecyclerView) : 0;
6618        }
6619
6620        /**
6621         * Return the end padding of the parent RecyclerView
6622         *
6623         * @return Padding in pixels
6624         */
6625        public int getPaddingEnd() {
6626            return mRecyclerView != null ? ViewCompat.getPaddingEnd(mRecyclerView) : 0;
6627        }
6628
6629        /**
6630         * Returns true if the RecyclerView this LayoutManager is bound to has focus.
6631         *
6632         * @return True if the RecyclerView has focus, false otherwise.
6633         * @see View#isFocused()
6634         */
6635        public boolean isFocused() {
6636            return mRecyclerView != null && mRecyclerView.isFocused();
6637        }
6638
6639        /**
6640         * Returns true if the RecyclerView this LayoutManager is bound to has or contains focus.
6641         *
6642         * @return true if the RecyclerView has or contains focus
6643         * @see View#hasFocus()
6644         */
6645        public boolean hasFocus() {
6646            return mRecyclerView != null && mRecyclerView.hasFocus();
6647        }
6648
6649        /**
6650         * Returns the item View which has or contains focus.
6651         *
6652         * @return A direct child of RecyclerView which has focus or contains the focused child.
6653         */
6654        public View getFocusedChild() {
6655            if (mRecyclerView == null) {
6656                return null;
6657            }
6658            final View focused = mRecyclerView.getFocusedChild();
6659            if (focused == null || mChildHelper.isHidden(focused)) {
6660                return null;
6661            }
6662            return focused;
6663        }
6664
6665        /**
6666         * Returns the number of items in the adapter bound to the parent RecyclerView.
6667         * <p>
6668         * Note that this number is not necessarily equal to {@link State#getItemCount()}. In
6669         * methods where State is available, you should use {@link State#getItemCount()} instead.
6670         * For more details, check the documentation for {@link State#getItemCount()}.
6671         *
6672         * @return The number of items in the bound adapter
6673         * @see State#getItemCount()
6674         */
6675        public int getItemCount() {
6676            final Adapter a = mRecyclerView != null ? mRecyclerView.getAdapter() : null;
6677            return a != null ? a.getItemCount() : 0;
6678        }
6679
6680        /**
6681         * Offset all child views attached to the parent RecyclerView by dx pixels along
6682         * the horizontal axis.
6683         *
6684         * @param dx Pixels to offset by
6685         */
6686        public void offsetChildrenHorizontal(int dx) {
6687            if (mRecyclerView != null) {
6688                mRecyclerView.offsetChildrenHorizontal(dx);
6689            }
6690        }
6691
6692        /**
6693         * Offset all child views attached to the parent RecyclerView by dy pixels along
6694         * the vertical axis.
6695         *
6696         * @param dy Pixels to offset by
6697         */
6698        public void offsetChildrenVertical(int dy) {
6699            if (mRecyclerView != null) {
6700                mRecyclerView.offsetChildrenVertical(dy);
6701            }
6702        }
6703
6704        /**
6705         * Flags a view so that it will not be scrapped or recycled.
6706         * <p>
6707         * Scope of ignoring a child is strictly restricted to position tracking, scrapping and
6708         * recyling. Methods like {@link #removeAndRecycleAllViews(Recycler)} will ignore the child
6709         * whereas {@link #removeAllViews()} or {@link #offsetChildrenHorizontal(int)} will not
6710         * ignore the child.
6711         * <p>
6712         * Before this child can be recycled again, you have to call
6713         * {@link #stopIgnoringView(View)}.
6714         * <p>
6715         * You can call this method only if your LayoutManger is in onLayout or onScroll callback.
6716         *
6717         * @param view View to ignore.
6718         * @see #stopIgnoringView(View)
6719         */
6720        public void ignoreView(View view) {
6721            if (view.getParent() != mRecyclerView || mRecyclerView.indexOfChild(view) == -1) {
6722                // checking this because calling this method on a recycled or detached view may
6723                // cause loss of state.
6724                throw new IllegalArgumentException("View should be fully attached to be ignored");
6725            }
6726            final ViewHolder vh = getChildViewHolderInt(view);
6727            vh.addFlags(ViewHolder.FLAG_IGNORE);
6728            mRecyclerView.mViewInfoStore.removeViewHolder(vh);
6729        }
6730
6731        /**
6732         * View can be scrapped and recycled again.
6733         * <p>
6734         * Note that calling this method removes all information in the view holder.
6735         * <p>
6736         * You can call this method only if your LayoutManger is in onLayout or onScroll callback.
6737         *
6738         * @param view View to ignore.
6739         */
6740        public void stopIgnoringView(View view) {
6741            final ViewHolder vh = getChildViewHolderInt(view);
6742            vh.stopIgnoring();
6743            vh.resetInternal();
6744            vh.addFlags(ViewHolder.FLAG_INVALID);
6745        }
6746
6747        /**
6748         * Temporarily detach and scrap all currently attached child views. Views will be scrapped
6749         * into the given Recycler. The Recycler may prefer to reuse scrap views before
6750         * other views that were previously recycled.
6751         *
6752         * @param recycler Recycler to scrap views into
6753         */
6754        public void detachAndScrapAttachedViews(Recycler recycler) {
6755            final int childCount = getChildCount();
6756            for (int i = childCount - 1; i >= 0; i--) {
6757                final View v = getChildAt(i);
6758                scrapOrRecycleView(recycler, i, v);
6759            }
6760        }
6761
6762        private void scrapOrRecycleView(Recycler recycler, int index, View view) {
6763            final ViewHolder viewHolder = getChildViewHolderInt(view);
6764            if (viewHolder.shouldIgnore()) {
6765                if (DEBUG) {
6766                    Log.d(TAG, "ignoring view " + viewHolder);
6767                }
6768                return;
6769            }
6770            if (viewHolder.isInvalid() && !viewHolder.isRemoved() &&
6771                    !mRecyclerView.mAdapter.hasStableIds()) {
6772                removeViewAt(index);
6773                recycler.recycleViewHolderInternal(viewHolder);
6774            } else {
6775                detachViewAt(index);
6776                recycler.scrapView(view);
6777            }
6778        }
6779
6780        /**
6781         * Recycles the scrapped views.
6782         * <p>
6783         * When a view is detached and removed, it does not trigger a ViewGroup invalidate. This is
6784         * the expected behavior if scrapped views are used for animations. Otherwise, we need to
6785         * call remove and invalidate RecyclerView to ensure UI update.
6786         *
6787         * @param recycler Recycler
6788         */
6789        void removeAndRecycleScrapInt(Recycler recycler) {
6790            final int scrapCount = recycler.getScrapCount();
6791            // Loop backward, recycler might be changed by removeDetachedView()
6792            for (int i = scrapCount - 1; i >= 0; i--) {
6793                final View scrap = recycler.getScrapViewAt(i);
6794                final ViewHolder vh = getChildViewHolderInt(scrap);
6795                if (vh.shouldIgnore()) {
6796                    continue;
6797                }
6798                // If the scrap view is animating, we need to cancel them first. If we cancel it
6799                // here, ItemAnimator callback may recycle it which will cause double recycling.
6800                // To avoid this, we mark it as not recycleable before calling the item animator.
6801                // Since removeDetachedView calls a user API, a common mistake (ending animations on
6802                // the view) may recycle it too, so we guard it before we call user APIs.
6803                vh.setIsRecyclable(false);
6804                if (vh.isTmpDetached()) {
6805                    mRecyclerView.removeDetachedView(scrap, false);
6806                }
6807                if (mRecyclerView.mItemAnimator != null) {
6808                    mRecyclerView.mItemAnimator.endAnimation(vh);
6809                }
6810                vh.setIsRecyclable(true);
6811                recycler.quickRecycleScrapView(scrap);
6812            }
6813            recycler.clearScrap();
6814            if (scrapCount > 0) {
6815                mRecyclerView.invalidate();
6816            }
6817        }
6818
6819
6820        /**
6821         * Measure a child view using standard measurement policy, taking the padding
6822         * of the parent RecyclerView and any added item decorations into account.
6823         *
6824         * <p>If the RecyclerView can be scrolled in either dimension the caller may
6825         * pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
6826         *
6827         * @param child Child view to measure
6828         * @param widthUsed Width in pixels currently consumed by other views, if relevant
6829         * @param heightUsed Height in pixels currently consumed by other views, if relevant
6830         */
6831        public void measureChild(View child, int widthUsed, int heightUsed) {
6832            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
6833
6834            final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
6835            widthUsed += insets.left + insets.right;
6836            heightUsed += insets.top + insets.bottom;
6837
6838            final int widthSpec = getChildMeasureSpec(getWidth(),
6839                    getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
6840                    canScrollHorizontally());
6841            final int heightSpec = getChildMeasureSpec(getHeight(),
6842                    getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
6843                    canScrollVertically());
6844            child.measure(widthSpec, heightSpec);
6845        }
6846
6847        /**
6848         * Measure a child view using standard measurement policy, taking the padding
6849         * of the parent RecyclerView, any added item decorations and the child margins
6850         * into account.
6851         *
6852         * <p>If the RecyclerView can be scrolled in either dimension the caller may
6853         * pass 0 as the widthUsed or heightUsed parameters as they will be irrelevant.</p>
6854         *
6855         * @param child Child view to measure
6856         * @param widthUsed Width in pixels currently consumed by other views, if relevant
6857         * @param heightUsed Height in pixels currently consumed by other views, if relevant
6858         */
6859        public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
6860            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
6861
6862            final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
6863            widthUsed += insets.left + insets.right;
6864            heightUsed += insets.top + insets.bottom;
6865
6866            final int widthSpec = getChildMeasureSpec(getWidth(),
6867                    getPaddingLeft() + getPaddingRight() +
6868                            lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
6869                    canScrollHorizontally());
6870            final int heightSpec = getChildMeasureSpec(getHeight(),
6871                    getPaddingTop() + getPaddingBottom() +
6872                            lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
6873                    canScrollVertically());
6874            child.measure(widthSpec, heightSpec);
6875        }
6876
6877        /**
6878         * Calculate a MeasureSpec value for measuring a child view in one dimension.
6879         *
6880         * @param parentSize Size of the parent view where the child will be placed
6881         * @param padding Total space currently consumed by other elements of parent
6882         * @param childDimension Desired size of the child view, or MATCH_PARENT/WRAP_CONTENT.
6883         *                       Generally obtained from the child view's LayoutParams
6884         * @param canScroll true if the parent RecyclerView can scroll in this dimension
6885         *
6886         * @return a MeasureSpec value for the child view
6887         */
6888        public static int getChildMeasureSpec(int parentSize, int padding, int childDimension,
6889                boolean canScroll) {
6890            int size = Math.max(0, parentSize - padding);
6891            int resultSize = 0;
6892            int resultMode = 0;
6893
6894            if (canScroll) {
6895                if (childDimension >= 0) {
6896                    resultSize = childDimension;
6897                    resultMode = MeasureSpec.EXACTLY;
6898                } else {
6899                    // MATCH_PARENT can't be applied since we can scroll in this dimension, wrap
6900                    // instead using UNSPECIFIED.
6901                    resultSize = 0;
6902                    resultMode = MeasureSpec.UNSPECIFIED;
6903                }
6904            } else {
6905                if (childDimension >= 0) {
6906                    resultSize = childDimension;
6907                    resultMode = MeasureSpec.EXACTLY;
6908                } else if (childDimension == LayoutParams.FILL_PARENT) {
6909                    resultSize = size;
6910                    resultMode = MeasureSpec.EXACTLY;
6911                } else if (childDimension == LayoutParams.WRAP_CONTENT) {
6912                    resultSize = size;
6913                    resultMode = MeasureSpec.AT_MOST;
6914                }
6915            }
6916            return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
6917        }
6918
6919        /**
6920         * Returns the measured width of the given child, plus the additional size of
6921         * any insets applied by {@link ItemDecoration ItemDecorations}.
6922         *
6923         * @param child Child view to query
6924         * @return child's measured width plus <code>ItemDecoration</code> insets
6925         *
6926         * @see View#getMeasuredWidth()
6927         */
6928        public int getDecoratedMeasuredWidth(View child) {
6929            final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
6930            return child.getMeasuredWidth() + insets.left + insets.right;
6931        }
6932
6933        /**
6934         * Returns the measured height of the given child, plus the additional size of
6935         * any insets applied by {@link ItemDecoration ItemDecorations}.
6936         *
6937         * @param child Child view to query
6938         * @return child's measured height plus <code>ItemDecoration</code> insets
6939         *
6940         * @see View#getMeasuredHeight()
6941         */
6942        public int getDecoratedMeasuredHeight(View child) {
6943            final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
6944            return child.getMeasuredHeight() + insets.top + insets.bottom;
6945        }
6946
6947        /**
6948         * Lay out the given child view within the RecyclerView using coordinates that
6949         * include any current {@link ItemDecoration ItemDecorations}.
6950         *
6951         * <p>LayoutManagers should prefer working in sizes and coordinates that include
6952         * item decoration insets whenever possible. This allows the LayoutManager to effectively
6953         * ignore decoration insets within measurement and layout code. See the following
6954         * methods:</p>
6955         * <ul>
6956         *     <li>{@link #measureChild(View, int, int)}</li>
6957         *     <li>{@link #measureChildWithMargins(View, int, int)}</li>
6958         *     <li>{@link #getDecoratedLeft(View)}</li>
6959         *     <li>{@link #getDecoratedTop(View)}</li>
6960         *     <li>{@link #getDecoratedRight(View)}</li>
6961         *     <li>{@link #getDecoratedBottom(View)}</li>
6962         *     <li>{@link #getDecoratedMeasuredWidth(View)}</li>
6963         *     <li>{@link #getDecoratedMeasuredHeight(View)}</li>
6964         * </ul>
6965         *
6966         * @param child Child to lay out
6967         * @param left Left edge, with item decoration insets included
6968         * @param top Top edge, with item decoration insets included
6969         * @param right Right edge, with item decoration insets included
6970         * @param bottom Bottom edge, with item decoration insets included
6971         *
6972         * @see View#layout(int, int, int, int)
6973         */
6974        public void layoutDecorated(View child, int left, int top, int right, int bottom) {
6975            final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
6976            child.layout(left + insets.left, top + insets.top, right - insets.right,
6977                    bottom - insets.bottom);
6978        }
6979
6980        /**
6981         * Returns the left edge of the given child view within its parent, offset by any applied
6982         * {@link ItemDecoration ItemDecorations}.
6983         *
6984         * @param child Child to query
6985         * @return Child left edge with offsets applied
6986         * @see #getLeftDecorationWidth(View)
6987         */
6988        public int getDecoratedLeft(View child) {
6989            return child.getLeft() - getLeftDecorationWidth(child);
6990        }
6991
6992        /**
6993         * Returns the top edge of the given child view within its parent, offset by any applied
6994         * {@link ItemDecoration ItemDecorations}.
6995         *
6996         * @param child Child to query
6997         * @return Child top edge with offsets applied
6998         * @see #getTopDecorationHeight(View)
6999         */
7000        public int getDecoratedTop(View child) {
7001            return child.getTop() - getTopDecorationHeight(child);
7002        }
7003
7004        /**
7005         * Returns the right edge of the given child view within its parent, offset by any applied
7006         * {@link ItemDecoration ItemDecorations}.
7007         *
7008         * @param child Child to query
7009         * @return Child right edge with offsets applied
7010         * @see #getRightDecorationWidth(View)
7011         */
7012        public int getDecoratedRight(View child) {
7013            return child.getRight() + getRightDecorationWidth(child);
7014        }
7015
7016        /**
7017         * Returns the bottom edge of the given child view within its parent, offset by any applied
7018         * {@link ItemDecoration ItemDecorations}.
7019         *
7020         * @param child Child to query
7021         * @return Child bottom edge with offsets applied
7022         * @see #getBottomDecorationHeight(View)
7023         */
7024        public int getDecoratedBottom(View child) {
7025            return child.getBottom() + getBottomDecorationHeight(child);
7026        }
7027
7028        /**
7029         * Calculates the item decor insets applied to the given child and updates the provided
7030         * Rect instance with the inset values.
7031         * <ul>
7032         *     <li>The Rect's left is set to the total width of left decorations.</li>
7033         *     <li>The Rect's top is set to the total height of top decorations.</li>
7034         *     <li>The Rect's right is set to the total width of right decorations.</li>
7035         *     <li>The Rect's bottom is set to total height of bottom decorations.</li>
7036         * </ul>
7037         * <p>
7038         * Note that item decorations are automatically calculated when one of the LayoutManager's
7039         * measure child methods is called. If you need to measure the child with custom specs via
7040         * {@link View#measure(int, int)}, you can use this method to get decorations.
7041         *
7042         * @param child The child view whose decorations should be calculated
7043         * @param outRect The Rect to hold result values
7044         */
7045        public void calculateItemDecorationsForChild(View child, Rect outRect) {
7046            if (mRecyclerView == null) {
7047                outRect.set(0, 0, 0, 0);
7048                return;
7049            }
7050            Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
7051            outRect.set(insets);
7052        }
7053
7054        /**
7055         * Returns the total height of item decorations applied to child's top.
7056         * <p>
7057         * Note that this value is not updated until the View is measured or
7058         * {@link #calculateItemDecorationsForChild(View, Rect)} is called.
7059         *
7060         * @param child Child to query
7061         * @return The total height of item decorations applied to the child's top.
7062         * @see #getDecoratedTop(View)
7063         * @see #calculateItemDecorationsForChild(View, Rect)
7064         */
7065        public int getTopDecorationHeight(View child) {
7066            return ((LayoutParams) child.getLayoutParams()).mDecorInsets.top;
7067        }
7068
7069        /**
7070         * Returns the total height of item decorations applied to child's bottom.
7071         * <p>
7072         * Note that this value is not updated until the View is measured or
7073         * {@link #calculateItemDecorationsForChild(View, Rect)} is called.
7074         *
7075         * @param child Child to query
7076         * @return The total height of item decorations applied to the child's bottom.
7077         * @see #getDecoratedBottom(View)
7078         * @see #calculateItemDecorationsForChild(View, Rect)
7079         */
7080        public int getBottomDecorationHeight(View child) {
7081            return ((LayoutParams) child.getLayoutParams()).mDecorInsets.bottom;
7082        }
7083
7084        /**
7085         * Returns the total width of item decorations applied to child's left.
7086         * <p>
7087         * Note that this value is not updated until the View is measured or
7088         * {@link #calculateItemDecorationsForChild(View, Rect)} is called.
7089         *
7090         * @param child Child to query
7091         * @return The total width of item decorations applied to the child's left.
7092         * @see #getDecoratedLeft(View)
7093         * @see #calculateItemDecorationsForChild(View, Rect)
7094         */
7095        public int getLeftDecorationWidth(View child) {
7096            return ((LayoutParams) child.getLayoutParams()).mDecorInsets.left;
7097        }
7098
7099        /**
7100         * Returns the total width of item decorations applied to child's right.
7101         * <p>
7102         * Note that this value is not updated until the View is measured or
7103         * {@link #calculateItemDecorationsForChild(View, Rect)} is called.
7104         *
7105         * @param child Child to query
7106         * @return The total width of item decorations applied to the child's right.
7107         * @see #getDecoratedRight(View)
7108         * @see #calculateItemDecorationsForChild(View, Rect)
7109         */
7110        public int getRightDecorationWidth(View child) {
7111            return ((LayoutParams) child.getLayoutParams()).mDecorInsets.right;
7112        }
7113
7114        /**
7115         * Called when searching for a focusable view in the given direction has failed
7116         * for the current content of the RecyclerView.
7117         *
7118         * <p>This is the LayoutManager's opportunity to populate views in the given direction
7119         * to fulfill the request if it can. The LayoutManager should attach and return
7120         * the view to be focused. The default implementation returns null.</p>
7121         *
7122         * @param focused   The currently focused view
7123         * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
7124         *                  {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
7125         *                  {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
7126         *                  or 0 for not applicable
7127         * @param recycler  The recycler to use for obtaining views for currently offscreen items
7128         * @param state     Transient state of RecyclerView
7129         * @return The chosen view to be focused
7130         */
7131        @Nullable
7132        public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
7133                State state) {
7134            return null;
7135        }
7136
7137        /**
7138         * This method gives a LayoutManager an opportunity to intercept the initial focus search
7139         * before the default behavior of {@link FocusFinder} is used. If this method returns
7140         * null FocusFinder will attempt to find a focusable child view. If it fails
7141         * then {@link #onFocusSearchFailed(View, int, RecyclerView.Recycler, RecyclerView.State)}
7142         * will be called to give the LayoutManager an opportunity to add new views for items
7143         * that did not have attached views representing them. The LayoutManager should not add
7144         * or remove views from this method.
7145         *
7146         * @param focused The currently focused view
7147         * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
7148         *                  {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
7149         *                  {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
7150         * @return A descendant view to focus or null to fall back to default behavior.
7151         *         The default implementation returns null.
7152         */
7153        public View onInterceptFocusSearch(View focused, int direction) {
7154            return null;
7155        }
7156
7157        /**
7158         * Called when a child of the RecyclerView wants a particular rectangle to be positioned
7159         * onto the screen. See {@link ViewParent#requestChildRectangleOnScreen(android.view.View,
7160         * android.graphics.Rect, boolean)} for more details.
7161         *
7162         * <p>The base implementation will attempt to perform a standard programmatic scroll
7163         * to bring the given rect into view, within the padded area of the RecyclerView.</p>
7164         *
7165         * @param child The direct child making the request.
7166         * @param rect  The rectangle in the child's coordinates the child
7167         *              wishes to be on the screen.
7168         * @param immediate True to forbid animated or delayed scrolling,
7169         *                  false otherwise
7170         * @return Whether the group scrolled to handle the operation
7171         */
7172        public boolean requestChildRectangleOnScreen(RecyclerView parent, View child, Rect rect,
7173                boolean immediate) {
7174            final int parentLeft = getPaddingLeft();
7175            final int parentTop = getPaddingTop();
7176            final int parentRight = getWidth() - getPaddingRight();
7177            final int parentBottom = getHeight() - getPaddingBottom();
7178            final int childLeft = child.getLeft() + rect.left;
7179            final int childTop = child.getTop() + rect.top;
7180            final int childRight = childLeft + rect.width();
7181            final int childBottom = childTop + rect.height();
7182
7183            final int offScreenLeft = Math.min(0, childLeft - parentLeft);
7184            final int offScreenTop = Math.min(0, childTop - parentTop);
7185            final int offScreenRight = Math.max(0, childRight - parentRight);
7186            final int offScreenBottom = Math.max(0, childBottom - parentBottom);
7187
7188            // Favor the "start" layout direction over the end when bringing one side or the other
7189            // of a large rect into view. If we decide to bring in end because start is already
7190            // visible, limit the scroll such that start won't go out of bounds.
7191            final int dx;
7192            if (getLayoutDirection() == ViewCompat.LAYOUT_DIRECTION_RTL) {
7193                dx = offScreenRight != 0 ? offScreenRight
7194                        : Math.max(offScreenLeft, childRight - parentRight);
7195            } else {
7196                dx = offScreenLeft != 0 ? offScreenLeft
7197                        : Math.min(childLeft - parentLeft, offScreenRight);
7198            }
7199
7200            // Favor bringing the top into view over the bottom. If top is already visible and
7201            // we should scroll to make bottom visible, make sure top does not go out of bounds.
7202            final int dy = offScreenTop != 0 ? offScreenTop
7203                    : Math.min(childTop - parentTop, offScreenBottom);
7204
7205            if (dx != 0 || dy != 0) {
7206                if (immediate) {
7207                    parent.scrollBy(dx, dy);
7208                } else {
7209                    parent.smoothScrollBy(dx, dy);
7210                }
7211                return true;
7212            }
7213            return false;
7214        }
7215
7216        /**
7217         * @deprecated Use {@link #onRequestChildFocus(RecyclerView, State, View, View)}
7218         */
7219        @Deprecated
7220        public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
7221            // eat the request if we are in the middle of a scroll or layout
7222            return isSmoothScrolling() || parent.isComputingLayout();
7223        }
7224
7225        /**
7226         * Called when a descendant view of the RecyclerView requests focus.
7227         *
7228         * <p>A LayoutManager wishing to keep focused views aligned in a specific
7229         * portion of the view may implement that behavior in an override of this method.</p>
7230         *
7231         * <p>If the LayoutManager executes different behavior that should override the default
7232         * behavior of scrolling the focused child on screen instead of running alongside it,
7233         * this method should return true.</p>
7234         *
7235         * @param parent  The RecyclerView hosting this LayoutManager
7236         * @param state   Current state of RecyclerView
7237         * @param child   Direct child of the RecyclerView containing the newly focused view
7238         * @param focused The newly focused view. This may be the same view as child or it may be
7239         *                null
7240         * @return true if the default scroll behavior should be suppressed
7241         */
7242        public boolean onRequestChildFocus(RecyclerView parent, State state, View child,
7243                View focused) {
7244            return onRequestChildFocus(parent, child, focused);
7245        }
7246
7247        /**
7248         * Called if the RecyclerView this LayoutManager is bound to has a different adapter set.
7249         * The LayoutManager may use this opportunity to clear caches and configure state such
7250         * that it can relayout appropriately with the new data and potentially new view types.
7251         *
7252         * <p>The default implementation removes all currently attached views.</p>
7253         *
7254         * @param oldAdapter The previous adapter instance. Will be null if there was previously no
7255         *                   adapter.
7256         * @param newAdapter The new adapter instance. Might be null if
7257         *                   {@link #setAdapter(RecyclerView.Adapter)} is called with {@code null}.
7258         */
7259        public void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) {
7260        }
7261
7262        /**
7263         * Called to populate focusable views within the RecyclerView.
7264         *
7265         * <p>The LayoutManager implementation should return <code>true</code> if the default
7266         * behavior of {@link ViewGroup#addFocusables(java.util.ArrayList, int)} should be
7267         * suppressed.</p>
7268         *
7269         * <p>The default implementation returns <code>false</code> to trigger RecyclerView
7270         * to fall back to the default ViewGroup behavior.</p>
7271         *
7272         * @param recyclerView The RecyclerView hosting this LayoutManager
7273         * @param views List of output views. This method should add valid focusable views
7274         *              to this list.
7275         * @param direction One of {@link View#FOCUS_UP}, {@link View#FOCUS_DOWN},
7276         *                  {@link View#FOCUS_LEFT}, {@link View#FOCUS_RIGHT},
7277         *                  {@link View#FOCUS_BACKWARD}, {@link View#FOCUS_FORWARD}
7278         * @param focusableMode The type of focusables to be added.
7279         *
7280         * @return true to suppress the default behavior, false to add default focusables after
7281         *         this method returns.
7282         *
7283         * @see #FOCUSABLES_ALL
7284         * @see #FOCUSABLES_TOUCH_MODE
7285         */
7286        public boolean onAddFocusables(RecyclerView recyclerView, ArrayList<View> views,
7287                int direction, int focusableMode) {
7288            return false;
7289        }
7290
7291        /**
7292         * Called when {@link Adapter#notifyDataSetChanged()} is triggered instead of giving
7293         * detailed information on what has actually changed.
7294         *
7295         * @param recyclerView
7296         */
7297        public void onItemsChanged(RecyclerView recyclerView) {
7298        }
7299
7300        /**
7301         * Called when items have been added to the adapter. The LayoutManager may choose to
7302         * requestLayout if the inserted items would require refreshing the currently visible set
7303         * of child views. (e.g. currently empty space would be filled by appended items, etc.)
7304         *
7305         * @param recyclerView
7306         * @param positionStart
7307         * @param itemCount
7308         */
7309        public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
7310        }
7311
7312        /**
7313         * Called when items have been removed from the adapter.
7314         *
7315         * @param recyclerView
7316         * @param positionStart
7317         * @param itemCount
7318         */
7319        public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
7320        }
7321
7322        /**
7323         * Called when items have been changed in the adapter.
7324         * To receive payload,  override {@link #onItemsUpdated(RecyclerView, int, int, Object)}
7325         * instead, then this callback will not be invoked.
7326         *
7327         * @param recyclerView
7328         * @param positionStart
7329         * @param itemCount
7330         */
7331        public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount) {
7332        }
7333
7334        /**
7335         * Called when items have been changed in the adapter and with optional payload.
7336         * Default implementation calls {@link #onItemsUpdated(RecyclerView, int, int)}.
7337         *
7338         * @param recyclerView
7339         * @param positionStart
7340         * @param itemCount
7341         * @param payload
7342         */
7343        public void onItemsUpdated(RecyclerView recyclerView, int positionStart, int itemCount,
7344                Object payload) {
7345            onItemsUpdated(recyclerView, positionStart, itemCount);
7346        }
7347
7348        /**
7349         * Called when an item is moved withing the adapter.
7350         * <p>
7351         * Note that, an item may also change position in response to another ADD/REMOVE/MOVE
7352         * operation. This callback is only called if and only if {@link Adapter#notifyItemMoved}
7353         * is called.
7354         *
7355         * @param recyclerView
7356         * @param from
7357         * @param to
7358         * @param itemCount
7359         */
7360        public void onItemsMoved(RecyclerView recyclerView, int from, int to, int itemCount) {
7361
7362        }
7363
7364
7365        /**
7366         * <p>Override this method if you want to support scroll bars.</p>
7367         *
7368         * <p>Read {@link RecyclerView#computeHorizontalScrollExtent()} for details.</p>
7369         *
7370         * <p>Default implementation returns 0.</p>
7371         *
7372         * @param state Current state of RecyclerView
7373         * @return The horizontal extent of the scrollbar's thumb
7374         * @see RecyclerView#computeHorizontalScrollExtent()
7375         */
7376        public int computeHorizontalScrollExtent(State state) {
7377            return 0;
7378        }
7379
7380        /**
7381         * <p>Override this method if you want to support scroll bars.</p>
7382         *
7383         * <p>Read {@link RecyclerView#computeHorizontalScrollOffset()} for details.</p>
7384         *
7385         * <p>Default implementation returns 0.</p>
7386         *
7387         * @param state Current State of RecyclerView where you can find total item count
7388         * @return The horizontal offset of the scrollbar's thumb
7389         * @see RecyclerView#computeHorizontalScrollOffset()
7390         */
7391        public int computeHorizontalScrollOffset(State state) {
7392            return 0;
7393        }
7394
7395        /**
7396         * <p>Override this method if you want to support scroll bars.</p>
7397         *
7398         * <p>Read {@link RecyclerView#computeHorizontalScrollRange()} for details.</p>
7399         *
7400         * <p>Default implementation returns 0.</p>
7401         *
7402         * @param state Current State of RecyclerView where you can find total item count
7403         * @return The total horizontal range represented by the vertical scrollbar
7404         * @see RecyclerView#computeHorizontalScrollRange()
7405         */
7406        public int computeHorizontalScrollRange(State state) {
7407            return 0;
7408        }
7409
7410        /**
7411         * <p>Override this method if you want to support scroll bars.</p>
7412         *
7413         * <p>Read {@link RecyclerView#computeVerticalScrollExtent()} for details.</p>
7414         *
7415         * <p>Default implementation returns 0.</p>
7416         *
7417         * @param state Current state of RecyclerView
7418         * @return The vertical extent of the scrollbar's thumb
7419         * @see RecyclerView#computeVerticalScrollExtent()
7420         */
7421        public int computeVerticalScrollExtent(State state) {
7422            return 0;
7423        }
7424
7425        /**
7426         * <p>Override this method if you want to support scroll bars.</p>
7427         *
7428         * <p>Read {@link RecyclerView#computeVerticalScrollOffset()} for details.</p>
7429         *
7430         * <p>Default implementation returns 0.</p>
7431         *
7432         * @param state Current State of RecyclerView where you can find total item count
7433         * @return The vertical offset of the scrollbar's thumb
7434         * @see RecyclerView#computeVerticalScrollOffset()
7435         */
7436        public int computeVerticalScrollOffset(State state) {
7437            return 0;
7438        }
7439
7440        /**
7441         * <p>Override this method if you want to support scroll bars.</p>
7442         *
7443         * <p>Read {@link RecyclerView#computeVerticalScrollRange()} for details.</p>
7444         *
7445         * <p>Default implementation returns 0.</p>
7446         *
7447         * @param state Current State of RecyclerView where you can find total item count
7448         * @return The total vertical range represented by the vertical scrollbar
7449         * @see RecyclerView#computeVerticalScrollRange()
7450         */
7451        public int computeVerticalScrollRange(State state) {
7452            return 0;
7453        }
7454
7455        /**
7456         * Measure the attached RecyclerView. Implementations must call
7457         * {@link #setMeasuredDimension(int, int)} before returning.
7458         *
7459         * <p>The default implementation will handle EXACTLY measurements and respect
7460         * the minimum width and height properties of the host RecyclerView if measured
7461         * as UNSPECIFIED. AT_MOST measurements will be treated as EXACTLY and the RecyclerView
7462         * will consume all available space.</p>
7463         *
7464         * @param recycler Recycler
7465         * @param state Transient state of RecyclerView
7466         * @param widthSpec Width {@link android.view.View.MeasureSpec}
7467         * @param heightSpec Height {@link android.view.View.MeasureSpec}
7468         */
7469        public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
7470            mRecyclerView.defaultOnMeasure(widthSpec, heightSpec);
7471        }
7472
7473        /**
7474         * {@link View#setMeasuredDimension(int, int) Set the measured dimensions} of the
7475         * host RecyclerView.
7476         *
7477         * @param widthSize Measured width
7478         * @param heightSize Measured height
7479         */
7480        public void setMeasuredDimension(int widthSize, int heightSize) {
7481            mRecyclerView.setMeasuredDimension(widthSize, heightSize);
7482        }
7483
7484        /**
7485         * @return The host RecyclerView's {@link View#getMinimumWidth()}
7486         */
7487        public int getMinimumWidth() {
7488            return ViewCompat.getMinimumWidth(mRecyclerView);
7489        }
7490
7491        /**
7492         * @return The host RecyclerView's {@link View#getMinimumHeight()}
7493         */
7494        public int getMinimumHeight() {
7495            return ViewCompat.getMinimumHeight(mRecyclerView);
7496        }
7497        /**
7498         * <p>Called when the LayoutManager should save its state. This is a good time to save your
7499         * scroll position, configuration and anything else that may be required to restore the same
7500         * layout state if the LayoutManager is recreated.</p>
7501         * <p>RecyclerView does NOT verify if the LayoutManager has changed between state save and
7502         * restore. This will let you share information between your LayoutManagers but it is also
7503         * your responsibility to make sure they use the same parcelable class.</p>
7504         *
7505         * @return Necessary information for LayoutManager to be able to restore its state
7506         */
7507        public Parcelable onSaveInstanceState() {
7508            return null;
7509        }
7510
7511
7512        public void onRestoreInstanceState(Parcelable state) {
7513
7514        }
7515
7516        void stopSmoothScroller() {
7517            if (mSmoothScroller != null) {
7518                mSmoothScroller.stop();
7519            }
7520        }
7521
7522        private void onSmoothScrollerStopped(SmoothScroller smoothScroller) {
7523            if (mSmoothScroller == smoothScroller) {
7524                mSmoothScroller = null;
7525            }
7526        }
7527
7528        /**
7529         * RecyclerView calls this method to notify LayoutManager that scroll state has changed.
7530         *
7531         * @param state The new scroll state for RecyclerView
7532         */
7533        public void onScrollStateChanged(int state) {
7534        }
7535
7536        /**
7537         * Removes all views and recycles them using the given recycler.
7538         * <p>
7539         * If you want to clean cached views as well, you should call {@link Recycler#clear()} too.
7540         * <p>
7541         * If a View is marked as "ignored", it is not removed nor recycled.
7542         *
7543         * @param recycler Recycler to use to recycle children
7544         * @see #removeAndRecycleView(View, Recycler)
7545         * @see #removeAndRecycleViewAt(int, Recycler)
7546         * @see #ignoreView(View)
7547         */
7548        public void removeAndRecycleAllViews(Recycler recycler) {
7549            for (int i = getChildCount() - 1; i >= 0; i--) {
7550                final View view = getChildAt(i);
7551                if (!getChildViewHolderInt(view).shouldIgnore()) {
7552                    removeAndRecycleViewAt(i, recycler);
7553                }
7554            }
7555        }
7556
7557        // called by accessibility delegate
7558        void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfoCompat info) {
7559            onInitializeAccessibilityNodeInfo(mRecyclerView.mRecycler, mRecyclerView.mState, info);
7560        }
7561
7562        /**
7563         * Called by the AccessibilityDelegate when the information about the current layout should
7564         * be populated.
7565         * <p>
7566         * Default implementation adds a {@link
7567         * android.support.v4.view.accessibility.AccessibilityNodeInfoCompat.CollectionInfoCompat}.
7568         * <p>
7569         * You should override
7570         * {@link #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
7571         * {@link #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)},
7572         * {@link #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)} and
7573         * {@link #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)} for
7574         * more accurate accessibility information.
7575         *
7576         * @param recycler The Recycler that can be used to convert view positions into adapter
7577         *                 positions
7578         * @param state    The current state of RecyclerView
7579         * @param info     The info that should be filled by the LayoutManager
7580         * @see View#onInitializeAccessibilityNodeInfo(
7581         *android.view.accessibility.AccessibilityNodeInfo)
7582         * @see #getRowCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
7583         * @see #getColumnCountForAccessibility(RecyclerView.Recycler, RecyclerView.State)
7584         * @see #isLayoutHierarchical(RecyclerView.Recycler, RecyclerView.State)
7585         * @see #getSelectionModeForAccessibility(RecyclerView.Recycler, RecyclerView.State)
7586         */
7587        public void onInitializeAccessibilityNodeInfo(Recycler recycler, State state,
7588                AccessibilityNodeInfoCompat info) {
7589            if (ViewCompat.canScrollVertically(mRecyclerView, -1) ||
7590                    ViewCompat.canScrollHorizontally(mRecyclerView, -1)) {
7591                info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD);
7592                info.setScrollable(true);
7593            }
7594            if (ViewCompat.canScrollVertically(mRecyclerView, 1) ||
7595                    ViewCompat.canScrollHorizontally(mRecyclerView, 1)) {
7596                info.addAction(AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD);
7597                info.setScrollable(true);
7598            }
7599            final AccessibilityNodeInfoCompat.CollectionInfoCompat collectionInfo
7600                    = AccessibilityNodeInfoCompat.CollectionInfoCompat
7601                    .obtain(getRowCountForAccessibility(recycler, state),
7602                            getColumnCountForAccessibility(recycler, state),
7603                            isLayoutHierarchical(recycler, state),
7604                            getSelectionModeForAccessibility(recycler, state));
7605            info.setCollectionInfo(collectionInfo);
7606        }
7607
7608        // called by accessibility delegate
7609        public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
7610            onInitializeAccessibilityEvent(mRecyclerView.mRecycler, mRecyclerView.mState, event);
7611        }
7612
7613        /**
7614         * Called by the accessibility delegate to initialize an accessibility event.
7615         * <p>
7616         * Default implementation adds item count and scroll information to the event.
7617         *
7618         * @param recycler The Recycler that can be used to convert view positions into adapter
7619         *                 positions
7620         * @param state    The current state of RecyclerView
7621         * @param event    The event instance to initialize
7622         * @see View#onInitializeAccessibilityEvent(android.view.accessibility.AccessibilityEvent)
7623         */
7624        public void onInitializeAccessibilityEvent(Recycler recycler, State state,
7625                AccessibilityEvent event) {
7626            final AccessibilityRecordCompat record = AccessibilityEventCompat
7627                    .asRecord(event);
7628            if (mRecyclerView == null || record == null) {
7629                return;
7630            }
7631            record.setScrollable(ViewCompat.canScrollVertically(mRecyclerView, 1)
7632                    || ViewCompat.canScrollVertically(mRecyclerView, -1)
7633                    || ViewCompat.canScrollHorizontally(mRecyclerView, -1)
7634                    || ViewCompat.canScrollHorizontally(mRecyclerView, 1));
7635
7636            if (mRecyclerView.mAdapter != null) {
7637                record.setItemCount(mRecyclerView.mAdapter.getItemCount());
7638            }
7639        }
7640
7641        // called by accessibility delegate
7642        void onInitializeAccessibilityNodeInfoForItem(View host, AccessibilityNodeInfoCompat info) {
7643            final ViewHolder vh = getChildViewHolderInt(host);
7644            // avoid trying to create accessibility node info for removed children
7645            if (vh != null && !vh.isRemoved() && !mChildHelper.isHidden(vh.itemView)) {
7646                onInitializeAccessibilityNodeInfoForItem(mRecyclerView.mRecycler,
7647                        mRecyclerView.mState, host, info);
7648            }
7649        }
7650
7651        /**
7652         * Called by the AccessibilityDelegate when the accessibility information for a specific
7653         * item should be populated.
7654         * <p>
7655         * Default implementation adds basic positioning information about the item.
7656         *
7657         * @param recycler The Recycler that can be used to convert view positions into adapter
7658         *                 positions
7659         * @param state    The current state of RecyclerView
7660         * @param host     The child for which accessibility node info should be populated
7661         * @param info     The info to fill out about the item
7662         * @see android.widget.AbsListView#onInitializeAccessibilityNodeInfoForItem(View, int,
7663         * android.view.accessibility.AccessibilityNodeInfo)
7664         */
7665        public void onInitializeAccessibilityNodeInfoForItem(Recycler recycler, State state,
7666                View host, AccessibilityNodeInfoCompat info) {
7667            int rowIndexGuess = canScrollVertically() ? getPosition(host) : 0;
7668            int columnIndexGuess = canScrollHorizontally() ? getPosition(host) : 0;
7669            final AccessibilityNodeInfoCompat.CollectionItemInfoCompat itemInfo
7670                    = AccessibilityNodeInfoCompat.CollectionItemInfoCompat.obtain(rowIndexGuess, 1,
7671                    columnIndexGuess, 1, false, false);
7672            info.setCollectionItemInfo(itemInfo);
7673        }
7674
7675        /**
7676         * A LayoutManager can call this method to force RecyclerView to run simple animations in
7677         * the next layout pass, even if there is not any trigger to do so. (e.g. adapter data
7678         * change).
7679         * <p>
7680         * Note that, calling this method will not guarantee that RecyclerView will run animations
7681         * at all. For example, if there is not any {@link ItemAnimator} set, RecyclerView will
7682         * not run any animations but will still clear this flag after the layout is complete.
7683         *
7684         */
7685        public void requestSimpleAnimationsInNextLayout() {
7686            mRequestedSimpleAnimations = true;
7687        }
7688
7689        /**
7690         * Returns the selection mode for accessibility. Should be
7691         * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE},
7692         * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_SINGLE} or
7693         * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_MULTIPLE}.
7694         * <p>
7695         * Default implementation returns
7696         * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
7697         *
7698         * @param recycler The Recycler that can be used to convert view positions into adapter
7699         *                 positions
7700         * @param state    The current state of RecyclerView
7701         * @return Selection mode for accessibility. Default implementation returns
7702         * {@link AccessibilityNodeInfoCompat.CollectionInfoCompat#SELECTION_MODE_NONE}.
7703         */
7704        public int getSelectionModeForAccessibility(Recycler recycler, State state) {
7705            return AccessibilityNodeInfoCompat.CollectionInfoCompat.SELECTION_MODE_NONE;
7706        }
7707
7708        /**
7709         * Returns the number of rows for accessibility.
7710         * <p>
7711         * Default implementation returns the number of items in the adapter if LayoutManager
7712         * supports vertical scrolling or 1 if LayoutManager does not support vertical
7713         * scrolling.
7714         *
7715         * @param recycler The Recycler that can be used to convert view positions into adapter
7716         *                 positions
7717         * @param state    The current state of RecyclerView
7718         * @return The number of rows in LayoutManager for accessibility.
7719         */
7720        public int getRowCountForAccessibility(Recycler recycler, State state) {
7721            if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
7722                return 1;
7723            }
7724            return canScrollVertically() ? mRecyclerView.mAdapter.getItemCount() : 1;
7725        }
7726
7727        /**
7728         * Returns the number of columns for accessibility.
7729         * <p>
7730         * Default implementation returns the number of items in the adapter if LayoutManager
7731         * supports horizontal scrolling or 1 if LayoutManager does not support horizontal
7732         * scrolling.
7733         *
7734         * @param recycler The Recycler that can be used to convert view positions into adapter
7735         *                 positions
7736         * @param state    The current state of RecyclerView
7737         * @return The number of rows in LayoutManager for accessibility.
7738         */
7739        public int getColumnCountForAccessibility(Recycler recycler, State state) {
7740            if (mRecyclerView == null || mRecyclerView.mAdapter == null) {
7741                return 1;
7742            }
7743            return canScrollHorizontally() ? mRecyclerView.mAdapter.getItemCount() : 1;
7744        }
7745
7746        /**
7747         * Returns whether layout is hierarchical or not to be used for accessibility.
7748         * <p>
7749         * Default implementation returns false.
7750         *
7751         * @param recycler The Recycler that can be used to convert view positions into adapter
7752         *                 positions
7753         * @param state    The current state of RecyclerView
7754         * @return True if layout is hierarchical.
7755         */
7756        public boolean isLayoutHierarchical(Recycler recycler, State state) {
7757            return false;
7758        }
7759
7760        // called by accessibility delegate
7761        boolean performAccessibilityAction(int action, Bundle args) {
7762            return performAccessibilityAction(mRecyclerView.mRecycler, mRecyclerView.mState,
7763                    action, args);
7764        }
7765
7766        /**
7767         * Called by AccessibilityDelegate when an action is requested from the RecyclerView.
7768         *
7769         * @param recycler  The Recycler that can be used to convert view positions into adapter
7770         *                  positions
7771         * @param state     The current state of RecyclerView
7772         * @param action    The action to perform
7773         * @param args      Optional action arguments
7774         * @see View#performAccessibilityAction(int, android.os.Bundle)
7775         */
7776        public boolean performAccessibilityAction(Recycler recycler, State state, int action,
7777                Bundle args) {
7778            if (mRecyclerView == null) {
7779                return false;
7780            }
7781            int vScroll = 0, hScroll = 0;
7782            switch (action) {
7783                case AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD:
7784                    if (ViewCompat.canScrollVertically(mRecyclerView, -1)) {
7785                        vScroll = -(getHeight() - getPaddingTop() - getPaddingBottom());
7786                    }
7787                    if (ViewCompat.canScrollHorizontally(mRecyclerView, -1)) {
7788                        hScroll = -(getWidth() - getPaddingLeft() - getPaddingRight());
7789                    }
7790                    break;
7791                case AccessibilityNodeInfoCompat.ACTION_SCROLL_FORWARD:
7792                    if (ViewCompat.canScrollVertically(mRecyclerView, 1)) {
7793                        vScroll = getHeight() - getPaddingTop() - getPaddingBottom();
7794                    }
7795                    if (ViewCompat.canScrollHorizontally(mRecyclerView, 1)) {
7796                        hScroll = getWidth() - getPaddingLeft() - getPaddingRight();
7797                    }
7798                    break;
7799            }
7800            if (vScroll == 0 && hScroll == 0) {
7801                return false;
7802            }
7803            mRecyclerView.scrollBy(hScroll, vScroll);
7804            return true;
7805        }
7806
7807        // called by accessibility delegate
7808        boolean performAccessibilityActionForItem(View view, int action, Bundle args) {
7809            return performAccessibilityActionForItem(mRecyclerView.mRecycler, mRecyclerView.mState,
7810                    view, action, args);
7811        }
7812
7813        /**
7814         * Called by AccessibilityDelegate when an accessibility action is requested on one of the
7815         * children of LayoutManager.
7816         * <p>
7817         * Default implementation does not do anything.
7818         *
7819         * @param recycler The Recycler that can be used to convert view positions into adapter
7820         *                 positions
7821         * @param state    The current state of RecyclerView
7822         * @param view     The child view on which the action is performed
7823         * @param action   The action to perform
7824         * @param args     Optional action arguments
7825         * @return true if action is handled
7826         * @see View#performAccessibilityAction(int, android.os.Bundle)
7827         */
7828        public boolean performAccessibilityActionForItem(Recycler recycler, State state, View view,
7829                int action, Bundle args) {
7830            return false;
7831        }
7832
7833        /**
7834         * Parse the xml attributes to get the most common properties used by layout managers.
7835         *
7836         * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_android_orientation
7837         * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_spanCount
7838         * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_reverseLayout
7839         * @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_stackFromEnd
7840         *
7841         * @return an object containing the properties as specified in the attrs.
7842         */
7843        public static Properties getProperties(Context context, AttributeSet attrs,
7844                int defStyleAttr, int defStyleRes) {
7845            Properties properties = new Properties();
7846            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView,
7847                    defStyleAttr, defStyleRes);
7848            properties.orientation = a.getInt(R.styleable.RecyclerView_android_orientation, VERTICAL);
7849            properties.spanCount = a.getInt(R.styleable.RecyclerView_spanCount, 1);
7850            properties.reverseLayout = a.getBoolean(R.styleable.RecyclerView_reverseLayout, false);
7851            properties.stackFromEnd = a.getBoolean(R.styleable.RecyclerView_stackFromEnd, false);
7852            a.recycle();
7853            return properties;
7854        }
7855
7856        /**
7857         * Some general properties that a LayoutManager may want to use.
7858         */
7859        public static class Properties {
7860            /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_android_orientation */
7861            public int orientation;
7862            /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_spanCount */
7863            public int spanCount;
7864            /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_reverseLayout */
7865            public boolean reverseLayout;
7866            /** @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_stackFromEnd */
7867            public boolean stackFromEnd;
7868        }
7869    }
7870
7871    /**
7872     * An ItemDecoration allows the application to add a special drawing and layout offset
7873     * to specific item views from the adapter's data set. This can be useful for drawing dividers
7874     * between items, highlights, visual grouping boundaries and more.
7875     *
7876     * <p>All ItemDecorations are drawn in the order they were added, before the item
7877     * views (in {@link ItemDecoration#onDraw(Canvas, RecyclerView, RecyclerView.State) onDraw()}
7878     * and after the items (in {@link ItemDecoration#onDrawOver(Canvas, RecyclerView,
7879     * RecyclerView.State)}.</p>
7880     */
7881    public static abstract class ItemDecoration {
7882        /**
7883         * Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
7884         * Any content drawn by this method will be drawn before the item views are drawn,
7885         * and will thus appear underneath the views.
7886         *
7887         * @param c Canvas to draw into
7888         * @param parent RecyclerView this ItemDecoration is drawing into
7889         * @param state The current state of RecyclerView
7890         */
7891        public void onDraw(Canvas c, RecyclerView parent, State state) {
7892            onDraw(c, parent);
7893        }
7894
7895        /**
7896         * @deprecated
7897         * Override {@link #onDraw(Canvas, RecyclerView, RecyclerView.State)}
7898         */
7899        @Deprecated
7900        public void onDraw(Canvas c, RecyclerView parent) {
7901        }
7902
7903        /**
7904         * Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
7905         * Any content drawn by this method will be drawn after the item views are drawn
7906         * and will thus appear over the views.
7907         *
7908         * @param c Canvas to draw into
7909         * @param parent RecyclerView this ItemDecoration is drawing into
7910         * @param state The current state of RecyclerView.
7911         */
7912        public void onDrawOver(Canvas c, RecyclerView parent, State state) {
7913            onDrawOver(c, parent);
7914        }
7915
7916        /**
7917         * @deprecated
7918         * Override {@link #onDrawOver(Canvas, RecyclerView, RecyclerView.State)}
7919         */
7920        @Deprecated
7921        public void onDrawOver(Canvas c, RecyclerView parent) {
7922        }
7923
7924
7925        /**
7926         * @deprecated
7927         * Use {@link #getItemOffsets(Rect, View, RecyclerView, State)}
7928         */
7929        @Deprecated
7930        public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
7931            outRect.set(0, 0, 0, 0);
7932        }
7933
7934        /**
7935         * Retrieve any offsets for the given item. Each field of <code>outRect</code> specifies
7936         * the number of pixels that the item view should be inset by, similar to padding or margin.
7937         * The default implementation sets the bounds of outRect to 0 and returns.
7938         *
7939         * <p>
7940         * If this ItemDecoration does not affect the positioning of item views, it should set
7941         * all four fields of <code>outRect</code> (left, top, right, bottom) to zero
7942         * before returning.
7943         *
7944         * <p>
7945         * If you need to access Adapter for additional data, you can call
7946         * {@link RecyclerView#getChildAdapterPosition(View)} to get the adapter position of the
7947         * View.
7948         *
7949         * @param outRect Rect to receive the output.
7950         * @param view    The child view to decorate
7951         * @param parent  RecyclerView this ItemDecoration is decorating
7952         * @param state   The current state of RecyclerView.
7953         */
7954        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, State state) {
7955            getItemOffsets(outRect, ((LayoutParams) view.getLayoutParams()).getViewLayoutPosition(),
7956                    parent);
7957        }
7958    }
7959
7960    /**
7961     * An OnItemTouchListener allows the application to intercept touch events in progress at the
7962     * view hierarchy level of the RecyclerView before those touch events are considered for
7963     * RecyclerView's own scrolling behavior.
7964     *
7965     * <p>This can be useful for applications that wish to implement various forms of gestural
7966     * manipulation of item views within the RecyclerView. OnItemTouchListeners may intercept
7967     * a touch interaction already in progress even if the RecyclerView is already handling that
7968     * gesture stream itself for the purposes of scrolling.</p>
7969     *
7970     * @see SimpleOnItemTouchListener
7971     */
7972    public static interface OnItemTouchListener {
7973        /**
7974         * Silently observe and/or take over touch events sent to the RecyclerView
7975         * before they are handled by either the RecyclerView itself or its child views.
7976         *
7977         * <p>The onInterceptTouchEvent methods of each attached OnItemTouchListener will be run
7978         * in the order in which each listener was added, before any other touch processing
7979         * by the RecyclerView itself or child views occurs.</p>
7980         *
7981         * @param e MotionEvent describing the touch event. All coordinates are in
7982         *          the RecyclerView's coordinate system.
7983         * @return true if this OnItemTouchListener wishes to begin intercepting touch events, false
7984         *         to continue with the current behavior and continue observing future events in
7985         *         the gesture.
7986         */
7987        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e);
7988
7989        /**
7990         * Process a touch event as part of a gesture that was claimed by returning true from
7991         * a previous call to {@link #onInterceptTouchEvent}.
7992         *
7993         * @param e MotionEvent describing the touch event. All coordinates are in
7994         *          the RecyclerView's coordinate system.
7995         */
7996        public void onTouchEvent(RecyclerView rv, MotionEvent e);
7997
7998        /**
7999         * Called when a child of RecyclerView does not want RecyclerView and its ancestors to
8000         * intercept touch events with
8001         * {@link ViewGroup#onInterceptTouchEvent(MotionEvent)}.
8002         *
8003         * @param disallowIntercept True if the child does not want the parent to
8004         *            intercept touch events.
8005         * @see ViewParent#requestDisallowInterceptTouchEvent(boolean)
8006         */
8007        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept);
8008    }
8009
8010    /**
8011     * An implementation of {@link RecyclerView.OnItemTouchListener} that has empty method bodies and
8012     * default return values.
8013     * <p>
8014     * You may prefer to extend this class if you don't need to override all methods. Another
8015     * benefit of using this class is future compatibility. As the interface may change, we'll
8016     * always provide a default implementation on this class so that your code won't break when
8017     * you update to a new version of the support library.
8018     */
8019    public static class SimpleOnItemTouchListener implements RecyclerView.OnItemTouchListener {
8020        @Override
8021        public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
8022            return false;
8023        }
8024
8025        @Override
8026        public void onTouchEvent(RecyclerView rv, MotionEvent e) {
8027        }
8028
8029        @Override
8030        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
8031        }
8032    }
8033
8034
8035    /**
8036     * An OnScrollListener can be set on a RecyclerView to receive messages
8037     * when a scrolling event has occurred on that RecyclerView.
8038     *
8039     * @see RecyclerView#setOnScrollListener(OnScrollListener) and
8040     * RecyclerView#addOnScrollListener(OnScrollListener)
8041     *
8042     * If you are planning to have several listeners at the same time, use
8043     * RecyclerView#addOnScrollListener. If there will be only one listener at the time and you
8044     * want your components to be able to easily replace the listener use
8045     * RecyclerView#setOnScrollListener.
8046     */
8047    public abstract static class OnScrollListener {
8048        /**
8049         * Callback method to be invoked when RecyclerView's scroll state changes.
8050         *
8051         * @param recyclerView The RecyclerView whose scroll state has changed.
8052         * @param newState     The updated scroll state. One of {@link #SCROLL_STATE_IDLE},
8053         *                     {@link #SCROLL_STATE_DRAGGING} or {@link #SCROLL_STATE_SETTLING}.
8054         */
8055        public void onScrollStateChanged(RecyclerView recyclerView, int newState){}
8056
8057        /**
8058         * Callback method to be invoked when the RecyclerView has been scrolled. This will be
8059         * called after the scroll has completed.
8060         * <p>
8061         * This callback will also be called if visible item range changes after a layout
8062         * calculation. In that case, dx and dy will be 0.
8063         *
8064         * @param recyclerView The RecyclerView which scrolled.
8065         * @param dx The amount of horizontal scroll.
8066         * @param dy The amount of vertical scroll.
8067         */
8068        public void onScrolled(RecyclerView recyclerView, int dx, int dy){}
8069    }
8070
8071    /**
8072     * A RecyclerListener can be set on a RecyclerView to receive messages whenever
8073     * a view is recycled.
8074     *
8075     * @see RecyclerView#setRecyclerListener(RecyclerListener)
8076     */
8077    public interface RecyclerListener {
8078
8079        /**
8080         * This method is called whenever the view in the ViewHolder is recycled.
8081         *
8082         * RecyclerView calls this method right before clearing ViewHolder's internal data and
8083         * sending it to RecycledViewPool. This way, if ViewHolder was holding valid information
8084         * before being recycled, you can call {@link ViewHolder#getAdapterPosition()} to get
8085         * its adapter position.
8086         *
8087         * @param holder The ViewHolder containing the view that was recycled
8088         */
8089        public void onViewRecycled(ViewHolder holder);
8090    }
8091
8092    /**
8093     * A Listener interface that can be attached to a RecylcerView to get notified
8094     * whenever a ViewHolder is attached to or detached from RecyclerView.
8095     */
8096    public interface OnChildAttachStateChangeListener {
8097
8098        /**
8099         * Called when a view is attached to the RecyclerView.
8100         *
8101         * @param view The View which is attached to the RecyclerView
8102         */
8103        public void onChildViewAttachedToWindow(View view);
8104
8105        /**
8106         * Called when a view is detached from RecyclerView.
8107         *
8108         * @param view The View which is being detached from the RecyclerView
8109         */
8110        public void onChildViewDetachedFromWindow(View view);
8111    }
8112
8113    /**
8114     * A ViewHolder describes an item view and metadata about its place within the RecyclerView.
8115     *
8116     * <p>{@link Adapter} implementations should subclass ViewHolder and add fields for caching
8117     * potentially expensive {@link View#findViewById(int)} results.</p>
8118     *
8119     * <p>While {@link LayoutParams} belong to the {@link LayoutManager},
8120     * {@link ViewHolder ViewHolders} belong to the adapter. Adapters should feel free to use
8121     * their own custom ViewHolder implementations to store data that makes binding view contents
8122     * easier. Implementations should assume that individual item views will hold strong references
8123     * to <code>ViewHolder</code> objects and that <code>RecyclerView</code> instances may hold
8124     * strong references to extra off-screen item views for caching purposes</p>
8125     */
8126    public static abstract class ViewHolder {
8127        public final View itemView;
8128        int mPosition = NO_POSITION;
8129        int mOldPosition = NO_POSITION;
8130        long mItemId = NO_ID;
8131        int mItemViewType = INVALID_TYPE;
8132        int mPreLayoutPosition = NO_POSITION;
8133
8134        // The item that this holder is shadowing during an item change event/animation
8135        ViewHolder mShadowedHolder = null;
8136        // The item that is shadowing this holder during an item change event/animation
8137        ViewHolder mShadowingHolder = null;
8138
8139        /**
8140         * This ViewHolder has been bound to a position; mPosition, mItemId and mItemViewType
8141         * are all valid.
8142         */
8143        static final int FLAG_BOUND = 1 << 0;
8144
8145        /**
8146         * The data this ViewHolder's view reflects is stale and needs to be rebound
8147         * by the adapter. mPosition and mItemId are consistent.
8148         */
8149        static final int FLAG_UPDATE = 1 << 1;
8150
8151        /**
8152         * This ViewHolder's data is invalid. The identity implied by mPosition and mItemId
8153         * are not to be trusted and may no longer match the item view type.
8154         * This ViewHolder must be fully rebound to different data.
8155         */
8156        static final int FLAG_INVALID = 1 << 2;
8157
8158        /**
8159         * This ViewHolder points at data that represents an item previously removed from the
8160         * data set. Its view may still be used for things like outgoing animations.
8161         */
8162        static final int FLAG_REMOVED = 1 << 3;
8163
8164        /**
8165         * This ViewHolder should not be recycled. This flag is set via setIsRecyclable()
8166         * and is intended to keep views around during animations.
8167         */
8168        static final int FLAG_NOT_RECYCLABLE = 1 << 4;
8169
8170        /**
8171         * This ViewHolder is returned from scrap which means we are expecting an addView call
8172         * for this itemView. When returned from scrap, ViewHolder stays in the scrap list until
8173         * the end of the layout pass and then recycled by RecyclerView if it is not added back to
8174         * the RecyclerView.
8175         */
8176        static final int FLAG_RETURNED_FROM_SCRAP = 1 << 5;
8177
8178        /**
8179         * This ViewHolder is fully managed by the LayoutManager. We do not scrap, recycle or remove
8180         * it unless LayoutManager is replaced.
8181         * It is still fully visible to the LayoutManager.
8182         */
8183        static final int FLAG_IGNORE = 1 << 7;
8184
8185        /**
8186         * When the View is detached form the parent, we set this flag so that we can take correct
8187         * action when we need to remove it or add it back.
8188         */
8189        static final int FLAG_TMP_DETACHED = 1 << 8;
8190
8191        /**
8192         * Set when we can no longer determine the adapter position of this ViewHolder until it is
8193         * rebound to a new position. It is different than FLAG_INVALID because FLAG_INVALID is
8194         * set even when the type does not match. Also, FLAG_ADAPTER_POSITION_UNKNOWN is set as soon
8195         * as adapter notification arrives vs FLAG_INVALID is set lazily before layout is
8196         * re-calculated.
8197         */
8198        static final int FLAG_ADAPTER_POSITION_UNKNOWN = 1 << 9;
8199
8200        /**
8201         * Set when a addChangePayload(null) is called
8202         */
8203        static final int FLAG_ADAPTER_FULLUPDATE = 1 << 10;
8204
8205        /**
8206         * Used by ItemAnimator when a ViewHolder's position changes
8207         */
8208        static final int FLAG_MOVED = 1 << 11;
8209
8210        /**
8211         * Used by ItemAnimator when a ViewHolder appears in pre-layout
8212         */
8213        static final int FLAG_APPEARED_IN_PRE_LAYOUT = 1 << 12;
8214
8215        /**
8216         * Used when a ViewHolder starts the layout pass as a hidden ViewHolder but is re-used from
8217         * hidden list (as if it was scrap) without being recycled in between.
8218         *
8219         * When a ViewHolder is hidden, there are 2 paths it can be re-used:
8220         *   a) Animation ends, view is recycled and used from the recycle pool.
8221         *   b) LayoutManager asks for the View for that position while the ViewHolder is hidden.
8222         *
8223         * This flag is used to represent "case b" where the ViewHolder is reused without being
8224         * recycled (thus "bounced" from the hidden list). This state requires special handling
8225         * because the ViewHolder must be added to pre layout maps for animations as if it was
8226         * already there.
8227         */
8228        static final int FLAG_BOUNCED_FROM_HIDDEN_LIST = 1 << 13;
8229
8230        private int mFlags;
8231
8232        private static final List<Object> FULLUPDATE_PAYLOADS = Collections.EMPTY_LIST;
8233
8234        List<Object> mPayloads = null;
8235        List<Object> mUnmodifiedPayloads = null;
8236
8237        private int mIsRecyclableCount = 0;
8238
8239        // If non-null, view is currently considered scrap and may be reused for other data by the
8240        // scrap container.
8241        private Recycler mScrapContainer = null;
8242        // Keeps whether this ViewHolder lives in Change scrap or Attached scrap
8243        private boolean mInChangeScrap = false;
8244
8245        // Saves isImportantForAccessibility value for the view item while it's in hidden state and
8246        // marked as unimportant for accessibility.
8247        private int mWasImportantForAccessibilityBeforeHidden =
8248                ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8249
8250        /**
8251         * Is set when VH is bound from the adapter and cleaned right before it is sent to
8252         * {@link RecycledViewPool}.
8253         */
8254        RecyclerView mOwnerRecyclerView;
8255
8256        public ViewHolder(View itemView) {
8257            if (itemView == null) {
8258                throw new IllegalArgumentException("itemView may not be null");
8259            }
8260            this.itemView = itemView;
8261        }
8262
8263        void flagRemovedAndOffsetPosition(int mNewPosition, int offset, boolean applyToPreLayout) {
8264            addFlags(ViewHolder.FLAG_REMOVED);
8265            offsetPosition(offset, applyToPreLayout);
8266            mPosition = mNewPosition;
8267        }
8268
8269        void offsetPosition(int offset, boolean applyToPreLayout) {
8270            if (mOldPosition == NO_POSITION) {
8271                mOldPosition = mPosition;
8272            }
8273            if (mPreLayoutPosition == NO_POSITION) {
8274                mPreLayoutPosition = mPosition;
8275            }
8276            if (applyToPreLayout) {
8277                mPreLayoutPosition += offset;
8278            }
8279            mPosition += offset;
8280            if (itemView.getLayoutParams() != null) {
8281                ((LayoutParams) itemView.getLayoutParams()).mInsetsDirty = true;
8282            }
8283        }
8284
8285        void clearOldPosition() {
8286            mOldPosition = NO_POSITION;
8287            mPreLayoutPosition = NO_POSITION;
8288        }
8289
8290        void saveOldPosition() {
8291            if (mOldPosition == NO_POSITION) {
8292                mOldPosition = mPosition;
8293            }
8294        }
8295
8296        boolean shouldIgnore() {
8297            return (mFlags & FLAG_IGNORE) != 0;
8298        }
8299
8300        /**
8301         * @deprecated This method is deprecated because its meaning is ambiguous due to the async
8302         * handling of adapter updates. Please use {@link #getLayoutPosition()} or
8303         * {@link #getAdapterPosition()} depending on your use case.
8304         *
8305         * @see #getLayoutPosition()
8306         * @see #getAdapterPosition()
8307         */
8308        @Deprecated
8309        public final int getPosition() {
8310            return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
8311        }
8312
8313        /**
8314         * Returns the position of the ViewHolder in terms of the latest layout pass.
8315         * <p>
8316         * This position is mostly used by RecyclerView components to be consistent while
8317         * RecyclerView lazily processes adapter updates.
8318         * <p>
8319         * For performance and animation reasons, RecyclerView batches all adapter updates until the
8320         * next layout pass. This may cause mismatches between the Adapter position of the item and
8321         * the position it had in the latest layout calculations.
8322         * <p>
8323         * LayoutManagers should always call this method while doing calculations based on item
8324         * positions. All methods in {@link RecyclerView.LayoutManager}, {@link RecyclerView.State},
8325         * {@link RecyclerView.Recycler} that receive a position expect it to be the layout position
8326         * of the item.
8327         * <p>
8328         * If LayoutManager needs to call an external method that requires the adapter position of
8329         * the item, it can use {@link #getAdapterPosition()} or
8330         * {@link RecyclerView.Recycler#convertPreLayoutPositionToPostLayout(int)}.
8331         *
8332         * @return Returns the adapter position of the ViewHolder in the latest layout pass.
8333         * @see #getAdapterPosition()
8334         */
8335        public final int getLayoutPosition() {
8336            return mPreLayoutPosition == NO_POSITION ? mPosition : mPreLayoutPosition;
8337        }
8338
8339        /**
8340         * Returns the Adapter position of the item represented by this ViewHolder.
8341         * <p>
8342         * Note that this might be different than the {@link #getLayoutPosition()} if there are
8343         * pending adapter updates but a new layout pass has not happened yet.
8344         * <p>
8345         * RecyclerView does not handle any adapter updates until the next layout traversal. This
8346         * may create temporary inconsistencies between what user sees on the screen and what
8347         * adapter contents have. This inconsistency is not important since it will be less than
8348         * 16ms but it might be a problem if you want to use ViewHolder position to access the
8349         * adapter. Sometimes, you may need to get the exact adapter position to do
8350         * some actions in response to user events. In that case, you should use this method which
8351         * will calculate the Adapter position of the ViewHolder.
8352         * <p>
8353         * Note that if you've called {@link RecyclerView.Adapter#notifyDataSetChanged()}, until the
8354         * next layout pass, the return value of this method will be {@link #NO_POSITION}.
8355         *
8356         * @return The adapter position of the item if it still exists in the adapter.
8357         * {@link RecyclerView#NO_POSITION} if item has been removed from the adapter,
8358         * {@link RecyclerView.Adapter#notifyDataSetChanged()} has been called after the last
8359         * layout pass or the ViewHolder has already been recycled.
8360         */
8361        public final int getAdapterPosition() {
8362            if (mOwnerRecyclerView == null) {
8363                return NO_POSITION;
8364            }
8365            return mOwnerRecyclerView.getAdapterPositionFor(this);
8366        }
8367
8368        /**
8369         * When LayoutManager supports animations, RecyclerView tracks 3 positions for ViewHolders
8370         * to perform animations.
8371         * <p>
8372         * If a ViewHolder was laid out in the previous onLayout call, old position will keep its
8373         * adapter index in the previous layout.
8374         *
8375         * @return The previous adapter index of the Item represented by this ViewHolder or
8376         * {@link #NO_POSITION} if old position does not exists or cleared (pre-layout is
8377         * complete).
8378         */
8379        public final int getOldPosition() {
8380            return mOldPosition;
8381        }
8382
8383        /**
8384         * Returns The itemId represented by this ViewHolder.
8385         *
8386         * @return The the item's id if adapter has stable ids, {@link RecyclerView#NO_ID}
8387         * otherwise
8388         */
8389        public final long getItemId() {
8390            return mItemId;
8391        }
8392
8393        /**
8394         * @return The view type of this ViewHolder.
8395         */
8396        public final int getItemViewType() {
8397            return mItemViewType;
8398        }
8399
8400        boolean isScrap() {
8401            return mScrapContainer != null;
8402        }
8403
8404        void unScrap() {
8405            mScrapContainer.unscrapView(this);
8406        }
8407
8408        boolean wasReturnedFromScrap() {
8409            return (mFlags & FLAG_RETURNED_FROM_SCRAP) != 0;
8410        }
8411
8412        void clearReturnedFromScrapFlag() {
8413            mFlags = mFlags & ~FLAG_RETURNED_FROM_SCRAP;
8414        }
8415
8416        void clearTmpDetachFlag() {
8417            mFlags = mFlags & ~FLAG_TMP_DETACHED;
8418        }
8419
8420        void stopIgnoring() {
8421            mFlags = mFlags & ~FLAG_IGNORE;
8422        }
8423
8424        void setScrapContainer(Recycler recycler, boolean isChangeScrap) {
8425            mScrapContainer = recycler;
8426            mInChangeScrap = isChangeScrap;
8427        }
8428
8429        boolean isInvalid() {
8430            return (mFlags & FLAG_INVALID) != 0;
8431        }
8432
8433        boolean needsUpdate() {
8434            return (mFlags & FLAG_UPDATE) != 0;
8435        }
8436
8437        boolean isBound() {
8438            return (mFlags & FLAG_BOUND) != 0;
8439        }
8440
8441        boolean isRemoved() {
8442            return (mFlags & FLAG_REMOVED) != 0;
8443        }
8444
8445        boolean hasAnyOfTheFlags(int flags) {
8446            return (mFlags & flags) != 0;
8447        }
8448
8449        boolean isTmpDetached() {
8450            return (mFlags & FLAG_TMP_DETACHED) != 0;
8451        }
8452
8453        boolean isAdapterPositionUnknown() {
8454            return (mFlags & FLAG_ADAPTER_POSITION_UNKNOWN) != 0 || isInvalid();
8455        }
8456
8457        void setFlags(int flags, int mask) {
8458            mFlags = (mFlags & ~mask) | (flags & mask);
8459        }
8460
8461        void addFlags(int flags) {
8462            mFlags |= flags;
8463        }
8464
8465        void addChangePayload(Object payload) {
8466            if (payload == null) {
8467                addFlags(FLAG_ADAPTER_FULLUPDATE);
8468            } else if ((mFlags & FLAG_ADAPTER_FULLUPDATE) == 0) {
8469                createPayloadsIfNeeded();
8470                mPayloads.add(payload);
8471            }
8472        }
8473
8474        private void createPayloadsIfNeeded() {
8475            if (mPayloads == null) {
8476                mPayloads = new ArrayList<Object>();
8477                mUnmodifiedPayloads = Collections.unmodifiableList(mPayloads);
8478            }
8479        }
8480
8481        void clearPayload() {
8482            if (mPayloads != null) {
8483                mPayloads.clear();
8484            }
8485            mFlags = mFlags & ~FLAG_ADAPTER_FULLUPDATE;
8486        }
8487
8488        List<Object> getUnmodifiedPayloads() {
8489            if ((mFlags & FLAG_ADAPTER_FULLUPDATE) == 0) {
8490                if (mPayloads == null || mPayloads.size() == 0) {
8491                    // Initial state,  no update being called.
8492                    return FULLUPDATE_PAYLOADS;
8493                }
8494                // there are none-null payloads
8495                return mUnmodifiedPayloads;
8496            } else {
8497                // a full update has been called.
8498                return FULLUPDATE_PAYLOADS;
8499            }
8500        }
8501
8502        void resetInternal() {
8503            mFlags = 0;
8504            mPosition = NO_POSITION;
8505            mOldPosition = NO_POSITION;
8506            mItemId = NO_ID;
8507            mPreLayoutPosition = NO_POSITION;
8508            mIsRecyclableCount = 0;
8509            mShadowedHolder = null;
8510            mShadowingHolder = null;
8511            clearPayload();
8512            mWasImportantForAccessibilityBeforeHidden = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8513        }
8514
8515        /**
8516         * Called when the child view enters the hidden state
8517         */
8518        private void onEnteredHiddenState() {
8519            // While the view item is in hidden state, make it invisible for the accessibility.
8520            mWasImportantForAccessibilityBeforeHidden =
8521                    ViewCompat.getImportantForAccessibility(itemView);
8522            ViewCompat.setImportantForAccessibility(itemView,
8523                    ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS);
8524        }
8525
8526        /**
8527         * Called when the child view leaves the hidden state
8528         */
8529        private void onLeftHiddenState() {
8530            ViewCompat.setImportantForAccessibility(
8531                    itemView, mWasImportantForAccessibilityBeforeHidden);
8532            mWasImportantForAccessibilityBeforeHidden = ViewCompat.IMPORTANT_FOR_ACCESSIBILITY_AUTO;
8533        }
8534
8535        @Override
8536        public String toString() {
8537            final StringBuilder sb = new StringBuilder("ViewHolder{" +
8538                    Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId +
8539                    ", oldPos=" + mOldPosition + ", pLpos:" + mPreLayoutPosition);
8540            if (isScrap()) {
8541                sb.append(" scrap ")
8542                        .append(mInChangeScrap ? "[changeScrap]" : "[attachedScrap]");
8543            }
8544            if (isInvalid()) sb.append(" invalid");
8545            if (!isBound()) sb.append(" unbound");
8546            if (needsUpdate()) sb.append(" update");
8547            if (isRemoved()) sb.append(" removed");
8548            if (shouldIgnore()) sb.append(" ignored");
8549            if (isTmpDetached()) sb.append(" tmpDetached");
8550            if (!isRecyclable()) sb.append(" not recyclable(" + mIsRecyclableCount + ")");
8551            if (isAdapterPositionUnknown()) sb.append(" undefined adapter position");
8552
8553            if (itemView.getParent() == null) sb.append(" no parent");
8554            sb.append("}");
8555            return sb.toString();
8556        }
8557
8558        /**
8559         * Informs the recycler whether this item can be recycled. Views which are not
8560         * recyclable will not be reused for other items until setIsRecyclable() is
8561         * later set to true. Calls to setIsRecyclable() should always be paired (one
8562         * call to setIsRecyclabe(false) should always be matched with a later call to
8563         * setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally
8564         * reference-counted.
8565         *
8566         * @param recyclable Whether this item is available to be recycled. Default value
8567         * is true.
8568         */
8569        public final void setIsRecyclable(boolean recyclable) {
8570            mIsRecyclableCount = recyclable ? mIsRecyclableCount - 1 : mIsRecyclableCount + 1;
8571            if (mIsRecyclableCount < 0) {
8572                mIsRecyclableCount = 0;
8573                if (DEBUG) {
8574                    throw new RuntimeException("isRecyclable decremented below 0: " +
8575                            "unmatched pair of setIsRecyable() calls for " + this);
8576                }
8577                Log.e(VIEW_LOG_TAG, "isRecyclable decremented below 0: " +
8578                        "unmatched pair of setIsRecyable() calls for " + this);
8579            } else if (!recyclable && mIsRecyclableCount == 1) {
8580                mFlags |= FLAG_NOT_RECYCLABLE;
8581            } else if (recyclable && mIsRecyclableCount == 0) {
8582                mFlags &= ~FLAG_NOT_RECYCLABLE;
8583            }
8584            if (DEBUG) {
8585                Log.d(TAG, "setIsRecyclable val:" + recyclable + ":" + this);
8586            }
8587        }
8588
8589        /**
8590         * @see {@link #setIsRecyclable(boolean)}
8591         *
8592         * @return true if this item is available to be recycled, false otherwise.
8593         */
8594        public final boolean isRecyclable() {
8595            return (mFlags & FLAG_NOT_RECYCLABLE) == 0 &&
8596                    !ViewCompat.hasTransientState(itemView);
8597        }
8598
8599        /**
8600         * Returns whether we have animations referring to this view holder or not.
8601         * This is similar to isRecyclable flag but does not check transient state.
8602         */
8603        private boolean shouldBeKeptAsChild() {
8604            return (mFlags & FLAG_NOT_RECYCLABLE) != 0;
8605        }
8606
8607        /**
8608         * @return True if ViewHolder is not refenrenced by RecyclerView animations but has
8609         * transient state which will prevent it from being recycled.
8610         */
8611        private boolean doesTransientStatePreventRecycling() {
8612            return (mFlags & FLAG_NOT_RECYCLABLE) == 0 && ViewCompat.hasTransientState(itemView);
8613        }
8614
8615        boolean isUpdated() {
8616            return (mFlags & FLAG_UPDATE) != 0;
8617        }
8618    }
8619
8620    private int getAdapterPositionFor(ViewHolder viewHolder) {
8621        if (viewHolder.hasAnyOfTheFlags( ViewHolder.FLAG_INVALID |
8622                ViewHolder.FLAG_REMOVED | ViewHolder.FLAG_ADAPTER_POSITION_UNKNOWN)
8623                || !viewHolder.isBound()) {
8624            return RecyclerView.NO_POSITION;
8625        }
8626        return mAdapterHelper.applyPendingUpdatesToPosition(viewHolder.mPosition);
8627    }
8628
8629    // NestedScrollingChild
8630
8631    @Override
8632    public void setNestedScrollingEnabled(boolean enabled) {
8633        mScrollingChildHelper.setNestedScrollingEnabled(enabled);
8634    }
8635
8636    @Override
8637    public boolean isNestedScrollingEnabled() {
8638        return mScrollingChildHelper.isNestedScrollingEnabled();
8639    }
8640
8641    @Override
8642    public boolean startNestedScroll(int axes) {
8643        return mScrollingChildHelper.startNestedScroll(axes);
8644    }
8645
8646    @Override
8647    public void stopNestedScroll() {
8648        mScrollingChildHelper.stopNestedScroll();
8649    }
8650
8651    @Override
8652    public boolean hasNestedScrollingParent() {
8653        return mScrollingChildHelper.hasNestedScrollingParent();
8654    }
8655
8656    @Override
8657    public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed,
8658            int dyUnconsumed, int[] offsetInWindow) {
8659        return mScrollingChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed,
8660                dxUnconsumed, dyUnconsumed, offsetInWindow);
8661    }
8662
8663    @Override
8664    public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
8665        return mScrollingChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
8666    }
8667
8668    @Override
8669    public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
8670        return mScrollingChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
8671    }
8672
8673    @Override
8674    public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
8675        return mScrollingChildHelper.dispatchNestedPreFling(velocityX, velocityY);
8676    }
8677
8678    /**
8679     * {@link android.view.ViewGroup.MarginLayoutParams LayoutParams} subclass for children of
8680     * {@link RecyclerView}. Custom {@link LayoutManager layout managers} are encouraged
8681     * to create their own subclass of this <code>LayoutParams</code> class
8682     * to store any additional required per-child view metadata about the layout.
8683     */
8684    public static class LayoutParams extends android.view.ViewGroup.MarginLayoutParams {
8685        ViewHolder mViewHolder;
8686        final Rect mDecorInsets = new Rect();
8687        boolean mInsetsDirty = true;
8688        // Flag is set to true if the view is bound while it is detached from RV.
8689        // In this case, we need to manually call invalidate after view is added to guarantee that
8690        // invalidation is populated through the View hierarchy
8691        boolean mPendingInvalidate = false;
8692
8693        public LayoutParams(Context c, AttributeSet attrs) {
8694            super(c, attrs);
8695        }
8696
8697        public LayoutParams(int width, int height) {
8698            super(width, height);
8699        }
8700
8701        public LayoutParams(MarginLayoutParams source) {
8702            super(source);
8703        }
8704
8705        public LayoutParams(ViewGroup.LayoutParams source) {
8706            super(source);
8707        }
8708
8709        public LayoutParams(LayoutParams source) {
8710            super((ViewGroup.LayoutParams) source);
8711        }
8712
8713        /**
8714         * Returns true if the view this LayoutParams is attached to needs to have its content
8715         * updated from the corresponding adapter.
8716         *
8717         * @return true if the view should have its content updated
8718         */
8719        public boolean viewNeedsUpdate() {
8720            return mViewHolder.needsUpdate();
8721        }
8722
8723        /**
8724         * Returns true if the view this LayoutParams is attached to is now representing
8725         * potentially invalid data. A LayoutManager should scrap/recycle it.
8726         *
8727         * @return true if the view is invalid
8728         */
8729        public boolean isViewInvalid() {
8730            return mViewHolder.isInvalid();
8731        }
8732
8733        /**
8734         * Returns true if the adapter data item corresponding to the view this LayoutParams
8735         * is attached to has been removed from the data set. A LayoutManager may choose to
8736         * treat it differently in order to animate its outgoing or disappearing state.
8737         *
8738         * @return true if the item the view corresponds to was removed from the data set
8739         */
8740        public boolean isItemRemoved() {
8741            return mViewHolder.isRemoved();
8742        }
8743
8744        /**
8745         * Returns true if the adapter data item corresponding to the view this LayoutParams
8746         * is attached to has been changed in the data set. A LayoutManager may choose to
8747         * treat it differently in order to animate its changing state.
8748         *
8749         * @return true if the item the view corresponds to was changed in the data set
8750         */
8751        public boolean isItemChanged() {
8752            return mViewHolder.isUpdated();
8753        }
8754
8755        /**
8756         * @deprecated use {@link #getViewLayoutPosition()} or {@link #getViewAdapterPosition()}
8757         */
8758        public int getViewPosition() {
8759            return mViewHolder.getPosition();
8760        }
8761
8762        /**
8763         * Returns the adapter position that the view this LayoutParams is attached to corresponds
8764         * to as of latest layout calculation.
8765         *
8766         * @return the adapter position this view as of latest layout pass
8767         */
8768        public int getViewLayoutPosition() {
8769            return mViewHolder.getLayoutPosition();
8770        }
8771
8772        /**
8773         * Returns the up-to-date adapter position that the view this LayoutParams is attached to
8774         * corresponds to.
8775         *
8776         * @return the up-to-date adapter position this view. It may return
8777         * {@link RecyclerView#NO_POSITION} if item represented by this View has been removed or
8778         * its up-to-date position cannot be calculated.
8779         */
8780        public int getViewAdapterPosition() {
8781            return mViewHolder.getAdapterPosition();
8782        }
8783    }
8784
8785    /**
8786     * Observer base class for watching changes to an {@link Adapter}.
8787     * See {@link Adapter#registerAdapterDataObserver(AdapterDataObserver)}.
8788     */
8789    public static abstract class AdapterDataObserver {
8790        public void onChanged() {
8791            // Do nothing
8792        }
8793
8794        public void onItemRangeChanged(int positionStart, int itemCount) {
8795            // do nothing
8796        }
8797
8798        public void onItemRangeChanged(int positionStart, int itemCount, Object payload) {
8799            // fallback to onItemRangeChanged(positionStart, itemCount) if app
8800            // does not override this method.
8801            onItemRangeChanged(positionStart, itemCount);
8802        }
8803
8804        public void onItemRangeInserted(int positionStart, int itemCount) {
8805            // do nothing
8806        }
8807
8808        public void onItemRangeRemoved(int positionStart, int itemCount) {
8809            // do nothing
8810        }
8811
8812        public void onItemRangeMoved(int fromPosition, int toPosition, int itemCount) {
8813            // do nothing
8814        }
8815    }
8816
8817    /**
8818     * <p>Base class for smooth scrolling. Handles basic tracking of the target view position and
8819     * provides methods to trigger a programmatic scroll.</p>
8820     *
8821     * @see LinearSmoothScroller
8822     */
8823    public static abstract class SmoothScroller {
8824
8825        private int mTargetPosition = RecyclerView.NO_POSITION;
8826
8827        private RecyclerView mRecyclerView;
8828
8829        private LayoutManager mLayoutManager;
8830
8831        private boolean mPendingInitialRun;
8832
8833        private boolean mRunning;
8834
8835        private View mTargetView;
8836
8837        private final Action mRecyclingAction;
8838
8839        public SmoothScroller() {
8840            mRecyclingAction = new Action(0, 0);
8841        }
8842
8843        /**
8844         * Starts a smooth scroll for the given target position.
8845         * <p>In each animation step, {@link RecyclerView} will check
8846         * for the target view and call either
8847         * {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
8848         * {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)} until
8849         * SmoothScroller is stopped.</p>
8850         *
8851         * <p>Note that if RecyclerView finds the target view, it will automatically stop the
8852         * SmoothScroller. This <b>does not</b> mean that scroll will stop, it only means it will
8853         * stop calling SmoothScroller in each animation step.</p>
8854         */
8855        void start(RecyclerView recyclerView, LayoutManager layoutManager) {
8856            mRecyclerView = recyclerView;
8857            mLayoutManager = layoutManager;
8858            if (mTargetPosition == RecyclerView.NO_POSITION) {
8859                throw new IllegalArgumentException("Invalid target position");
8860            }
8861            mRecyclerView.mState.mTargetPosition = mTargetPosition;
8862            mRunning = true;
8863            mPendingInitialRun = true;
8864            mTargetView = findViewByPosition(getTargetPosition());
8865            onStart();
8866            mRecyclerView.mViewFlinger.postOnAnimation();
8867        }
8868
8869        public void setTargetPosition(int targetPosition) {
8870            mTargetPosition = targetPosition;
8871        }
8872
8873        /**
8874         * @return The LayoutManager to which this SmoothScroller is attached. Will return
8875         * <code>null</code> after the SmoothScroller is stopped.
8876         */
8877        @Nullable
8878        public LayoutManager getLayoutManager() {
8879            return mLayoutManager;
8880        }
8881
8882        /**
8883         * Stops running the SmoothScroller in each animation callback. Note that this does not
8884         * cancel any existing {@link Action} updated by
8885         * {@link #onTargetFound(android.view.View, RecyclerView.State, SmoothScroller.Action)} or
8886         * {@link #onSeekTargetStep(int, int, RecyclerView.State, SmoothScroller.Action)}.
8887         */
8888        final protected void stop() {
8889            if (!mRunning) {
8890                return;
8891            }
8892            onStop();
8893            mRecyclerView.mState.mTargetPosition = RecyclerView.NO_POSITION;
8894            mTargetView = null;
8895            mTargetPosition = RecyclerView.NO_POSITION;
8896            mPendingInitialRun = false;
8897            mRunning = false;
8898            // trigger a cleanup
8899            mLayoutManager.onSmoothScrollerStopped(this);
8900            // clear references to avoid any potential leak by a custom smooth scroller
8901            mLayoutManager = null;
8902            mRecyclerView = null;
8903        }
8904
8905        /**
8906         * Returns true if SmoothScroller has been started but has not received the first
8907         * animation
8908         * callback yet.
8909         *
8910         * @return True if this SmoothScroller is waiting to start
8911         */
8912        public boolean isPendingInitialRun() {
8913            return mPendingInitialRun;
8914        }
8915
8916
8917        /**
8918         * @return True if SmoothScroller is currently active
8919         */
8920        public boolean isRunning() {
8921            return mRunning;
8922        }
8923
8924        /**
8925         * Returns the adapter position of the target item
8926         *
8927         * @return Adapter position of the target item or
8928         * {@link RecyclerView#NO_POSITION} if no target view is set.
8929         */
8930        public int getTargetPosition() {
8931            return mTargetPosition;
8932        }
8933
8934        private void onAnimation(int dx, int dy) {
8935            final RecyclerView recyclerView = mRecyclerView;
8936            if (!mRunning || mTargetPosition == RecyclerView.NO_POSITION || recyclerView == null) {
8937                stop();
8938            }
8939            mPendingInitialRun = false;
8940            if (mTargetView != null) {
8941                // verify target position
8942                if (getChildPosition(mTargetView) == mTargetPosition) {
8943                    onTargetFound(mTargetView, recyclerView.mState, mRecyclingAction);
8944                    mRecyclingAction.runIfNecessary(recyclerView);
8945                    stop();
8946                } else {
8947                    Log.e(TAG, "Passed over target position while smooth scrolling.");
8948                    mTargetView = null;
8949                }
8950            }
8951            if (mRunning) {
8952                onSeekTargetStep(dx, dy, recyclerView.mState, mRecyclingAction);
8953                boolean hadJumpTarget = mRecyclingAction.hasJumpTarget();
8954                mRecyclingAction.runIfNecessary(recyclerView);
8955                if (hadJumpTarget) {
8956                    // It is not stopped so needs to be restarted
8957                    if (mRunning) {
8958                        mPendingInitialRun = true;
8959                        recyclerView.mViewFlinger.postOnAnimation();
8960                    } else {
8961                        stop(); // done
8962                    }
8963                }
8964            }
8965        }
8966
8967        /**
8968         * @see RecyclerView#getChildLayoutPosition(android.view.View)
8969         */
8970        public int getChildPosition(View view) {
8971            return mRecyclerView.getChildLayoutPosition(view);
8972        }
8973
8974        /**
8975         * @see RecyclerView.LayoutManager#getChildCount()
8976         */
8977        public int getChildCount() {
8978            return mRecyclerView.mLayout.getChildCount();
8979        }
8980
8981        /**
8982         * @see RecyclerView.LayoutManager#findViewByPosition(int)
8983         */
8984        public View findViewByPosition(int position) {
8985            return mRecyclerView.mLayout.findViewByPosition(position);
8986        }
8987
8988        /**
8989         * @see RecyclerView#scrollToPosition(int)
8990         * @deprecated Use {@link Action#jumpTo(int)}.
8991         */
8992        @Deprecated
8993        public void instantScrollToPosition(int position) {
8994            mRecyclerView.scrollToPosition(position);
8995        }
8996
8997        protected void onChildAttachedToWindow(View child) {
8998            if (getChildPosition(child) == getTargetPosition()) {
8999                mTargetView = child;
9000                if (DEBUG) {
9001                    Log.d(TAG, "smooth scroll target view has been attached");
9002                }
9003            }
9004        }
9005
9006        /**
9007         * Normalizes the vector.
9008         * @param scrollVector The vector that points to the target scroll position
9009         */
9010        protected void normalize(PointF scrollVector) {
9011            final double magnitute = Math.sqrt(scrollVector.x * scrollVector.x + scrollVector.y *
9012                    scrollVector.y);
9013            scrollVector.x /= magnitute;
9014            scrollVector.y /= magnitute;
9015        }
9016
9017        /**
9018         * Called when smooth scroll is started. This might be a good time to do setup.
9019         */
9020        abstract protected void onStart();
9021
9022        /**
9023         * Called when smooth scroller is stopped. This is a good place to cleanup your state etc.
9024         * @see #stop()
9025         */
9026        abstract protected void onStop();
9027
9028        /**
9029         * <p>RecyclerView will call this method each time it scrolls until it can find the target
9030         * position in the layout.</p>
9031         * <p>SmoothScroller should check dx, dy and if scroll should be changed, update the
9032         * provided {@link Action} to define the next scroll.</p>
9033         *
9034         * @param dx        Last scroll amount horizontally
9035         * @param dy        Last scroll amount verticaully
9036         * @param state     Transient state of RecyclerView
9037         * @param action    If you want to trigger a new smooth scroll and cancel the previous one,
9038         *                  update this object.
9039         */
9040        abstract protected void onSeekTargetStep(int dx, int dy, State state, Action action);
9041
9042        /**
9043         * Called when the target position is laid out. This is the last callback SmoothScroller
9044         * will receive and it should update the provided {@link Action} to define the scroll
9045         * details towards the target view.
9046         * @param targetView    The view element which render the target position.
9047         * @param state         Transient state of RecyclerView
9048         * @param action        Action instance that you should update to define final scroll action
9049         *                      towards the targetView
9050         */
9051        abstract protected void onTargetFound(View targetView, State state, Action action);
9052
9053        /**
9054         * Holds information about a smooth scroll request by a {@link SmoothScroller}.
9055         */
9056        public static class Action {
9057
9058            public static final int UNDEFINED_DURATION = Integer.MIN_VALUE;
9059
9060            private int mDx;
9061
9062            private int mDy;
9063
9064            private int mDuration;
9065
9066            private int mJumpToPosition = NO_POSITION;
9067
9068            private Interpolator mInterpolator;
9069
9070            private boolean changed = false;
9071
9072            // we track this variable to inform custom implementer if they are updating the action
9073            // in every animation callback
9074            private int consecutiveUpdates = 0;
9075
9076            /**
9077             * @param dx Pixels to scroll horizontally
9078             * @param dy Pixels to scroll vertically
9079             */
9080            public Action(int dx, int dy) {
9081                this(dx, dy, UNDEFINED_DURATION, null);
9082            }
9083
9084            /**
9085             * @param dx       Pixels to scroll horizontally
9086             * @param dy       Pixels to scroll vertically
9087             * @param duration Duration of the animation in milliseconds
9088             */
9089            public Action(int dx, int dy, int duration) {
9090                this(dx, dy, duration, null);
9091            }
9092
9093            /**
9094             * @param dx           Pixels to scroll horizontally
9095             * @param dy           Pixels to scroll vertically
9096             * @param duration     Duration of the animation in milliseconds
9097             * @param interpolator Interpolator to be used when calculating scroll position in each
9098             *                     animation step
9099             */
9100            public Action(int dx, int dy, int duration, Interpolator interpolator) {
9101                mDx = dx;
9102                mDy = dy;
9103                mDuration = duration;
9104                mInterpolator = interpolator;
9105            }
9106
9107            /**
9108             * Instead of specifying pixels to scroll, use the target position to jump using
9109             * {@link RecyclerView#scrollToPosition(int)}.
9110             * <p>
9111             * You may prefer using this method if scroll target is really far away and you prefer
9112             * to jump to a location and smooth scroll afterwards.
9113             * <p>
9114             * Note that calling this method takes priority over other update methods such as
9115             * {@link #update(int, int, int, Interpolator)}, {@link #setX(float)},
9116             * {@link #setY(float)} and #{@link #setInterpolator(Interpolator)}. If you call
9117             * {@link #jumpTo(int)}, the other changes will not be considered for this animation
9118             * frame.
9119             *
9120             * @param targetPosition The target item position to scroll to using instant scrolling.
9121             */
9122            public void jumpTo(int targetPosition) {
9123                mJumpToPosition = targetPosition;
9124            }
9125
9126            boolean hasJumpTarget() {
9127                return mJumpToPosition >= 0;
9128            }
9129
9130            private void runIfNecessary(RecyclerView recyclerView) {
9131                if (mJumpToPosition >= 0) {
9132                    final int position = mJumpToPosition;
9133                    mJumpToPosition = NO_POSITION;
9134                    recyclerView.jumpToPositionForSmoothScroller(position);
9135                    changed = false;
9136                    return;
9137                }
9138                if (changed) {
9139                    validate();
9140                    if (mInterpolator == null) {
9141                        if (mDuration == UNDEFINED_DURATION) {
9142                            recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy);
9143                        } else {
9144                            recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration);
9145                        }
9146                    } else {
9147                        recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration, mInterpolator);
9148                    }
9149                    consecutiveUpdates ++;
9150                    if (consecutiveUpdates > 10) {
9151                        // A new action is being set in every animation step. This looks like a bad
9152                        // implementation. Inform developer.
9153                        Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure"
9154                                + " you are not changing it unless necessary");
9155                    }
9156                    changed = false;
9157                } else {
9158                    consecutiveUpdates = 0;
9159                }
9160            }
9161
9162            private void validate() {
9163                if (mInterpolator != null && mDuration < 1) {
9164                    throw new IllegalStateException("If you provide an interpolator, you must"
9165                            + " set a positive duration");
9166                } else if (mDuration < 1) {
9167                    throw new IllegalStateException("Scroll duration must be a positive number");
9168                }
9169            }
9170
9171            public int getDx() {
9172                return mDx;
9173            }
9174
9175            public void setDx(int dx) {
9176                changed = true;
9177                mDx = dx;
9178            }
9179
9180            public int getDy() {
9181                return mDy;
9182            }
9183
9184            public void setDy(int dy) {
9185                changed = true;
9186                mDy = dy;
9187            }
9188
9189            public int getDuration() {
9190                return mDuration;
9191            }
9192
9193            public void setDuration(int duration) {
9194                changed = true;
9195                mDuration = duration;
9196            }
9197
9198            public Interpolator getInterpolator() {
9199                return mInterpolator;
9200            }
9201
9202            /**
9203             * Sets the interpolator to calculate scroll steps
9204             * @param interpolator The interpolator to use. If you specify an interpolator, you must
9205             *                     also set the duration.
9206             * @see #setDuration(int)
9207             */
9208            public void setInterpolator(Interpolator interpolator) {
9209                changed = true;
9210                mInterpolator = interpolator;
9211            }
9212
9213            /**
9214             * Updates the action with given parameters.
9215             * @param dx Pixels to scroll horizontally
9216             * @param dy Pixels to scroll vertically
9217             * @param duration Duration of the animation in milliseconds
9218             * @param interpolator Interpolator to be used when calculating scroll position in each
9219             *                     animation step
9220             */
9221            public void update(int dx, int dy, int duration, Interpolator interpolator) {
9222                mDx = dx;
9223                mDy = dy;
9224                mDuration = duration;
9225                mInterpolator = interpolator;
9226                changed = true;
9227            }
9228        }
9229    }
9230
9231    static class AdapterDataObservable extends Observable<AdapterDataObserver> {
9232        public boolean hasObservers() {
9233            return !mObservers.isEmpty();
9234        }
9235
9236        public void notifyChanged() {
9237            // since onChanged() is implemented by the app, it could do anything, including
9238            // removing itself from {@link mObservers} - and that could cause problems if
9239            // an iterator is used on the ArrayList {@link mObservers}.
9240            // to avoid such problems, just march thru the list in the reverse order.
9241            for (int i = mObservers.size() - 1; i >= 0; i--) {
9242                mObservers.get(i).onChanged();
9243            }
9244        }
9245
9246        public void notifyItemRangeChanged(int positionStart, int itemCount) {
9247            notifyItemRangeChanged(positionStart, itemCount, null);
9248        }
9249
9250        public void notifyItemRangeChanged(int positionStart, int itemCount, Object payload) {
9251            // since onItemRangeChanged() is implemented by the app, it could do anything, including
9252            // removing itself from {@link mObservers} - and that could cause problems if
9253            // an iterator is used on the ArrayList {@link mObservers}.
9254            // to avoid such problems, just march thru the list in the reverse order.
9255            for (int i = mObservers.size() - 1; i >= 0; i--) {
9256                mObservers.get(i).onItemRangeChanged(positionStart, itemCount, payload);
9257            }
9258        }
9259
9260        public void notifyItemRangeInserted(int positionStart, int itemCount) {
9261            // since onItemRangeInserted() is implemented by the app, it could do anything,
9262            // including removing itself from {@link mObservers} - and that could cause problems if
9263            // an iterator is used on the ArrayList {@link mObservers}.
9264            // to avoid such problems, just march thru the list in the reverse order.
9265            for (int i = mObservers.size() - 1; i >= 0; i--) {
9266                mObservers.get(i).onItemRangeInserted(positionStart, itemCount);
9267            }
9268        }
9269
9270        public void notifyItemRangeRemoved(int positionStart, int itemCount) {
9271            // since onItemRangeRemoved() is implemented by the app, it could do anything, including
9272            // removing itself from {@link mObservers} - and that could cause problems if
9273            // an iterator is used on the ArrayList {@link mObservers}.
9274            // to avoid such problems, just march thru the list in the reverse order.
9275            for (int i = mObservers.size() - 1; i >= 0; i--) {
9276                mObservers.get(i).onItemRangeRemoved(positionStart, itemCount);
9277            }
9278        }
9279
9280        public void notifyItemMoved(int fromPosition, int toPosition) {
9281            for (int i = mObservers.size() - 1; i >= 0; i--) {
9282                mObservers.get(i).onItemRangeMoved(fromPosition, toPosition, 1);
9283            }
9284        }
9285    }
9286
9287    /**
9288     * This is public so that the CREATOR can be access on cold launch.
9289     * @hide
9290     */
9291    public static class SavedState extends android.view.View.BaseSavedState {
9292
9293        Parcelable mLayoutState;
9294
9295        /**
9296         * called by CREATOR
9297         */
9298        SavedState(Parcel in) {
9299            super(in);
9300            mLayoutState = in.readParcelable(LayoutManager.class.getClassLoader());
9301        }
9302
9303        /**
9304         * Called by onSaveInstanceState
9305         */
9306        SavedState(Parcelable superState) {
9307            super(superState);
9308        }
9309
9310        @Override
9311        public void writeToParcel(Parcel dest, int flags) {
9312            super.writeToParcel(dest, flags);
9313            dest.writeParcelable(mLayoutState, 0);
9314        }
9315
9316        private void copyFrom(SavedState other) {
9317            mLayoutState = other.mLayoutState;
9318        }
9319
9320        public static final Parcelable.Creator<SavedState> CREATOR
9321                = new Parcelable.Creator<SavedState>() {
9322            @Override
9323            public SavedState createFromParcel(Parcel in) {
9324                return new SavedState(in);
9325            }
9326
9327            @Override
9328            public SavedState[] newArray(int size) {
9329                return new SavedState[size];
9330            }
9331        };
9332    }
9333    /**
9334     * <p>Contains useful information about the current RecyclerView state like target scroll
9335     * position or view focus. State object can also keep arbitrary data, identified by resource
9336     * ids.</p>
9337     * <p>Often times, RecyclerView components will need to pass information between each other.
9338     * To provide a well defined data bus between components, RecyclerView passes the same State
9339     * object to component callbacks and these components can use it to exchange data.</p>
9340     * <p>If you implement custom components, you can use State's put/get/remove methods to pass
9341     * data between your components without needing to manage their lifecycles.</p>
9342     */
9343    public static class State {
9344
9345        private int mTargetPosition = RecyclerView.NO_POSITION;
9346
9347        private SparseArray<Object> mData;
9348
9349        /**
9350         * Number of items adapter has.
9351         */
9352        int mItemCount = 0;
9353
9354        /**
9355         * Number of items adapter had in the previous layout.
9356         */
9357        private int mPreviousLayoutItemCount = 0;
9358
9359        /**
9360         * Number of items that were NOT laid out but has been deleted from the adapter after the
9361         * previous layout.
9362         */
9363        private int mDeletedInvisibleItemCountSincePreviousLayout = 0;
9364
9365        private boolean mStructureChanged = false;
9366
9367        private boolean mInPreLayout = false;
9368
9369        private boolean mRunSimpleAnimations = false;
9370
9371        private boolean mRunPredictiveAnimations = false;
9372
9373        private boolean mTrackOldChangeHolders = false;
9374
9375        State reset() {
9376            mTargetPosition = RecyclerView.NO_POSITION;
9377            if (mData != null) {
9378                mData.clear();
9379            }
9380            mItemCount = 0;
9381            mStructureChanged = false;
9382            return this;
9383        }
9384
9385        public boolean isPreLayout() {
9386            return mInPreLayout;
9387        }
9388
9389        /**
9390         * Returns whether RecyclerView will run predictive animations in this layout pass
9391         * or not.
9392         *
9393         * @return true if RecyclerView is calculating predictive animations to be run at the end
9394         *         of the layout pass.
9395         */
9396        public boolean willRunPredictiveAnimations() {
9397            return mRunPredictiveAnimations;
9398        }
9399
9400        /**
9401         * Returns whether RecyclerView will run simple animations in this layout pass
9402         * or not.
9403         *
9404         * @return true if RecyclerView is calculating simple animations to be run at the end of
9405         *         the layout pass.
9406         */
9407        public boolean willRunSimpleAnimations() {
9408            return mRunSimpleAnimations;
9409        }
9410
9411        /**
9412         * Removes the mapping from the specified id, if there was any.
9413         * @param resourceId Id of the resource you want to remove. It is suggested to use R.id.* to
9414         *                   preserve cross functionality and avoid conflicts.
9415         */
9416        public void remove(int resourceId) {
9417            if (mData == null) {
9418                return;
9419            }
9420            mData.remove(resourceId);
9421        }
9422
9423        /**
9424         * Gets the Object mapped from the specified id, or <code>null</code>
9425         * if no such data exists.
9426         *
9427         * @param resourceId Id of the resource you want to remove. It is suggested to use R.id.*
9428         *                   to
9429         *                   preserve cross functionality and avoid conflicts.
9430         */
9431        public <T> T get(int resourceId) {
9432            if (mData == null) {
9433                return null;
9434            }
9435            return (T) mData.get(resourceId);
9436        }
9437
9438        /**
9439         * Adds a mapping from the specified id to the specified value, replacing the previous
9440         * mapping from the specified key if there was one.
9441         *
9442         * @param resourceId Id of the resource you want to add. It is suggested to use R.id.* to
9443         *                   preserve cross functionality and avoid conflicts.
9444         * @param data       The data you want to associate with the resourceId.
9445         */
9446        public void put(int resourceId, Object data) {
9447            if (mData == null) {
9448                mData = new SparseArray<Object>();
9449            }
9450            mData.put(resourceId, data);
9451        }
9452
9453        /**
9454         * If scroll is triggered to make a certain item visible, this value will return the
9455         * adapter index of that item.
9456         * @return Adapter index of the target item or
9457         * {@link RecyclerView#NO_POSITION} if there is no target
9458         * position.
9459         */
9460        public int getTargetScrollPosition() {
9461            return mTargetPosition;
9462        }
9463
9464        /**
9465         * Returns if current scroll has a target position.
9466         * @return true if scroll is being triggered to make a certain position visible
9467         * @see #getTargetScrollPosition()
9468         */
9469        public boolean hasTargetScrollPosition() {
9470            return mTargetPosition != RecyclerView.NO_POSITION;
9471        }
9472
9473        /**
9474         * @return true if the structure of the data set has changed since the last call to
9475         *         onLayoutChildren, false otherwise
9476         */
9477        public boolean didStructureChange() {
9478            return mStructureChanged;
9479        }
9480
9481        /**
9482         * Returns the total number of items that can be laid out. Note that this number is not
9483         * necessarily equal to the number of items in the adapter, so you should always use this
9484         * number for your position calculations and never access the adapter directly.
9485         * <p>
9486         * RecyclerView listens for Adapter's notify events and calculates the effects of adapter
9487         * data changes on existing Views. These calculations are used to decide which animations
9488         * should be run.
9489         * <p>
9490         * To support predictive animations, RecyclerView may rewrite or reorder Adapter changes to
9491         * present the correct state to LayoutManager in pre-layout pass.
9492         * <p>
9493         * For example, a newly added item is not included in pre-layout item count because
9494         * pre-layout reflects the contents of the adapter before the item is added. Behind the
9495         * scenes, RecyclerView offsets {@link Recycler#getViewForPosition(int)} calls such that
9496         * LayoutManager does not know about the new item's existence in pre-layout. The item will
9497         * be available in second layout pass and will be included in the item count. Similar
9498         * adjustments are made for moved and removed items as well.
9499         * <p>
9500         * You can get the adapter's item count via {@link LayoutManager#getItemCount()} method.
9501         *
9502         * @return The number of items currently available
9503         * @see LayoutManager#getItemCount()
9504         */
9505        public int getItemCount() {
9506            return mInPreLayout ?
9507                    (mPreviousLayoutItemCount - mDeletedInvisibleItemCountSincePreviousLayout) :
9508                    mItemCount;
9509        }
9510
9511        @Override
9512        public String toString() {
9513            return "State{" +
9514                    "mTargetPosition=" + mTargetPosition +
9515                    ", mData=" + mData +
9516                    ", mItemCount=" + mItemCount +
9517                    ", mPreviousLayoutItemCount=" + mPreviousLayoutItemCount +
9518                    ", mDeletedInvisibleItemCountSincePreviousLayout="
9519                    + mDeletedInvisibleItemCountSincePreviousLayout +
9520                    ", mStructureChanged=" + mStructureChanged +
9521                    ", mInPreLayout=" + mInPreLayout +
9522                    ", mRunSimpleAnimations=" + mRunSimpleAnimations +
9523                    ", mRunPredictiveAnimations=" + mRunPredictiveAnimations +
9524                    '}';
9525        }
9526    }
9527
9528    /**
9529     * Internal listener that manages items after animations finish. This is how items are
9530     * retained (not recycled) during animations, but allowed to be recycled afterwards.
9531     * It depends on the contract with the ItemAnimator to call the appropriate dispatch*Finished()
9532     * method on the animator's listener when it is done animating any item.
9533     */
9534    private class ItemAnimatorRestoreListener implements ItemAnimator.ItemAnimatorListener {
9535
9536        @Override
9537        public void onAnimationFinished(ViewHolder item) {
9538            item.setIsRecyclable(true);
9539            if (item.mShadowedHolder != null && item.mShadowingHolder == null) { // old vh
9540                item.mShadowedHolder = null;
9541            }
9542            // always null this because an OldViewHolder can never become NewViewHolder w/o being
9543            // recycled.
9544            item.mShadowingHolder = null;
9545            if (!item.shouldBeKeptAsChild()) {
9546                if (!removeAnimatingView(item.itemView) && item.isTmpDetached()) {
9547                    removeDetachedView(item.itemView, false);
9548                }
9549            }
9550        }
9551    }
9552
9553    /**
9554     * This class defines the animations that take place on items as changes are made
9555     * to the adapter.
9556     *
9557     * Subclasses of ItemAnimator can be used to implement custom animations for actions on
9558     * ViewHolder items. The RecyclerView will manage retaining these items while they
9559     * are being animated, but implementors must call {@link #dispatchAnimationFinished(ViewHolder)}
9560     * when a ViewHolder's animation is finished. In other words, there must be a matching
9561     * {@link #dispatchAnimationFinished(ViewHolder)} call for each
9562     * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo) animateAppearance()},
9563     * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
9564     * animateChange()}
9565     * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo) animatePersistence()},
9566     * and
9567     * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9568     * animateDisappearance()} call.
9569     *
9570     * <p>By default, RecyclerView uses {@link DefaultItemAnimator}.</p>
9571     *
9572     * @see #setItemAnimator(ItemAnimator)
9573     */
9574    @SuppressWarnings("UnusedParameters")
9575    public static abstract class ItemAnimator {
9576
9577        /**
9578         * The Item represented by this ViewHolder is updated.
9579         * <p>
9580         * @see #recordPreLayoutInformation(State, ViewHolder, int, List)
9581         */
9582        public static final int FLAG_CHANGED = ViewHolder.FLAG_UPDATE;
9583
9584        /**
9585         * The Item represented by this ViewHolder is removed from the adapter.
9586         * <p>
9587         * @see #recordPreLayoutInformation(State, ViewHolder, int, List)
9588         */
9589        public static final int FLAG_REMOVED = ViewHolder.FLAG_REMOVED;
9590
9591        /**
9592         * Adapter {@link Adapter#notifyDataSetChanged()} has been called and the content
9593         * represented by this ViewHolder is invalid.
9594         * <p>
9595         * @see #recordPreLayoutInformation(State, ViewHolder, int, List)
9596         */
9597        public static final int FLAG_INVALIDATED = ViewHolder.FLAG_INVALID;
9598
9599        /**
9600         * The position of the Item represented by this ViewHolder has been changed. This flag is
9601         * not bound to {@link Adapter#notifyItemMoved(int, int)}. It might be set in response to
9602         * any adapter change that may have a side effect on this item. (e.g. The item before this
9603         * one has been removed from the Adapter).
9604         * <p>
9605         * @see #recordPreLayoutInformation(State, ViewHolder, int, List)
9606         */
9607        public static final int FLAG_MOVED = ViewHolder.FLAG_MOVED;
9608
9609        /**
9610         * This ViewHolder was not laid out but has been added to the layout in pre-layout state
9611         * by the {@link LayoutManager}. This means that the item was already in the Adapter but
9612         * invisible and it may become visible in the post layout phase. LayoutManagers may prefer
9613         * to add new items in pre-layout to specify their virtual location when they are invisible
9614         * (e.g. to specify the item should <i>animate in</i> from below the visible area).
9615         * <p>
9616         * @see #recordPreLayoutInformation(State, ViewHolder, int, List)
9617         */
9618        public static final int FLAG_APPEARED_IN_PRE_LAYOUT
9619                = ViewHolder.FLAG_APPEARED_IN_PRE_LAYOUT;
9620
9621        /**
9622         * The set of flags that might be passed to
9623         * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9624         */
9625        @IntDef(flag=true, value={
9626                FLAG_CHANGED, FLAG_REMOVED, FLAG_MOVED, FLAG_INVALIDATED,
9627                FLAG_APPEARED_IN_PRE_LAYOUT
9628        })
9629        @Retention(RetentionPolicy.SOURCE)
9630        public @interface AdapterChanges {}
9631        private ItemAnimatorListener mListener = null;
9632        private ArrayList<ItemAnimatorFinishedListener> mFinishedListeners =
9633                new ArrayList<ItemAnimatorFinishedListener>();
9634
9635        private long mAddDuration = 120;
9636        private long mRemoveDuration = 120;
9637        private long mMoveDuration = 250;
9638        private long mChangeDuration = 250;
9639
9640        /**
9641         * Gets the current duration for which all move animations will run.
9642         *
9643         * @return The current move duration
9644         */
9645        public long getMoveDuration() {
9646            return mMoveDuration;
9647        }
9648
9649        /**
9650         * Sets the duration for which all move animations will run.
9651         *
9652         * @param moveDuration The move duration
9653         */
9654        public void setMoveDuration(long moveDuration) {
9655            mMoveDuration = moveDuration;
9656        }
9657
9658        /**
9659         * Gets the current duration for which all add animations will run.
9660         *
9661         * @return The current add duration
9662         */
9663        public long getAddDuration() {
9664            return mAddDuration;
9665        }
9666
9667        /**
9668         * Sets the duration for which all add animations will run.
9669         *
9670         * @param addDuration The add duration
9671         */
9672        public void setAddDuration(long addDuration) {
9673            mAddDuration = addDuration;
9674        }
9675
9676        /**
9677         * Gets the current duration for which all remove animations will run.
9678         *
9679         * @return The current remove duration
9680         */
9681        public long getRemoveDuration() {
9682            return mRemoveDuration;
9683        }
9684
9685        /**
9686         * Sets the duration for which all remove animations will run.
9687         *
9688         * @param removeDuration The remove duration
9689         */
9690        public void setRemoveDuration(long removeDuration) {
9691            mRemoveDuration = removeDuration;
9692        }
9693
9694        /**
9695         * Gets the current duration for which all change animations will run.
9696         *
9697         * @return The current change duration
9698         */
9699        public long getChangeDuration() {
9700            return mChangeDuration;
9701        }
9702
9703        /**
9704         * Sets the duration for which all change animations will run.
9705         *
9706         * @param changeDuration The change duration
9707         */
9708        public void setChangeDuration(long changeDuration) {
9709            mChangeDuration = changeDuration;
9710        }
9711
9712        /**
9713         * Internal only:
9714         * Sets the listener that must be called when the animator is finished
9715         * animating the item (or immediately if no animation happens). This is set
9716         * internally and is not intended to be set by external code.
9717         *
9718         * @param listener The listener that must be called.
9719         */
9720        void setListener(ItemAnimatorListener listener) {
9721            mListener = listener;
9722        }
9723
9724        /**
9725         * Called by the RecyclerView before the layout begins. Item animator should record
9726         * necessary information about the View before it is potentially rebound, moved or removed.
9727         * <p>
9728         * The data returned from this method will be passed to the related <code>animate**</code>
9729         * methods.
9730         * <p>
9731         * Note that this method may be called after pre-layout phase if LayoutManager adds new
9732         * Views to the layout in pre-layout pass.
9733         * <p>
9734         * The default implementation returns an {@link ItemHolderInfo} which holds the bounds of
9735         * the View and the adapter change flags.
9736         *
9737         * @param state       The current State of RecyclerView which includes some useful data
9738         *                    about the layout that will be calculated.
9739         * @param viewHolder  The ViewHolder whose information should be recorded.
9740         * @param changeFlags Additional information about what changes happened in the Adapter
9741         *                    about the Item represented by this ViewHolder. For instance, if
9742         *                    item is deleted from the adapter, {@link #FLAG_REMOVED} will be set.
9743         * @param payloads    The payload list that was previously passed to
9744         *                    {@link Adapter#notifyItemChanged(int, Object)} or
9745         *                    {@link Adapter#notifyItemRangeChanged(int, int, Object)}.
9746         *
9747         * @return An ItemHolderInfo instance that preserves necessary information about the
9748         * ViewHolder. This object will be passed back to related <code>animate**</code> methods
9749         * after layout is complete.
9750         *
9751         * @see #recordPostLayoutInformation(State, ViewHolder)
9752         * @see #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9753         * @see #animateDisappearance(ViewHolder, ItemHolderInfo)
9754         * @see #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
9755         * @see #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9756         */
9757        public @NonNull ItemHolderInfo recordPreLayoutInformation(@NonNull State state,
9758                @NonNull ViewHolder viewHolder, @AdapterChanges int changeFlags,
9759                @NonNull List<Object> payloads) {
9760            return obtainHolderInfo().setFrom(viewHolder);
9761        }
9762
9763        /**
9764         * Called by the RecyclerView after the layout is complete. Item animator should record
9765         * necessary information about the View's final state.
9766         * <p>
9767         * The data returned from this method will be passed to the related <code>animate**</code>
9768         * methods.
9769         * <p>
9770         * The default implementation returns an {@link ItemHolderInfo} which holds the bounds of
9771         * the View.
9772         *
9773         * @param state      The current State of RecyclerView which includes some useful data about
9774         *                   the layout that will be calculated.
9775         * @param viewHolder The ViewHolder whose information should be recorded.
9776         *
9777         * @return An ItemHolderInfo that preserves necessary information about the ViewHolder.
9778         * This object will be passed back to related <code>animate**</code> methods when
9779         * RecyclerView decides how items should be animated.
9780         *
9781         * @see #recordPreLayoutInformation(State, ViewHolder, int, List)
9782         * @see #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9783         * @see #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9784         * @see #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
9785         * @see #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9786         */
9787        public @NonNull ItemHolderInfo recordPostLayoutInformation(@NonNull State state,
9788                @NonNull ViewHolder viewHolder) {
9789            return obtainHolderInfo().setFrom(viewHolder);
9790        }
9791
9792        /**
9793         * Called by the RecyclerView when a ViewHolder has disappeared from the layout.
9794         * <p>
9795         * This means that the View was a child of the LayoutManager when layout started but has
9796         * been removed by the LayoutManager. It might have been removed from the adapter or simply
9797         * become invisible due to other factors. You can distinguish these two cases by checking
9798         * the change flags that were passed to
9799         * {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9800         * <p>
9801         * If LayoutManager supports predictive animations, it might provide a target disappear
9802         * location for the View by laying it out in that location. When that happens,
9803         * RecyclerView will call {@link #recordPostLayoutInformation(State, ViewHolder)} and the
9804         * response of that call will be passed to this method as the <code>postLayoutInfo</code>.
9805         * <p>
9806         * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation
9807         * is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it
9808         * decides not to animate the view).
9809         *
9810         * @param viewHolder    The ViewHolder which should be animated
9811         * @param preLayoutInfo The information that was returned from
9812         *                      {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9813         * @param postLayoutInfo The information that was returned from
9814         *                       {@link #recordPostLayoutInformation(State, ViewHolder)}. Might be
9815         *                       null if the LayoutManager did not layout the item.
9816         *
9817         * @return true if a later call to {@link #runPendingAnimations()} is requested,
9818         * false otherwise.
9819         */
9820        public abstract boolean animateDisappearance(@NonNull ViewHolder viewHolder,
9821                @NonNull ItemHolderInfo preLayoutInfo, @Nullable ItemHolderInfo postLayoutInfo);
9822
9823        /**
9824         * Called by the RecyclerView when a ViewHolder is added to the layout.
9825         * <p>
9826         * In detail, this means that the ViewHolder was <b>not</b> a child when the layout started
9827         * but has  been added by the LayoutManager. It might be newly added to the adapter or
9828         * simply become visible due to other factors.
9829         * <p>
9830         * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation
9831         * is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it
9832         * decides not to animate the view).
9833         *
9834         * @param viewHolder     The ViewHolder which should be animated
9835         * @param preLayoutInfo  The information that was returned from
9836         *                       {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9837         *                       Might be null if Item was just added to the adapter or
9838         *                       LayoutManager does not support predictive animations or it could
9839         *                       not predict that this ViewHolder will become visible.
9840         * @param postLayoutInfo The information that was returned from {@link
9841         *                       #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9842         *
9843         * @return true if a later call to {@link #runPendingAnimations()} is requested,
9844         * false otherwise.
9845         */
9846        public abstract boolean animateAppearance(@NonNull ViewHolder viewHolder,
9847                @Nullable ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo);
9848
9849        /**
9850         * Called by the RecyclerView when a ViewHolder is present in both before and after the
9851         * layout and RecyclerView has not received a {@link Adapter#notifyItemChanged(int)} call
9852         * for it or a {@link Adapter#notifyDataSetChanged()} call.
9853         * <p>
9854         * This ViewHolder still represents the same data that it was representing when the layout
9855         * started but its position / size may be changed by the LayoutManager.
9856         * <p>
9857         * If the Item's layout position didn't change, RecyclerView still calls this method because
9858         * it does not track this information (or does not necessarily know that an animation is
9859         * not required). Your ItemAnimator should handle this case and if there is nothing to
9860         * animate, it should call {@link #dispatchAnimationFinished(ViewHolder)} and return
9861         * <code>false</code>.
9862         * <p>
9863         * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} when the animation
9864         * is complete (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it
9865         * decides not to animate the view).
9866         *
9867         * @param viewHolder     The ViewHolder which should be animated
9868         * @param preLayoutInfo  The information that was returned from
9869         *                       {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9870         * @param postLayoutInfo The information that was returned from {@link
9871         *                       #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9872         *
9873         * @return true if a later call to {@link #runPendingAnimations()} is requested,
9874         * false otherwise.
9875         */
9876        public abstract boolean animatePersistence(@NonNull ViewHolder viewHolder,
9877                @NonNull ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo);
9878
9879        /**
9880         * Called by the RecyclerView when an adapter item is present both before and after the
9881         * layout and RecyclerView has received a {@link Adapter#notifyItemChanged(int)} call
9882         * for it. This method may also be called when
9883         * {@link Adapter#notifyDataSetChanged()} is called and adapter has stable ids so that
9884         * RecyclerView could still rebind views to the same ViewHolders. If viewType changes when
9885         * {@link Adapter#notifyDataSetChanged()} is called, this method <b>will not</b> be called,
9886         * instead, {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)} will be
9887         * called for the new ViewHolder and the old one will be recycled.
9888         * <p>
9889         * If this method is called due to a {@link Adapter#notifyDataSetChanged()} call, there is
9890         * a good possibility that item contents didn't really change but it is rebound from the
9891         * adapter. {@link DefaultItemAnimator} will skip animating the View if its location on the
9892         * screen didn't change and your animator should handle this case as well and avoid creating
9893         * unnecessary animations.
9894         * <p>
9895         * When an item is updated, ItemAnimator has a chance to ask RecyclerView to keep the
9896         * previous presentation of the item as-is and supply a new ViewHolder for the updated
9897         * presentation (see: {@link #canReuseUpdatedViewHolder(ViewHolder)}.
9898         * This is useful if you don't know the contents of the Item and would like
9899         * to cross-fade the old and the new one ({@link DefaultItemAnimator} uses this technique).
9900         * <p>
9901         * When you are writing a custom item animator for your layout, it might be more performant
9902         * and elegant to re-use the same ViewHolder and animate the content changes manually.
9903         * <p>
9904         * When {@link Adapter#notifyItemChanged(int)} is called, the Item's view type may change.
9905         * If the Item's view type has changed or ItemAnimator returned <code>false</code> for
9906         * this ViewHolder when {@link #canReuseUpdatedViewHolder(ViewHolder)} was called, the
9907         * <code>oldHolder</code> and <code>newHolder</code> will be different ViewHolder instances
9908         * which represent the same Item. In that case, only the new ViewHolder is visible
9909         * to the LayoutManager but RecyclerView keeps old ViewHolder attached for animations.
9910         * <p>
9911         * ItemAnimator must call {@link #dispatchAnimationFinished(ViewHolder)} for each distinct
9912         * ViewHolder when their animation is complete
9913         * (or instantly call {@link #dispatchAnimationFinished(ViewHolder)} if it decides not to
9914         * animate the view).
9915         * <p>
9916         *  If oldHolder and newHolder are the same instance, you should call
9917         * {@link #dispatchAnimationFinished(ViewHolder)} <b>only once</b>.
9918         *
9919         * @param oldHolder     The ViewHolder before the layout is started, might be the same
9920         *                      instance with newHolder.
9921         * @param newHolder     The ViewHolder after the layout is finished, might be the same
9922         *                      instance with oldHolder.
9923         * @param preLayoutInfo  The information that was returned from
9924         *                       {@link #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9925         * @param postLayoutInfo The information that was returned from {@link
9926         *                       #recordPreLayoutInformation(State, ViewHolder, int, List)}.
9927         *
9928         * @return true if a later call to {@link #runPendingAnimations()} is requested,
9929         * false otherwise.
9930         */
9931        public abstract boolean animateChange(@NonNull ViewHolder oldHolder,
9932                @NonNull ViewHolder newHolder,
9933                @NonNull ItemHolderInfo preLayoutInfo, @NonNull ItemHolderInfo postLayoutInfo);
9934
9935        @AdapterChanges static int buildAdapterChangeFlagsForAnimations(ViewHolder viewHolder) {
9936            int flags = viewHolder.mFlags & (FLAG_INVALIDATED | FLAG_REMOVED | FLAG_CHANGED);
9937            if (viewHolder.isInvalid()) {
9938                return FLAG_INVALIDATED;
9939            }
9940            if ((flags & FLAG_INVALIDATED) == 0) {
9941                final int oldPos = viewHolder.getOldPosition();
9942                final int pos = viewHolder.getAdapterPosition();
9943                if (oldPos != NO_POSITION && pos != NO_POSITION && oldPos != pos){
9944                    flags |= FLAG_MOVED;
9945                }
9946            }
9947            return flags;
9948        }
9949
9950        /**
9951         * Called when there are pending animations waiting to be started. This state
9952         * is governed by the return values from
9953         * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9954         * animateAppearance()},
9955         * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
9956         * animateChange()}
9957         * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9958         * animatePersistence()}, and
9959         * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
9960         * animateDisappearance()}, which inform the RecyclerView that the ItemAnimator wants to be
9961         * called later to start the associated animations. runPendingAnimations() will be scheduled
9962         * to be run on the next frame.
9963         */
9964        abstract public void runPendingAnimations();
9965
9966        /**
9967         * Method called when an animation on a view should be ended immediately.
9968         * This could happen when other events, like scrolling, occur, so that
9969         * animating views can be quickly put into their proper end locations.
9970         * Implementations should ensure that any animations running on the item
9971         * are canceled and affected properties are set to their end values.
9972         * Also, {@link #dispatchAnimationFinished(ViewHolder)} should be called for each finished
9973         * animation since the animations are effectively done when this method is called.
9974         *
9975         * @param item The item for which an animation should be stopped.
9976         */
9977        abstract public void endAnimation(ViewHolder item);
9978
9979        /**
9980         * Method called when all item animations should be ended immediately.
9981         * This could happen when other events, like scrolling, occur, so that
9982         * animating views can be quickly put into their proper end locations.
9983         * Implementations should ensure that any animations running on any items
9984         * are canceled and affected properties are set to their end values.
9985         * Also, {@link #dispatchAnimationFinished(ViewHolder)} should be called for each finished
9986         * animation since the animations are effectively done when this method is called.
9987         */
9988        abstract public void endAnimations();
9989
9990        /**
9991         * Method which returns whether there are any item animations currently running.
9992         * This method can be used to determine whether to delay other actions until
9993         * animations end.
9994         *
9995         * @return true if there are any item animations currently running, false otherwise.
9996         */
9997        abstract public boolean isRunning();
9998
9999        /**
10000         * Method to be called by subclasses when an animation is finished.
10001         * <p>
10002         * For each call RecyclerView makes to
10003         * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
10004         * animateAppearance()},
10005         * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
10006         * animatePersistence()}, or
10007         * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
10008         * animateDisappearance()}, there
10009         * should
10010         * be a matching {@link #dispatchAnimationFinished(ViewHolder)} call by the subclass.
10011         * <p>
10012         * For {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
10013         * animateChange()}, sublcass should call this method for both the <code>oldHolder</code>
10014         * and <code>newHolder</code>  (if they are not the same instance).
10015         *
10016         * @param viewHolder The ViewHolder whose animation is finished.
10017         * @see #onAnimationFinished(ViewHolder)
10018         */
10019        public final void dispatchAnimationFinished(ViewHolder viewHolder) {
10020            onAnimationFinished(viewHolder);
10021            if (mListener != null) {
10022                mListener.onAnimationFinished(viewHolder);
10023            }
10024        }
10025
10026        /**
10027         * Called after {@link #dispatchAnimationFinished(ViewHolder)} is called by the
10028         * ItemAniamtor.
10029         *
10030         * @param viewHolder The ViewHolder whose animation is finished. There might still be other
10031         *                   animations running on this ViewHolder.
10032         * @see #dispatchAnimationFinished(ViewHolder)
10033         */
10034        public void onAnimationFinished(ViewHolder viewHolder) {
10035        }
10036
10037        /**
10038         * Method to be called by subclasses when an animation is started.
10039         * <p>
10040         * For each call RecyclerView makes to
10041         * {@link #animateAppearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
10042         * animateAppearance()},
10043         * {@link #animatePersistence(ViewHolder, ItemHolderInfo, ItemHolderInfo)
10044         * animatePersistence()}, or
10045         * {@link #animateDisappearance(ViewHolder, ItemHolderInfo, ItemHolderInfo)
10046         * animateDisappearance()}, there should be a matching
10047         * {@link #dispatchAnimationStarted(ViewHolder)} call by the subclass.
10048         * <p>
10049         * For {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)
10050         * animateChange()}, sublcass should call this method for both the <code>oldHolder</code>
10051         * and <code>newHolder</code> (if they are not the same instance).
10052         * <p>
10053         * If your ItemAnimator decides not to animate a ViewHolder, it should call
10054         * {@link #dispatchAnimationFinished(ViewHolder)} <b>without</b> calling
10055         * {@link #dispatchAnimationStarted(ViewHolder)}.
10056         *
10057         * @param viewHolder The ViewHolder whose animation is starting.
10058         * @see #onAnimationStarted(ViewHolder)
10059         */
10060        public final void dispatchAnimationStarted(ViewHolder viewHolder) {
10061            onAnimationStarted(viewHolder);
10062        }
10063
10064        /**
10065         * Called when a new animation is started on the given ViewHolder.
10066         *
10067         * @param viewHolder The ViewHolder which started animating. Note that the ViewHolder
10068         *                   might already be animating and this might be another animation.
10069         * @see #dispatchAnimationStarted(ViewHolder)
10070         */
10071        public void onAnimationStarted(ViewHolder viewHolder) {
10072
10073        }
10074
10075        /**
10076         * Like {@link #isRunning()}, this method returns whether there are any item
10077         * animations currently running. Addtionally, the listener passed in will be called
10078         * when there are no item animations running, either immediately (before the method
10079         * returns) if no animations are currently running, or when the currently running
10080         * animations are {@link #dispatchAnimationsFinished() finished}.
10081         *
10082         * <p>Note that the listener is transient - it is either called immediately and not
10083         * stored at all, or stored only until it is called when running animations
10084         * are finished sometime later.</p>
10085         *
10086         * @param listener A listener to be called immediately if no animations are running
10087         * or later when currently-running animations have finished. A null listener is
10088         * equivalent to calling {@link #isRunning()}.
10089         * @return true if there are any item animations currently running, false otherwise.
10090         */
10091        public final boolean isRunning(ItemAnimatorFinishedListener listener) {
10092            boolean running = isRunning();
10093            if (listener != null) {
10094                if (!running) {
10095                    listener.onAnimationsFinished();
10096                } else {
10097                    mFinishedListeners.add(listener);
10098                }
10099            }
10100            return running;
10101        }
10102
10103        /**
10104         * When an item is changed, ItemAnimator can decide whether it wants to re-use
10105         * the same ViewHolder for animations or RecyclerView should create a copy of the
10106         * item and ItemAnimator will use both to run the animation (e.g. cross-fade).
10107         * <p>
10108         * Note that this method will only be called if the {@link ViewHolder} still has the same
10109         * type ({@link Adapter#getItemViewType(int)}). Otherwise, ItemAnimator will always receive
10110         * both {@link ViewHolder}s in the
10111         * {@link #animateChange(ViewHolder, ViewHolder, ItemHolderInfo, ItemHolderInfo)} method.
10112         *
10113         * @param viewHolder The ViewHolder which represents the changed item's old content.
10114         *
10115         * @return True if RecyclerView should just rebind to the same ViewHolder or false if
10116         *         RecyclerView should create a new ViewHolder and pass this ViewHolder to the
10117         *         ItemAnimator to animate. Default implementation returns <code>true</code>.
10118         */
10119        public boolean canReuseUpdatedViewHolder(ViewHolder viewHolder) {
10120            return true;
10121        }
10122
10123        /**
10124         * This method should be called by ItemAnimator implementations to notify
10125         * any listeners that all pending and active item animations are finished.
10126         */
10127        public final void dispatchAnimationsFinished() {
10128            final int count = mFinishedListeners.size();
10129            for (int i = 0; i < count; ++i) {
10130                mFinishedListeners.get(i).onAnimationsFinished();
10131            }
10132            mFinishedListeners.clear();
10133        }
10134
10135        /**
10136         * Returns a new {@link ItemHolderInfo} which will be used to store information about the
10137         * ViewHolder. This information will later be passed into <code>animate**</code> methods.
10138         * <p>
10139         * You can override this method if you want to extend {@link ItemHolderInfo} and provide
10140         * your own instances.
10141         *
10142         * @return A new {@link ItemHolderInfo}.
10143         */
10144        public ItemHolderInfo obtainHolderInfo() {
10145            return new ItemHolderInfo();
10146        }
10147
10148        /**
10149         * The interface to be implemented by listeners to animation events from this
10150         * ItemAnimator. This is used internally and is not intended for developers to
10151         * create directly.
10152         */
10153        interface ItemAnimatorListener {
10154            void onAnimationFinished(ViewHolder item);
10155        }
10156
10157        /**
10158         * This interface is used to inform listeners when all pending or running animations
10159         * in an ItemAnimator are finished. This can be used, for example, to delay an action
10160         * in a data set until currently-running animations are complete.
10161         *
10162         * @see #isRunning(ItemAnimatorFinishedListener)
10163         */
10164        public interface ItemAnimatorFinishedListener {
10165            void onAnimationsFinished();
10166        }
10167
10168        /**
10169         * A simple data structure that holds information about an item's bounds.
10170         * This information is used in calculating item animations. Default implementation of
10171         * {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int, List)} and
10172         * {@link #recordPostLayoutInformation(RecyclerView.State, ViewHolder)} returns this data
10173         * structure. You can extend this class if you would like to keep more information about
10174         * the Views.
10175         * <p>
10176         * If you want to provide your own implementation butstill use `super` methods to record
10177         * basic information, you can override {@link #obtainHolderInfo()} to provide your own
10178         * instances.
10179         */
10180        public static class ItemHolderInfo {
10181
10182            /**
10183             * The left edge of the View (excluding decorations)
10184             */
10185            public int left;
10186
10187            /**
10188             * The top edge of the View (excluding decorations)
10189             */
10190            public int top;
10191
10192            /**
10193             * The right edge of the View (excluding decorations)
10194             */
10195            public int right;
10196
10197            /**
10198             * The bottom edge of the View (excluding decorations)
10199             */
10200            public int bottom;
10201
10202            /**
10203             * The change flags that were passed to
10204             * {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int, List)}.
10205             */
10206            @AdapterChanges
10207            public int changeFlags;
10208
10209            public ItemHolderInfo() {
10210            }
10211
10212            /**
10213             * Sets the {@link #left}, {@link #top}, {@link #right} and {@link #bottom} values from
10214             * the given ViewHolder. Clears all {@link #changeFlags}.
10215             *
10216             * @param holder The ViewHolder whose bounds should be copied.
10217             * @return This {@link ItemHolderInfo}
10218             */
10219            public ItemHolderInfo setFrom(RecyclerView.ViewHolder holder) {
10220                return setFrom(holder, 0);
10221            }
10222
10223            /**
10224             * Sets the {@link #left}, {@link #top}, {@link #right} and {@link #bottom} values from
10225             * the given ViewHolder and sets the {@link #changeFlags} to the given flags parameter.
10226             *
10227             * @param holder The ViewHolder whose bounds should be copied.
10228             * @param flags  The adapter change flags that were passed into
10229             *               {@link #recordPreLayoutInformation(RecyclerView.State, ViewHolder, int,
10230             *               List)}.
10231             * @return This {@link ItemHolderInfo}
10232             */
10233            public ItemHolderInfo setFrom(RecyclerView.ViewHolder holder,
10234                    @AdapterChanges int flags) {
10235                final View view = holder.itemView;
10236                this.left = view.getLeft();
10237                this.top = view.getTop();
10238                this.right = view.getRight();
10239                this.bottom = view.getBottom();
10240                return this;
10241            }
10242        }
10243    }
10244
10245    @Override
10246    protected int getChildDrawingOrder(int childCount, int i) {
10247        if (mChildDrawingOrderCallback == null) {
10248            return super.getChildDrawingOrder(childCount, i);
10249        } else {
10250            return mChildDrawingOrderCallback.onGetChildDrawingOrder(childCount, i);
10251        }
10252    }
10253
10254    /**
10255     * A callback interface that can be used to alter the drawing order of RecyclerView children.
10256     * <p>
10257     * It works using the {@link ViewGroup#getChildDrawingOrder(int, int)} method, so any case
10258     * that applies to that method also applies to this callback. For example, changing the drawing
10259     * order of two views will not have any effect if their elevation values are different since
10260     * elevation overrides the result of this callback.
10261     */
10262    public interface ChildDrawingOrderCallback {
10263        /**
10264         * Returns the index of the child to draw for this iteration. Override this
10265         * if you want to change the drawing order of children. By default, it
10266         * returns i.
10267         *
10268         * @param i The current iteration.
10269         * @return The index of the child to draw this iteration.
10270         *
10271         * @see RecyclerView#setChildDrawingOrderCallback(RecyclerView.ChildDrawingOrderCallback)
10272         */
10273        int onGetChildDrawingOrder(int childCount, int i);
10274    }
10275}
10276