对于RecyclerView的使用,大家可以查看将替代ListView的RecyclerView 的使用详解(一),单单从代码结构来说RecyclerView确实比ListView优化了很多,也简化了我们编写代码量,但是有一个问题会导致开发者不会去用它,更比说替换ListView了,我不知道使用过RecyclerView的人有没有进一步查看,RecyclerView没有提供Item的点击事件,我们使用列表不仅仅为了显示数据,同时也可以能会交互,所以RecyclerView这个问题导致基本没有人用它,我清楚谷歌是怎么想的,不过RecyclerView也并没有把所有的路给堵死,需要我们写代码来实现Item的点击事件,我们都知道RecyclerView里面新加了ViewHolder这个静态抽象类,这个类里面有一个方法getPosition()可以返回当前ViewHolder实例的位置,实现onItemClick就是使用它来做的,下面有两种方法来实现:
第一种:不修改源码
这种方法不修改源码,问题是只能在RecyclerView.Adapter中实现ItemClick事件
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View itemView) {
super(itemView);
itemView.setonClickListener(new onClickListener() {
@Override
public void onClick(View v) {
Log.e("jwzhangjie", "当前点击的位置:"+getPosition());
}
});
}
}
这种方式直观上看起来不太好,不过也可以实现ItemClick事件。
第二种方法:修改RecyclerView源码
1、把在RecyClerView类里面定义OnItemClickListener接口
public interface onItemClickListener {
void onItemClick(View view, int position);
}
public static onItemClickListener monItemClickListener = null;
public void setonItemClickListener(onItemClickListener listener) {
monItemClickListener = listener;
}
public final onItemClickListener getonItemClickListener() {
return mOnItemClickListener;
}
2、在RecyclerView中的抽象类ViewHolder中添加View的点击事件
public static abstract class ViewHolder implements OnClickListener{
public final View itemView;
int mPosition = NO_POSITION;
int mOldPosition = NO_POSITION;
long mItemId = NO_ID;
int mItemViewType = INVALID_TYPE;
static final int FLAG_BOUND = 1 << 0;
static final int FLAG_UPDATe = 1 << 1;
static final int FLAG_INVALID = 1 << 2;
static final int FLAG_REMOVED = 1 << 3;
static final int FLAG_NOT_RECYCLABLE = 1 << 4;
private int mFlags;
private int mIsRecyclableCount = 0;
// If non-null, view is currently considered scrap and may be reused for other data by the
// scrap container.
private Recycler mScrapContainer = null;
@Override
public void onClick(View v) {
if (monItemClickListener != null) {
mOnItemClickListener.onItemClick(itemView, getPosition());
}
}
public ViewHolder(View itemView) {
if (itemView == null) {
throw new IllegalArgumentException("itemView may not be null");
}
this.itemView = itemView;
this.itemView.setonClickListener(this);
}
void offsetPosition(int offset) {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
mPosition += offset;
}
void clearOldPosition() {
mOldPosition = NO_POSITION;
}
public final int getPosition() {
return mOldPosition == NO_POSITION ? mPosition : mOldPosition;
}
public final long getItemId() {
return mItemId;
}
public final int getItemViewType() {
return mItemViewType;
}
boolean isScrap() {
return mScrapContainer != null;
}
void unScrap() {
mScrapContainer.unscrapView(this);
mScrapContainer = null;
}
void setScrapContainer(Recycler recycler) {
mScrapContainer = recycler;
}
boolean isInvalid() {
return (mFlags & FLAG_INVALID) != 0;
}
boolean needsUpdate() {
return (mFlags & FLAG_UPDATE) != 0;
}
boolean isBound() {
return (mFlags & FLAG_BOUND) != 0;
}
boolean isRemoved() {
return (mFlags & FLAG_REMOVED) != 0;
}
void setFlags(int flags, int mask) {
mFlags = (mFlags & ~mask) | (flags & mask);
}
void addFlags(int flags) {
mFlags |= flags;
}
void clearFlagsForSharedPool() {
mFlags = 0;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ViewHolder{" +
Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId);
if (isScrap()) sb.append(" scrap");
if (isInvalid()) sb.append(" invalid");
if (!isBound()) sb.append(" unbound");
if (needsUpdate()) sb.append(" update");
if (isRemoved()) sb.append(" removed");
sb.append("}");
return sb.toString();
}
3、完成上面的步骤,就可以使用RecyclerView来完成itemClick事件了
cashAccountList.setonItemClickListener(new onItemClickListener() {
@Override
public void onItemClick(View view, int position) {
AppLog.e("position: "+position);
}
});
下面是完整的RecyclerView源码:
package android.support.v7.widget;
import android.content.Context;
import android.database.Observable;
import android.graphics.Canvas;
import android.graphics.PointF;
import android.graphics.Rect;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v4.util.Pools;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.EdgeEffectCompat;
import android.support.v4.widget.ScrollerCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.FocusFinder;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Interpolator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RecyclerView extends ViewGroup {
private static final String TAG = "RecyclerView";
private static final boolean DEBUG = false;
private static final boolean ENABLE_PREDICTIVE_ANIMATIONS = false;
private static final boolean DISPATCH_TEMP_DETACH = false;
public static final int HORIZonTAL = 0;
public static final int VERTICAL = 1;
public static final int NO_POSITION = -1;
public static final long NO_ID = -1;
public static final int INVALID_TYPE = -1;
private static final int MAX_SCROLL_DURATION = 2000;
private final RecyclerViewDataObserver mObserver = new RecyclerViewDataObserver();
private final Recycler mRecycler = new Recycler();
private SavedState mPendingSavedState;
private final Runnable mUpdateChildViewsRunnable = new Runnable() {
public void run() {
if (mPendingUpdates.isEmpty()) {
return;
}
eatRequestLayout();
updateChildViews();
resumeRequestLayout(true);
}
};
private final Rect mTempRect = new Rect();
private final ArrayList mPendingUpdates = new ArrayList();
private final ArrayList mPendingLayoutUpdates = new ArrayList();
private Pools.Pool mUpdateOpPool = new Pools.SimplePool(UpdateOp.POOL_SIZE);
private Adapter mAdapter;
private LayoutManager mLayout;
private RecyclerListener mRecyclerListener;
private final ArrayList mItemDecorations = new ArrayList();
private final ArrayList monItemTouchListeners =
new ArrayList();
private onItemTouchListener mActiveOnItemTouchListener;
private boolean mIsAttached;
private boolean mHasFixedSize;
private boolean mFirstLayoutComplete;
private boolean mEatRequestLayout;
private boolean mLayoutRequestEaten;
private boolean mAdapterUpdateDuringMeasure;
private final boolean mPostUpdatesOnAnimation;
private EdgeEffectCompat mLeftGlow, mTopGlow, mRightGlow, mBottomGlow;
ItemAnimator mItemAnimator = new DefaultItemAnimator();
private static final int INVALID_POINTER = -1;
public static final int SCROLL_STATE_IDLE = 0;
public static final int SCROLL_STATE_DRAGGING = 1;
public static final int SCROLL_STATE_SETTLING = 2;
// Touch/scrolling handling
private int mScrollState = SCROLL_STATE_IDLE;
private int mScrollPointerId = INVALID_POINTER;
private VelocityTracker mVelocityTracker;
private int mInitialTouchX;
private int mInitialTouchY;
private int mLastTouchX;
private int mLastTouchY;
private final int mTouchSlop;
private final int mMinFlingVelocity;
private final int mMaxFlingVelocity;
private final ViewFlinger mViewFlinger = new ViewFlinger();
private final State mState = new State();
private onScrollListener mScrollListener;
// For use in item animations
boolean mItemsAddedOrRemoved = false;
boolean mItemsChanged = false;
int mAnimatingViewIndex = -1;
int mNumAnimatingViews = 0;
boolean mInPreLayout = false;
private ItemAnimator.ItemAnimatorListener mItemAnimatorListener =
new ItemAnimatorRestoreListener();
private boolean mPostedAnimatorRunner = false;
private Runnable mItemAnimatorRunner = new Runnable() {
@Override
public void run() {
if (mItemAnimator != null) {
mItemAnimator.runPendingAnimations();
}
mPostedAnimatorRunner = false;
}
};
private static final Interpolator sQuinticInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
public RecyclerView(Context context) {
this(context, null);
}
public RecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final int version = Build.VERSION.SDK_INT;
mPostUpdatesonAnimation = version >= 16;
final ViewConfiguration vc = ViewConfiguration.get(context);
mTouchSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity();
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
mItemAnimator.setListener(mItemAnimatorListener);
}
public void setHasFixedSize(boolean hasFixedSize) {
mHasFixedSize = hasFixedSize;
}
public boolean hasFixedSize() {
return mHasFixedSize;
}
public void setAdapter(Adapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterAdapterDataObserver(mObserver);
}
// end all running animations
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
// Since animations are ended, mLayout.children should be equal to recyclerView.children.
// This may not be true if item animator's end does not work as expected. (e.g. not release
// children instantly). It is safer to use mLayout's child count.
if (mLayout != null) {
mLayout.removeAndRecycleAllViews(mRecycler);
mLayout.removeAndRecycleScrapInt(mRecycler, true);
}
final Adapter oldAdapter = mAdapter;
mAdapter = adapter;
if (adapter != null) {
adapter.registerAdapterDataObserver(mObserver);
}
if (mLayout != null) {
mLayout.onAdapterChanged(oldAdapter, mAdapter);
}
mRecycler.onAdapterChanged(oldAdapter, mAdapter);
mState.mStructureChanged = true;
markKnownViewsInvalid();
requestLayout();
}
public Adapter getAdapter() {
return mAdapter;
}
public void setRecyclerListener(RecyclerListener listener) {
mRecyclerListener = listener;
}
public void setLayoutManager(LayoutManager layout) {
if (layout == mLayout) {
return;
}
mRecycler.clear();
removeAllViews();
if (mLayout != null) {
if (mIsAttached) {
mLayout.onDetachedFromWindow(this);
}
mLayout.mRecyclerView = null;
}
mLayout = layout;
if (layout != null) {
if (layout.mRecyclerView != null) {
throw new IllegalArgumentException("LayoutManager " + layout +
" is already attached to a RecyclerView: " + layout.mRecyclerView);
}
layout.mRecyclerView = this;
if (mIsAttached) {
mLayout.onAttachedToWindow(this);
}
}
requestLayout();
}
@Override
protected Parcelable onSaveInstanceState() {
SavedState state = new SavedState(super.onSaveInstanceState());
if (mPendingSavedState != null) {
state.copyFrom(mPendingSavedState);
} else if (mLayout != null) {
state.mLayoutState = mLayout.onSaveInstanceState();
} else {
state.mLayoutState = null;
}
return state;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
mPendingSavedState = (SavedState) state;
super.onRestoreInstanceState(mPendingSavedState.getSuperState());
if (mLayout != null && mPendingSavedState.mLayoutState != null) {
mLayout.onRestoreInstanceState(mPendingSavedState.mLayoutState);
}
}
private void addAnimatingView(View view) {
boolean alreadyAdded = false;
if (mNumAnimatingViews > 0) {
for (int i = mAnimatingViewIndex; i < getChildCount(); ++i) {
if (getChildAt(i) == view) {
alreadyAdded = true;
break;
}
}
}
if (!alreadyAdded) {
if (mNumAnimatingViews == 0) {
mAnimatingViewIndex = getChildCount();
}
++mNumAnimatingViews;
addView(view);
}
mRecycler.unscrapView(getChildViewHolder(view));
}
private void removeAnimatingView(View view) {
if (mNumAnimatingViews > 0) {
for (int i = mAnimatingViewIndex; i < getChildCount(); ++i) {
if (getChildAt(i) == view) {
removeViewAt(i);
--mNumAnimatingViews;
if (mNumAnimatingViews == 0) {
mAnimatingViewIndex = -1;
}
mRecycler.recycleView(view);
return;
}
}
}
}
private View getAnimatingView(int position, int type) {
if (mNumAnimatingViews > 0) {
for (int i = mAnimatingViewIndex; i < getChildCount(); ++i) {
final View view = getChildAt(i);
ViewHolder holder = getChildViewHolder(view);
if (holder.getPosition() == position &&
( type == INVALID_TYPE || holder.getItemViewType() == type)) {
return view;
}
}
}
return null;
}
public LayoutManager getLayoutManager() {
return mLayout;
}
public RecycledViewPool getRecycledViewPool() {
return mRecycler.getRecycledViewPool();
}
public void setRecycledViewPool(RecycledViewPool pool) {
mRecycler.setRecycledViewPool(pool);
}
public void setItemViewCacheSize(int size) {
mRecycler.setViewCacheSize(size);
}
public int getScrollState() {
return mScrollState;
}
private void setScrollState(int state) {
if (state == mScrollState) {
return;
}
mScrollState = state;
if (state != SCROLL_STATE_SETTLING) {
stopScroll();
}
if (mScrollListener != null) {
mScrollListener.onScrollStateChanged(state);
}
}
public void addItemDecoration(ItemDecoration decor, int index) {
if (mItemDecorations.isEmpty()) {
setWillNotDraw(false);
}
if (index < 0) {
mItemDecorations.add(decor);
} else {
mItemDecorations.add(index, decor);
}
markItemDecorInsetsDirty();
requestLayout();
}
public void addItemDecoration(ItemDecoration decor) {
addItemDecoration(decor, -1);
}
public void removeItemDecoration(ItemDecoration decor) {
mItemDecorations.remove(decor);
if (mItemDecorations.isEmpty()) {
setWillNotDraw(ViewCompat.getOverScrollMode(this) == ViewCompat.OVER_SCROLL_NEVER);
}
markItemDecorInsetsDirty();
requestLayout();
}
public void setonScrollListener(onScrollListener listener) {
mScrollListener = listener;
}
public void scrollToPosition(int position) {
stopScroll();
mLayout.scrollToPosition(position);
awakenScrollBars();
}
public void smoothScrollToPosition(int position) {
mLayout.smoothScrollToPosition(this, mState, position);
}
@Override
public void scrollTo(int x, int y) {
throw new UnsupportedOperationException(
"RecyclerView does not support scrolling to an absolute position.");
}
@Override
public void scrollBy(int x, int y) {
if (mLayout == null) {
throw new IllegalStateException("Cannot scroll without a LayoutManager set. " +
"Call setLayoutManager with a non-null argument.");
}
final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
final boolean canScrollVertical = mLayout.canScrollVertically();
if (canScrollHorizontal || canScrollVertical) {
scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0);
}
}
private void consumePendingUpdateOperations() {
if (mItemAnimator != null) {
mItemAnimator.endAnimations();
}
if (mPendingUpdates.size() > 0) {
mUpdateChildViewsRunnable.run();
}
}
void scrollByInternal(int x, int y) {
int overscrollX = 0, overscrollY = 0;
consumePendingUpdateOperations();
if (mAdapter != null) {
eatRequestLayout();
if (x != 0) {
final int hresult = mLayout.scrollHorizontallyBy(x, mRecycler, mState);
overscrollX = x - hresult;
}
if (y != 0) {
final int vresult = mLayout.scrollVerticallyBy(y, mRecycler, mState);
overscrollY = y - vresult;
}
resumeRequestLayout(false);
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (ViewCompat.getOverScrollMode(this) != ViewCompat.OVER_SCROLL_NEVER) {
pullGlows(overscrollX, overscrollY);
}
if (mScrollListener != null && (x != 0 || y != 0)) {
mScrollListener.onScrolled(x, y);
}
if (!awakenScrollBars()) {
invalidate();
}
}
@Override
protected int computeHorizontalScrollOffset() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollOffset(mState)
: 0;
}
@Override
protected int computeHorizontalScrollExtent() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollExtent(mState) : 0;
}
@Override
protected int computeHorizontalScrollRange() {
return mLayout.canScrollHorizontally() ? mLayout.computeHorizontalScrollRange(mState) : 0;
}
@Override
protected int computeVerticalScrollOffset() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollOffset(mState) : 0;
}
@Override
protected int computeVerticalScrollExtent() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollExtent(mState) : 0;
}
@Override
protected int computeVerticalScrollRange() {
return mLayout.canScrollVertically() ? mLayout.computeVerticalScrollRange(mState) : 0;
}
void eatRequestLayout() {
if (!mEatRequestLayout) {
mEatRequestLayout = true;
mLayoutRequestEaten = false;
}
}
void resumeRequestLayout(boolean performLayoutChildren) {
if (mEatRequestLayout) {
if (performLayoutChildren && mLayoutRequestEaten &&
mLayout != null && mAdapter != null) {
dispatchLayout();
}
mEatRequestLayout = false;
mLayoutRequestEaten = false;
}
}
public void smoothScrollBy(int dx, int dy) {
if (dx != 0 || dy != 0) {
mViewFlinger.smoothScrollBy(dx, dy);
}
}
public boolean fling(int velocityX, int velocityY) {
if (Math.abs(velocityX) < mMinFlingVelocity) {
velocityX = 0;
}
if (Math.abs(velocityY) < mMinFlingVelocity) {
velocityY = 0;
}
velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity));
velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity));
if (velocityX != 0 || velocityY != 0) {
mViewFlinger.fling(velocityX, velocityY);
return true;
}
return false;
}
public void stopScroll() {
mViewFlinger.stop();
mLayout.stopSmoothScroller();
}
private void pullGlows(int overscrollX, int overscrollY) {
if (overscrollX < 0) {
if (mLeftGlow == null) {
mLeftGlow = new EdgeEffectCompat(getContext());
mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
}
mLeftGlow.onPull(-overscrollX / (float) getWidth());
} else if (overscrollX > 0) {
if (mRightGlow == null) {
mRightGlow = new EdgeEffectCompat(getContext());
mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
}
mRightGlow.onPull(overscrollX / (float) getWidth());
}
if (overscrollY < 0) {
if (mTopGlow == null) {
mTopGlow = new EdgeEffectCompat(getContext());
mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
}
mTopGlow.onPull(-overscrollY / (float) getHeight());
} else if (overscrollY > 0) {
if (mBottomGlow == null) {
mBottomGlow = new EdgeEffectCompat(getContext());
mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
}
mBottomGlow.onPull(overscrollY / (float) getHeight());
}
if (overscrollX != 0 || overscrollY != 0) {
ViewCompat.postInvalidateonAnimation(this);
}
}
private void releaseGlows() {
boolean needsInvalidate = false;
if (mLeftGlow != null) needsInvalidate = mLeftGlow.onRelease();
if (mTopGlow != null) needsInvalidate |= mTopGlow.onRelease();
if (mRightGlow != null) needsInvalidate |= mRightGlow.onRelease();
if (mBottomGlow != null) needsInvalidate |= mBottomGlow.onRelease();
if (needsInvalidate) {
ViewCompat.postInvalidateonAnimation(this);
}
}
void absorbGlows(int velocityX, int velocityY) {
if (velocityX < 0) {
if (mLeftGlow == null) {
mLeftGlow = new EdgeEffectCompat(getContext());
mLeftGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
}
mLeftGlow.onAbsorb(-velocityX);
} else if (velocityX > 0) {
if (mRightGlow == null) {
mRightGlow = new EdgeEffectCompat(getContext());
mRightGlow.setSize(getMeasuredHeight() - getPaddingTop() - getPaddingBottom(),
getMeasuredWidth() - getPaddingLeft() - getPaddingRight());
}
mRightGlow.onAbsorb(velocityX);
}
if (velocityY < 0) {
if (mTopGlow == null) {
mTopGlow = new EdgeEffectCompat(getContext());
mTopGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
}
mTopGlow.onAbsorb(-velocityY);
} else if (velocityY > 0) {
if (mBottomGlow == null) {
mBottomGlow = new EdgeEffectCompat(getContext());
mBottomGlow.setSize(getMeasuredWidth() - getPaddingLeft() - getPaddingRight(),
getMeasuredHeight() - getPaddingTop() - getPaddingBottom());
}
mBottomGlow.onAbsorb(velocityY);
}
if (velocityX != 0 || velocityY != 0) {
ViewCompat.postInvalidateonAnimation(this);
}
}
// Focus handling
@Override
public View focusSearch(View focused, int direction) {
View result = mLayout.onInterceptFocusSearch(focused, direction);
if (result != null) {
return result;
}
final FocusFinder ff = FocusFinder.getInstance();
result = ff.findNextFocus(this, focused, direction);
if (result == null && mAdapter != null) {
eatRequestLayout();
result = mLayout.onFocusSearchFailed(focused, direction, mRecycler, mState);
resumeRequestLayout(false);
}
return result != null ? result : super.focusSearch(focused, direction);
}
@Override
public void requestChildFocus(View child, View focused) {
if (!mLayout.onRequestChildFocus(this, child, focused)) {
mTempRect.set(0, 0, focused.getWidth(), focused.getHeight());
offsetDescendantRectToMyCoords(focused, mTempRect);
offsetRectIntoDescendantCoords(child, mTempRect);
requestChildRectangleonScreen(child, mTempRect, !mFirstLayoutComplete);
}
super.requestChildFocus(child, focused);
}
@Override
public boolean requestChildRectangleonScreen(View child, Rect rect, boolean immediate) {
return mLayout.requestChildRectangleonScreen(this, child, rect, immediate);
}
@Override
public void addFocusables(ArrayList views, int direction, int focusableMode) {
if (!mLayout.onAddFocusables(this, views, direction, focusableMode)) {
super.addFocusables(views, direction, focusableMode);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mIsAttached = true;
mFirstLayoutComplete = false;
if (mLayout != null) {
mLayout.onAttachedToWindow(this);
}
mPostedAnimatorRunner = false;
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mFirstLayoutComplete = false;
stopScroll();
// TODO Mark what our target position was if relevant, then we can jump there
// on reattach.
mIsAttached = false;
if (mLayout != null) {
mLayout.onDetachedFromWindow(this);
}
removeCallbacks(mItemAnimatorRunner);
}
public void addonItemTouchListener(onItemTouchListener listener) {
mOnItemTouchListeners.add(listener);
}
public void removeonItemTouchListener(onItemTouchListener listener) {
mOnItemTouchListeners.remove(listener);
if (mActiveonItemTouchListener == listener) {
mActiveonItemTouchListener = null;
}
}
private boolean dispatchonItemTouchIntercept(MotionEvent e) {
final int action = e.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_DOWN) {
mActiveonItemTouchListener = null;
}
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final onItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e) && action != MotionEvent.ACTION_CANCEL) {
mActiveonItemTouchListener = listener;
return true;
}
}
return false;
}
private boolean dispatchonItemTouch(MotionEvent e) {
final int action = e.getAction();
if (mActiveonItemTouchListener != null) {
if (action == MotionEvent.ACTION_DOWN) {
// Stale state from a previous gesture, we're starting a new one. Clear it.
mActiveonItemTouchListener = null;
} else {
mActiveOnItemTouchListener.onTouchEvent(this, e);
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
// Clean up for the next gesture.
mActiveonItemTouchListener = null;
}
return true;
}
}
// Listeners will have already received the ACTION_DOWN via dispatchonItemTouchIntercept
// as called from onInterceptTouchEvent; skip it.
if (action != MotionEvent.ACTION_DOWN) {
final int listenerCount = mOnItemTouchListeners.size();
for (int i = 0; i < listenerCount; i++) {
final onItemTouchListener listener = mOnItemTouchListeners.get(i);
if (listener.onInterceptTouchEvent(this, e)) {
mActiveonItemTouchListener = listener;
return true;
}
}
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
if (dispatchonItemTouchIntercept(e)) {
cancelTouch();
return true;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(e);
final int action = MotionEventCompat.getActionMasked(e);
final int actionIndex = MotionEventCompat.getActionIndex(e);
switch (action) {
case MotionEvent.ACTION_DOWN:
mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
if (mScrollState == SCROLL_STATE_SETTLING) {
getParent().requestDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
}
break;
case MotionEventCompat.ACTION_POINTER_DOWN:
mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
break;
case MotionEvent.ACTION_MOVE: {
final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id " +
mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
if (mScrollState != SCROLL_STATE_DRAGGING) {
final int dx = x - mInitialTouchX;
final int dy = y - mInitialTouchY;
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1);
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1);
startScroll = true;
}
if (startScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
}
}
} break;
case MotionEventCompat.ACTION_POINTER_UP: {
onPointerUp(e);
} break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.clear();
} break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
}
}
return mScrollState == SCROLL_STATE_DRAGGING;
}
@Override
public boolean onTouchEvent(MotionEvent e) {
if (dispatchonItemTouch(e)) {
cancelTouch();
return true;
}
final boolean canScrollHorizontally = mLayout.canScrollHorizontally();
final boolean canScrollVertically = mLayout.canScrollVertically();
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(e);
final int action = MotionEventCompat.getActionMasked(e);
final int actionIndex = MotionEventCompat.getActionIndex(e);
switch (action) {
case MotionEvent.ACTION_DOWN: {
mScrollPointerId = MotionEventCompat.getPointerId(e, 0);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
} break;
case MotionEventCompat.ACTION_POINTER_DOWN: {
mScrollPointerId = MotionEventCompat.getPointerId(e, actionIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, actionIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, actionIndex) + 0.5f);
} break;
case MotionEvent.ACTION_MOVE: {
final int index = MotionEventCompat.findPointerIndex(e, mScrollPointerId);
if (index < 0) {
Log.e(TAG, "Error processing scroll; pointer index for id " +
mScrollPointerId + " not found. Did any MotionEvents get skipped?");
return false;
}
final int x = (int) (MotionEventCompat.getX(e, index) + 0.5f);
final int y = (int) (MotionEventCompat.getY(e, index) + 0.5f);
if (mScrollState != SCROLL_STATE_DRAGGING) {
final int dx = x - mInitialTouchX;
final int dy = y - mInitialTouchY;
boolean startScroll = false;
if (canScrollHorizontally && Math.abs(dx) > mTouchSlop) {
mLastTouchX = mInitialTouchX + mTouchSlop * (dx < 0 ? -1 : 1);
startScroll = true;
}
if (canScrollVertically && Math.abs(dy) > mTouchSlop) {
mLastTouchY = mInitialTouchY + mTouchSlop * (dy < 0 ? -1 : 1);
startScroll = true;
}
if (startScroll) {
getParent().requestDisallowInterceptTouchEvent(true);
setScrollState(SCROLL_STATE_DRAGGING);
}
}
if (mScrollState == SCROLL_STATE_DRAGGING) {
final int dx = x - mLastTouchX;
final int dy = y - mLastTouchY;
scrollByInternal(canScrollHorizontally ? -dx : 0,
canScrollVertically ? -dy : 0);
}
mLastTouchX = x;
mLastTouchY = y;
} break;
case MotionEventCompat.ACTION_POINTER_UP: {
onPointerUp(e);
} break;
case MotionEvent.ACTION_UP: {
mVelocityTracker.computeCurrentVelocity(1000, mMaxFlingVelocity);
final float xvel = canScrollHorizontally ?
-VelocityTrackerCompat.getXVelocity(mVelocityTracker, mScrollPointerId) : 0;
final float yvel = canScrollVertically ?
-VelocityTrackerCompat.getYVelocity(mVelocityTracker, mScrollPointerId) : 0;
if (!((xvel != 0 || yvel != 0) && fling((int) xvel, (int) yvel))) {
setScrollState(SCROLL_STATE_IDLE);
}
mVelocityTracker.clear();
releaseGlows();
} break;
case MotionEvent.ACTION_CANCEL: {
cancelTouch();
} break;
}
return true;
}
private void cancelTouch() {
mVelocityTracker.clear();
releaseGlows();
setScrollState(SCROLL_STATE_IDLE);
}
private void onPointerUp(MotionEvent e) {
final int actionIndex = MotionEventCompat.getActionIndex(e);
if (MotionEventCompat.getPointerId(e, actionIndex) == mScrollPointerId) {
// Pick a new pointer to pick up the slack.
final int newIndex = actionIndex == 0 ? 1 : 0;
mScrollPointerId = MotionEventCompat.getPointerId(e, newIndex);
mInitialTouchX = mLastTouchX = (int) (MotionEventCompat.getX(e, newIndex) + 0.5f);
mInitialTouchY = mLastTouchY = (int) (MotionEventCompat.getY(e, newIndex) + 0.5f);
}
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
if (mAdapterUpdateDuringMeasure) {
eatRequestLayout();
updateChildViews();
mAdapterUpdateDuringMeasure = false;
resumeRequestLayout(false);
}
if (mAdapter != null) {
mState.mItemCount = mAdapter.getItemCount();
}
mLayout.onMeasure(mRecycler, mState, widthSpec, heightSpec);
final int widthSize = getMeasuredWidth();
final int heightSize = getMeasuredHeight();
if (mLeftGlow != null) mLeftGlow.setSize(heightSize, widthSize);
if (mTopGlow != null) mTopGlow.setSize(widthSize, heightSize);
if (mRightGlow != null) mRightGlow.setSize(heightSize, widthSize);
if (mBottomGlow != null) mBottomGlow.setSize(widthSize, heightSize);
}
public void setItemAnimator(ItemAnimator animator) {
if (mItemAnimator != null) {
mItemAnimator.setListener(null);
}
mItemAnimator = animator;
if (mItemAnimator != null) {
mItemAnimator.setListener(mItemAnimatorListener);
}
}
public ItemAnimator getItemAnimator() {
return mItemAnimator;
}
private void postAnimationRunner() {
if (!mPostedAnimatorRunner && mIsAttached) {
ViewCompat.postonAnimation(this, mItemAnimatorRunner);
mPostedAnimatorRunner = true;
}
}
private boolean predictiveItemAnimationsEnabled() {
return (mItemAnimator != null && mLayout.supportsPredictiveItemAnimations());
}
void dispatchLayout() {
if (mAdapter == null) {
Log.e(TAG, "No adapter attached; skipping layout");
return;
}
eatRequestLayout();
// simple animations are a subset of advanced animations (which will cause a
// prelayout step)
boolean animateChangesSimple = mItemAnimator != null && mItemsAddedOrRemoved
&& !mItemsChanged;
final boolean animateChangesAdvanced = ENABLE_PREDICTIVE_ANIMATIONS &&
animateChangesSimple && predictiveItemAnimationsEnabled();
mItemsAddedOrRemoved = mItemsChanged = false;
ArrayMap appearingViewInitialBounds = null;
mState.mInPreLayout = animateChangesAdvanced;
mState.mItemCount = mAdapter.getItemCount();
if (animateChangesSimple) {
// Step 0: Find out where all non-removed items are, pre-layout
mState.mPreLayoutHolderMap.clear();
mState.mPostLayoutHolderMap.clear();
int count = getChildCount();
for (int i = 0; i < count; ++i) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
final View view = holder.itemView;
mState.mPreLayoutHolderMap.put(holder, new ItemHolderInfo(holder,
view.getLeft(), view.getTop(), view.getRight(), view.getBottom(),
holder.mPosition));
}
}
if (animateChangesAdvanced) {
// Step 1: run prelayout: This will use the old positions of items. The layout manager
// is expected to layout everything, even removed items (though not to add removed
// items back to the container). This gives the pre-layout position of APPEARING views
// which come into existence as part of the real layout.
mInPreLayout = true;
final boolean didStructureChange = mState.mStructureChanged;
mState.mStructureChanged = false;
// temporarily disable flag because we are asking for previous layout
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = didStructureChange;
mInPreLayout = false;
appearingViewInitialBounds = new ArrayMap();
for (int i = 0; i < getChildCount(); ++i) {
boolean found = false;
View child = getChildAt(i);
for (int j = 0; j < mState.mPreLayoutHolderMap.size(); ++j) {
ViewHolder holder = mState.mPreLayoutHolderMap.keyAt(j);
if (holder.itemView == child) {
found = true;
continue;
}
}
if (!found) {
appearingViewInitialBounds.put(child, new Rect(child.getLeft(), child.getTop(),
child.getRight(), child.getBottom()));
}
}
}
clearOldPositions();
dispatchLayoutUpdates();
mState.mItemCount = mAdapter.getItemCount();
// Step 2: Run layout
mState.mInPreLayout = false;
mLayout.onLayoutChildren(mRecycler, mState);
mState.mStructureChanged = false;
mPendingSavedState = null;
// onLayoutChildren may have caused client code to disable item animations; re-check
animateChangesSimple = animateChangesSimple && mItemAnimator != null;
if (animateChangesSimple) {
// Step 3: Find out where things are now, post-layout
int count = getChildCount();
for (int i = 0; i < count; ++i) {
ViewHolder holder = getChildViewHolderInt(getChildAt(i));
final View view = holder.itemView;
mState.mPostLayoutHolderMap.put(holder, new ItemHolderInfo(holder,
view.getLeft(), view.getTop(), view.getRight(), view.getBottom(),
holder.mPosition));
}
// Step 4: Animate DISAPPEARING and REMOVED items
int preLayoutCount = mState.mPreLayoutHolderMap.size();
for (int i = preLayoutCount - 1; i >= 0; i--) {
ViewHolder itemHolder = mState.mPreLayoutHolderMap.keyAt(i);
if (!mState.mPostLayoutHolderMap.containsKey(itemHolder)) {
ItemHolderInfo disappearingItem = mState.mPreLayoutHolderMap.valueAt(i);
mState.mPreLayoutHolderMap.removeAt(i);
View disappearingItemView = disappearingItem.holder.itemView;
removeDetachedView(disappearingItemView, false);
mRecycler.unscrapView(disappearingItem.holder);
animateDisappearance(disappearingItem);
}
}
// Step 5: Animate APPEARING and ADDED items
int postLayoutCount = mState.mPostLayoutHolderMap.size();
if (postLayoutCount > 0) {
for (int i = postLayoutCount - 1; i >= 0; i--) {
ViewHolder itemHolder = mState.mPostLayoutHolderMap.keyAt(i);
ItemHolderInfo info = mState.mPostLayoutHolderMap.valueAt(i);
if ((mState.mPreLayoutHolderMap.isEmpty() ||
!mState.mPreLayoutHolderMap.containsKey(itemHolder))) {
mState.mPostLayoutHolderMap.removeAt(i);
Rect initialBounds = (appearingViewInitialBounds != null) ?
appearingViewInitialBounds.get(itemHolder.itemView) : null;
animateAppearance(itemHolder, initialBounds,
info.left, info.top);
}
}
}
// Step 6: Animate PERSISTENT items
count = mState.mPostLayoutHolderMap.size();
for (int i = 0; i < count; ++i) {
ViewHolder postHolder = mState.mPostLayoutHolderMap.keyAt(i);
ItemHolderInfo postInfo = mState.mPostLayoutHolderMap.valueAt(i);
ItemHolderInfo preInfo = mState.mPreLayoutHolderMap.get(postHolder);
if (preInfo != null && postInfo != null) {
if (preInfo.left != postInfo.left || preInfo.top != postInfo.top) {
postHolder.setIsRecyclable(false);
if (DEBUG) {
Log.d(TAG, "PERSISTENT: " + postHolder +
" with view " + postHolder.itemView);
}
if (mItemAnimator.animateMove(postHolder,
preInfo.left, preInfo.top, postInfo.left, postInfo.top)) {
postAnimationRunner();
}
}
}
}
}
resumeRequestLayout(false);
mLayout.removeAndRecycleScrapInt(mRecycler, !animateChangesAdvanced);
mState.mPreviousLayoutItemCount = mState.mItemCount;
mState.mDeletedInvisibleItemCountSincePreviousLayout = 0;
}
private void animateAppearance(ViewHolder itemHolder, Rect beforeBounds, int afterLeft,
int afterTop) {
View newItemView = itemHolder.itemView;
if (beforeBounds != null &&
(beforeBounds.left != afterLeft || beforeBounds.top != afterTop)) {
// slide items in if before/after locations differ
itemHolder.setIsRecyclable(false);
if (DEBUG) {
Log.d(TAG, "APPEARING: " + itemHolder + " with view " + newItemView);
}
if (mItemAnimator.animateMove(itemHolder,
beforeBounds.left, beforeBounds.top,
afterLeft, afterTop)) {
postAnimationRunner();
}
} else {
if (DEBUG) {
Log.d(TAG, "ADDED: " + itemHolder + " with view " + newItemView);
}
itemHolder.setIsRecyclable(false);
if (mItemAnimator.animateAdd(itemHolder)) {
postAnimationRunner();
}
}
}
private void animateDisappearance(ItemHolderInfo disappearingItem) {
View disappearingItemView = disappearingItem.holder.itemView;
addAnimatingView(disappearingItemView);
int oldLeft = disappearingItem.left;
int oldTop = disappearingItem.top;
int newLeft = disappearingItemView.getLeft();
int newTop = disappearingItemView.getTop();
if (oldLeft != newLeft || oldTop != newTop) {
disappearingItem.holder.setIsRecyclable(false);
disappearingItemView.layout(newLeft, newTop,
newLeft + disappearingItemView.getWidth(),
newTop + disappearingItemView.getHeight());
if (DEBUG) {
Log.d(TAG, "DISAPPEARING: " + disappearingItem.holder +
" with view " + disappearingItemView);
}
if (mItemAnimator.animateMove(disappearingItem.holder, oldLeft, oldTop,
newLeft, newTop)) {
postAnimationRunner();
}
} else {
if (DEBUG) {
Log.d(TAG, "REMOVED: " + disappearingItem.holder +
" with view " + disappearingItemView);
}
disappearingItem.holder.setIsRecyclable(false);
if (mItemAnimator.animateRemove(disappearingItem.holder)) {
postAnimationRunner();
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
eatRequestLayout();
dispatchLayout();
resumeRequestLayout(false);
mFirstLayoutComplete = true;
}
@Override
public void requestLayout() {
if (!mEatRequestLayout) {
super.requestLayout();
} else {
mLayoutRequestEaten = true;
}
}
void markItemDecorInsetsDirty() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
((LayoutParams) child.getLayoutParams()).mInsetsDirty = true;
}
}
@Override
public void draw(Canvas c) {
super.draw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDrawOver(c, this);
}
boolean needsInvalidate = false;
if (mLeftGlow != null && !mLeftGlow.isFinished()) {
final int restore = c.save();
c.rotate(270);
c.translate(-getHeight() + getPaddingTop(), 0);
needsInvalidate = mLeftGlow != null && mLeftGlow.draw(c);
c.restoreToCount(restore);
}
if (mTopGlow != null && !mTopGlow.isFinished()) {
c.translate(getPaddingLeft(), getPaddingTop());
needsInvalidate |= mTopGlow != null && mTopGlow.draw(c);
}
if (mRightGlow != null && !mRightGlow.isFinished()) {
final int restore = c.save();
final int width = getWidth();
c.rotate(90);
c.translate(-getPaddingTop(), -width);
needsInvalidate |= mRightGlow != null && mRightGlow.draw(c);
c.restoreToCount(restore);
}
if (mBottomGlow != null && !mBottomGlow.isFinished()) {
final int restore = c.save();
c.rotate(180);
c.translate(-getWidth() + getPaddingLeft(), -getHeight() + getPaddingTop());
needsInvalidate |= mBottomGlow != null && mBottomGlow.draw(c);
c.restoreToCount(restore);
}
if (needsInvalidate) {
ViewCompat.postInvalidateonAnimation(this);
}
}
@Override
public void onDraw(Canvas c) {
super.onDraw(c);
final int count = mItemDecorations.size();
for (int i = 0; i < count; i++) {
mItemDecorations.get(i).onDraw(c, this);
}
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && mLayout.checkLayoutParams((LayoutParams) p);
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateDefaultLayoutParams();
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateLayoutParams(getContext(), attrs);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
if (mLayout == null) {
throw new IllegalStateException("RecyclerView has no LayoutManager");
}
return mLayout.generateLayoutParams(p);
}
private int findPositionOffset(int position) {
int offset = 0;
int count = mPendingLayoutUpdates.size();
for (int i = 0; i < count; ++i) {
UpdateOp op = mPendingLayoutUpdates.get(i);
if (op.positionStart <= position) {
if (op.cmd == UpdateOp.REMOVE) {
offset -= op.itemCount;
} else if (op.cmd == UpdateOp.ADD) {
offset += op.itemCount;
}
}
}
return position + offset;
}
void dispatchLayoutUpdates() {
final int opCount = mPendingLayoutUpdates.size();
for (int i = 0; i < opCount; i++) {
final UpdateOp op = mPendingLayoutUpdates.get(i);
switch (op.cmd) {
case UpdateOp.ADD:
mLayout.onItemsAdded(this, op.positionStart, op.itemCount);
break;
case UpdateOp.REMOVE:
mLayout.onItemsRemoved(this, op.positionStart, op.itemCount);
break;
case UpdateOp.UPDATE:
// TODO: tell the layout manager
break;
}
recycleUpdateOp(op);
}
mPendingLayoutUpdates.clear();
}
void updateChildViews() {
final int opCount = mPendingUpdates.size();
for (int i = 0; i < opCount; i++) {
final UpdateOp op = mPendingUpdates.get(i);
switch (op.cmd) {
case UpdateOp.ADD:
if (DEBUG) {
Log.d(TAG, "UpdateOp.ADD start=" + op.positionStart + " count=" +
op.itemCount);
}
offsetPositionRecordsForInsert(op.positionStart, op.itemCount);
mItemsAddedOrRemoved = true;
break;
case UpdateOp.REMOVE:
if (DEBUG) {
Log.d(TAG, "UpdateOp.REMOVE start=" + op.positionStart + " count=" +
op.itemCount);
}
for (int j = 0; j < op.itemCount; ++j) {
ViewHolder holder = findViewHolderForPosition(op.positionStart + j, true);
if (holder != null) {
holder.setIsRecyclable(false);
} else {
mState.mDeletedInvisibleItemCountSincePreviousLayout ++;
}
}
offsetPositionRecordsForRemove(op.positionStart, op.itemCount);
mItemsAddedOrRemoved = true;
break;
case UpdateOp.UPDATE:
if (DEBUG) {
Log.d(TAG, "UpdateOp.UPDATE start=" + op.positionStart + " count=" +
op.itemCount);
}
viewRangeUpdate(op.positionStart, op.itemCount);
mItemsChanged = true;
break;
}
mPendingLayoutUpdates.add(op);
// TODO: recycle the op if no animator (also don't bother stashing in pending layout updates?)
}
mPendingUpdates.clear();
}
void clearOldPositions() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
holder.clearOldPosition();
}
mRecycler.clearOldPositions();
}
void offsetPositionRecordsForInsert(int positionStart, int itemCount) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
if (holder != null && holder.mPosition >= positionStart) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert attached child " + i + " holder " +
holder + " now at position " + (holder.mPosition + itemCount));
}
holder.offsetPosition(itemCount);
mState.mStructureChanged = true;
}
}
mRecycler.offsetPositionRecordsForInsert(positionStart, itemCount);
requestLayout();
}
void offsetPositionRecordsForRemove(int positionStart, int itemCount) {
final int positionEnd = positionStart + itemCount;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
if (holder != null) {
if (holder.mPosition >= positionEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
" holder " + holder + " now at position " +
(holder.mPosition - itemCount));
}
holder.offsetPosition(-itemCount);
mState.mStructureChanged = true;
} else if (holder.mPosition >= positionStart) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove attached child " + i +
" holder " + holder + " now REMOVED");
}
holder.addFlags(ViewHolder.FLAG_REMOVED);
mState.mStructureChanged = true;
}
}
}
mRecycler.offsetPositionRecordsForRemove(positionStart, itemCount);
requestLayout();
}
void viewRangeUpdate(int positionStart, int itemCount) {
final int childCount = getChildCount();
final int positionEnd = positionStart + itemCount;
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
if (holder == null) {
continue;
}
final int position = holder.getPosition();
if (position >= positionStart && position < positionEnd) {
holder.addFlags(ViewHolder.FLAG_UPDATE);
// Binding an attached view will request a layout if needed.
mAdapter.bindViewHolder(holder, holder.getPosition());
}
}
mRecycler.viewRangeUpdate(positionStart, itemCount);
}
void markKnownViewsInvalid() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
if (holder != null) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
}
mRecycler.markKnownViewsInvalid();
}
void postAdapterUpdate(UpdateOp op) {
mPendingUpdates.add(op);
if (mPendingUpdates.size() == 1) {
if (mPostUpdatesonAnimation && mHasFixedSize && mIsAttached) {
ViewCompat.postonAnimation(this, mUpdateChildViewsRunnable);
} else {
mAdapterUpdateDuringMeasure = true;
requestLayout();
}
}
}
public ViewHolder getChildViewHolder(View child) {
final ViewParent parent = child.getParent();
if (parent != null && parent != this) {
throw new IllegalArgumentException("View " + child + " is not a direct child of " +
this);
}
return getChildViewHolderInt(child);
}
static ViewHolder getChildViewHolderInt(View child) {
if (child == null) {
return null;
}
return ((LayoutParams) child.getLayoutParams()).mViewHolder;
}
public int getChildPosition(View child) {
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getPosition() : NO_POSITION;
}
public long getChildItemId(View child) {
if (mAdapter == null || !mAdapter.hasStableIds()) {
return NO_ID;
}
final ViewHolder holder = getChildViewHolderInt(child);
return holder != null ? holder.getItemId() : NO_ID;
}
public ViewHolder findViewHolderForPosition(int position) {
return findViewHolderForPosition(position, false);
}
ViewHolder findViewHolderForPosition(int position, boolean checkNewPosition) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
if (holder != null) {
if (checkNewPosition) {
if (holder.mPosition == position) {
return holder;
}
} else if(holder.getPosition() == position) {
return holder;
}
}
}
return mRecycler.findViewHolderForPosition(position);
}
public ViewHolder findViewHolderForItemId(long id) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final ViewHolder holder = getChildViewHolderInt(getChildAt(i));
if (holder != null && holder.getItemId() == id) {
return holder;
}
}
return mRecycler.findViewHolderForItemId(id);
}
public View findChildViewUnder(float x, float y) {
final int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = getChildAt(i);
final float translationX = ViewCompat.getTranslationX(child);
final float translationY = ViewCompat.getTranslationY(child);
if (x >= child.getLeft() + translationX &&
x <= child.getRight() + translationX &&
y >= child.getTop() + translationY &&
y <= child.getBottom() + translationY) {
return child;
}
}
return null;
}
public void offsetChildrenVertical(int dy) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
getChildAt(i).offsetTopAndBottom(dy);
}
}
public void onChildAttachedToWindow(View child) {
}
public void onChildDetachedFromWindow(View child) {
}
public void offsetChildrenHorizontal(int dx) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
getChildAt(i).offsetLeftAndRight(dx);
}
}
Rect getItemDecorInsetsForChild(View child) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!lp.mInsetsDirty) {
return lp.mDecorInsets;
}
final Rect insets = lp.mDecorInsets;
insets.set(0, 0, 0, 0);
final int decorCount = mItemDecorations.size();
for (int i = 0; i < decorCount; i++) {
mTempRect.set(0, 0, 0, 0);
mItemDecorations.get(i).getItemOffsets(mTempRect, lp.getViewPosition(), this);
insets.left += mTempRect.left;
insets.top += mTempRect.top;
insets.right += mTempRect.right;
insets.bottom += mTempRect.bottom;
}
lp.mInsetsDirty = false;
return insets;
}
private class ViewFlinger implements Runnable {
private int mLastFlingX;
private int mLastFlingY;
private ScrollerCompat mScroller;
private Interpolator mInterpolator = sQuinticInterpolator;
// When set to true, postonAnimation callbacks are delayed until the run method completes
private boolean mEatRunonAnimationRequest = false;
// Tracks if postAnimationCallback should be re-attached when it is done
private boolean mReSchedulePostAnimationCallback = false;
public ViewFlinger() {
mScroller = ScrollerCompat.create(getContext(), sQuinticInterpolator);
}
@Override
public void run() {
disableRunonAnimationRequests();
consumePendingUpdateOperations();
// keep a local reference so that if it is changed during onAnimation method, it wont cause
// unexpected behaviors
final ScrollerCompat scroller = mScroller;
final SmoothScroller smoothScroller = mLayout.mSmoothScroller;
if (scroller.computeScrollOffset()) {
final int x = scroller.getCurrX();
final int y = scroller.getCurrY();
final int dx = x - mLastFlingX;
final int dy = y - mLastFlingY;
mLastFlingX = x;
mLastFlingY = y;
int overscrollX = 0, overscrollY = 0;
if (mAdapter != null) {
eatRequestLayout();
if (dx != 0) {
final int hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState);
overscrollX = dx - hresult;
}
if (dy != 0) {
final int vresult = mLayout.scrollVerticallyBy(dy, mRecycler, mState);
overscrollY = dy - vresult;
}
if (smoothScroller != null && !smoothScroller.isPendingInitialRun() &&
smoothScroller.isRunning()) {
smoothScroller.onAnimation(dx - overscrollX, dy - overscrollY);
}
resumeRequestLayout(false);
}
if (!mItemDecorations.isEmpty()) {
invalidate();
}
if (overscrollX != 0 || overscrollY != 0) {
final int vel = (int) scroller.getCurrVelocity();
int velX = 0;
if (overscrollX != x) {
velX = overscrollX < 0 ? -vel : overscrollX > 0 ? vel : 0;
}
int velY = 0;
if (overscrollY != y) {
velY = overscrollY < 0 ? -vel : overscrollY > 0 ? vel : 0;
}
if (ViewCompat.getOverScrollMode(RecyclerView.this) !=
ViewCompat.OVER_SCROLL_NEVER) {
absorbGlows(velX, velY);
}
if ((velX != 0 || overscrollX == x || scroller.getFinalX() == 0) &&
(velY != 0 || overscrollY == y || scroller.getFinalY() == 0)) {
scroller.abortAnimation();
}
}
if (mScrollListener != null && (x != 0 || y != 0)) {
mScrollListener.onScrolled(dx, dy);
}
if (!awakenScrollBars()) {
invalidate();
}
if (scroller.isFinished()) {
setScrollState(SCROLL_STATE_IDLE);
} else {
postonAnimation();
}
}
// call this after the onAnimation is complete not to have inconsistent callbacks etc.
if (smoothScroller != null && smoothScroller.isPendingInitialRun()) {
smoothScroller.onAnimation(0, 0);
}
enableRunonAnimationRequests();
}
private void disableRunonAnimationRequests() {
mReSchedulePostAnimationCallback = false;
mEatRunonAnimationRequest = true;
}
private void enableRunonAnimationRequests() {
mEatRunonAnimationRequest = false;
if (mReSchedulePostAnimationCallback) {
postonAnimation();
}
}
void postonAnimation() {
if (mEatRunOnAnimationRequest) {
mReSchedulePostAnimationCallback = true;
} else {
ViewCompat.postonAnimation(RecyclerView.this, this);
}
}
public void fling(int velocityX, int velocityY) {
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.fling(0, 0, velocityX, velocityY,
Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);
postonAnimation();
}
public void smoothScrollBy(int dx, int dy) {
smoothScrollBy(dx, dy, 0, 0);
}
public void smoothScrollBy(int dx, int dy, int vx, int vy) {
smoothScrollBy(dx, dy, computeScrollDuration(dx, dy, vx, vy));
}
private float distanceInfluenceForSnapDuration(float f) {
f -= 0.5f; // center the values about 0.
f *= 0.3f * Math.PI / 2.0f;
return (float) Math.sin(f);
}
private int computeScrollDuration(int dx, int dy, int vx, int vy) {
final int absDx = Math.abs(dx);
final int absDy = Math.abs(dy);
final boolean horizontal = absDx > absDy;
final int velocity = (int) Math.sqrt(vx * vx + vy * vy);
final int delta = (int) Math.sqrt(dx * dx + dy * dy);
final int containerSize = horizontal ? getWidth() : getHeight();
final int halfContainerSize = containerSize / 2;
final float distanceRatio = Math.min(1.f, 1.f * delta / containerSize);
final float distance = halfContainerSize + halfContainerSize *
distanceInfluenceForSnapDuration(distanceRatio);
final int duration;
if (velocity > 0) {
duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
} else {
float absDelta = (float) (horizontal ? absDx : absDy);
duration = (int) (((absDelta / containerSize) + 1) * 300);
}
return Math.min(duration, MAX_SCROLL_DURATION);
}
public void smoothScrollBy(int dx, int dy, int duration) {
smoothScrollBy(dx, dy, duration, sQuinticInterpolator);
}
public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) {
if (mInterpolator != interpolator) {
mInterpolator = interpolator;
mScroller = ScrollerCompat.create(getContext(), interpolator);
}
setScrollState(SCROLL_STATE_SETTLING);
mLastFlingX = mLastFlingY = 0;
mScroller.startScroll(0, 0, dx, dy, duration);
postonAnimation();
}
public void stop() {
removeCallbacks(this);
mScroller.abortAnimation();
}
}
private class RecyclerViewDataObserver extends AdapterDataObserver {
@Override
public void onChanged() {
if (mAdapter.hasStableIds()) {
// TODO Determine what actually changed
markKnownViewsInvalid();
mState.mStructureChanged = true;
requestLayout();
} else {
markKnownViewsInvalid();
mState.mStructureChanged = true;
requestLayout();
}
}
@Override
public void onItemRangeChanged(int positionStart, int itemCount) {
postAdapterUpdate(obtainUpdateOp(UpdateOp.UPDATE, positionStart, itemCount));
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
postAdapterUpdate(obtainUpdateOp(UpdateOp.ADD, positionStart, itemCount));
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
postAdapterUpdate(obtainUpdateOp(UpdateOp.REMOVE, positionStart, itemCount));
}
}
public static class RecycledViewPool {
private SparseArray> mScrap =
new SparseArray>();
private SparseIntArray mMaxScrap = new SparseIntArray();
private int mAttachCount = 0;
private static final int DEFAULT_MAX_SCRAP = 5;
public void clear() {
mScrap.clear();
}
public void setMaxRecycledViews(int viewType, int max) {
mMaxScrap.put(viewType, max);
final ArrayList scrapHeap = mScrap.get(viewType);
if (scrapHeap != null) {
while (scrapHeap.size() > max) {
scrapHeap.remove(scrapHeap.size() - 1);
}
}
}
public ViewHolder getRecycledView(int viewType) {
final ArrayList scrapHeap = mScrap.get(viewType);
if (scrapHeap != null && !scrapHeap.isEmpty()) {
final int index = scrapHeap.size() - 1;
final ViewHolder scrap = scrapHeap.get(index);
scrapHeap.remove(index);
return scrap;
}
return null;
}
public void putRecycledView(ViewHolder scrap) {
final int viewType = scrap.getItemViewType();
final ArrayList scrapHeap = getScrapHeapForType(viewType);
if (mMaxScrap.get(viewType) <= scrapHeap.size()) {
return;
}
scrap.mPosition = NO_POSITION;
scrap.mOldPosition = NO_POSITION;
scrap.mItemId = NO_ID;
scrap.clearFlagsForSharedPool();
scrapHeap.add(scrap);
}
void attach(Adapter adapter) {
mAttachCount++;
}
void detach() {
mAttachCount--;
}
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) {
if (mAttachCount == 1) {
clear();
}
}
private ArrayList getScrapHeapForType(int viewType) {
ArrayList scrap = mScrap.get(viewType);
if (scrap == null) {
scrap = new ArrayList();
mScrap.put(viewType, scrap);
if (mMaxScrap.indexOfKey(viewType) < 0) {
mMaxScrap.put(viewType, DEFAULT_MAX_SCRAP);
}
}
return scrap;
}
}
public final class Recycler {
private final ArrayList mAttachedScrap = new ArrayList();
private final ArrayList mCachedViews = new ArrayList();
private final List
mUnmodifiableAttachedScrap = Collections.unmodifiableList(mAttachedScrap);
private int mViewCacheMax = DEFAULT_CACHE_SIZE;
private RecycledViewPool mRecyclerPool;
private static final int DEFAULT_CACHE_SIZE = 2;
public void clear() {
mAttachedScrap.clear();
recycleCachedViews();
}
public void setViewCacheSize(int viewCount) {
mViewCacheMax = viewCount;
while (mCachedViews.size() > viewCount) {
mCachedViews.remove(mCachedViews.size() - 1);
}
}
public List getScrapList() {
return mUnmodifiableAttachedScrap;
}
boolean validateViewHolderForOffsetPosition(ViewHolder holder, int offsetPosition) {
// if it is a removed holder, nothing to verify since we cannot ask adapter anymore
// if it is not removed, verify the type and id.
if (holder.isRemoved()) {
return true;
}
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
if (DEBUG) {
Log.d(TAG, "validateViewHolderForOffsetPosition: invalid position, returning "
+ "false");
}
return false;
}
final int type = mAdapter.getItemViewType(offsetPosition);
if (type != holder.getItemViewType()) {
return false;
}
if (mAdapter.hasStableIds()) {
return holder.getItemId() == mAdapter.getItemId(offsetPosition);
}
return true;
}
public View getViewForPosition(int position) {
ViewHolder holder;
holder = getScrapViewForPosition(position, INVALID_TYPE);
final int offsetPosition = findPositionOffset(position);
if (holder != null) {
if (!validateViewHolderForOffsetPosition(holder, offsetPosition)) {
// recycle this scrap
removeDetachedView(holder.itemView, false);
quickRecycleScrapView(holder.itemView);
// if validate fails, we can query scrap again w/ type. that may return a
// different view holder from cache.
final int type = mAdapter.getItemViewType(offsetPosition);
if (mAdapter.hasStableIds()) {
final long id = mAdapter.getItemId(offsetPosition);
holder = getScrapViewForId(id, type);
} else {
holder = getScrapViewForPosition(offsetPosition, type);
}
}
} else {
// try recycler.
holder = getRecycledViewPool()
.getRecycledView(mAdapter.getItemViewType(offsetPosition));
}
if (holder == null) {
if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
throw new IndexOutOfBoundsException("Invalid item position " + position
+ "(" + offsetPosition + ")");
} else {
holder = mAdapter.createViewHolder(RecyclerView.this,
mAdapter.getItemViewType(offsetPosition));
if (DEBUG) {
Log.d(TAG, "getViewForPosition created new ViewHolder");
}
}
}
if (!holder.isRemoved() && (!holder.isBound() || holder.needsUpdate())) {
if (DEBUG) {
Log.d(TAG, "getViewForPosition unbound holder or needs update; updating...");
}
// TODO: think through when getOffsetPosition() is called. I use it here because
// existing views have already been offset appropriately through the mOldOffset
// mechanism, but new views do not have this mechanism.
mAdapter.bindViewHolder(holder, offsetPosition);
}
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp == null) {
lp = generateDefaultLayoutParams();
holder.itemView.setLayoutParams(lp);
} else if (!checkLayoutParams(lp)) {
lp = generateLayoutParams(lp);
holder.itemView.setLayoutParams(lp);
}
((LayoutParams) lp).mViewHolder = holder;
return holder.itemView;
}
public void recycleView(View view) {
recycleViewHolder(getChildViewHolderInt(view));
}
void recycleCachedViews() {
final int count = mCachedViews.size();
for (int i = count - 1; i >= 0; i--) {
final ViewHolder cachedView = mCachedViews.get(i);
if (cachedView.isRecyclable()) {
getRecycledViewPool().putRecycledView(cachedView);
dispatchViewRecycled(cachedView);
}
mCachedViews.remove(i);
}
}
void recycleViewHolder(ViewHolder holder) {
if (holder.isScrap() || holder.itemView.getParent() != null) {
throw new IllegalArgumentException(
"Scrapped or attached views may not be recycled.");
}
boolean cached = false;
if (!holder.isInvalid() && (mInPreLayout || !holder.isRemoved())) {
// Retire oldest cached views first
if (mCachedViews.size() == mViewCacheMax && !mCachedViews.isEmpty()) {
for (int i = 0; i < mCachedViews.size(); i++) {
final ViewHolder cachedView = mCachedViews.get(i);
if (cachedView.isRecyclable()) {
mCachedViews.remove(i);
getRecycledViewPool().putRecycledView(cachedView);
dispatchViewRecycled(cachedView);
break;
}
}
}
if (mCachedViews.size() < mViewCacheMax) {
mCachedViews.add(holder);
cached = true;
}
}
if (!cached && holder.isRecyclable()) {
getRecycledViewPool().putRecycledView(holder);
dispatchViewRecycled(holder);
}
// Remove from pre/post maps that are used to animate items; a recycled holder
// should not be animated
mState.mPreLayoutHolderMap.remove(holder);
mState.mPostLayoutHolderMap.remove(holder);
}
void quickRecycleScrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
holder.mScrapContainer = null;
recycleViewHolder(holder);
}
void scrapView(View view) {
final ViewHolder holder = getChildViewHolderInt(view);
holder.setScrapContainer(this);
mAttachedScrap.add(holder);
}
void unscrapView(ViewHolder holder) {
mAttachedScrap.remove(holder);
holder.mScrapContainer = null;
}
int getScrapCount() {
return mAttachedScrap.size();
}
View getScrapViewAt(int index) {
return mAttachedScrap.get(index).itemView;
}
void clearScrap() {
mAttachedScrap.clear();
}
ViewHolder getScrapViewForPosition(int position, int type) {
final int scrapCount = mAttachedScrap.size();
// Try first for an exact, non-invalid match from scrap.
for (int i = 0; i < scrapCount; i++) {
final ViewHolder holder = mAttachedScrap.get(i);
if (holder.getPosition() == position && !holder.isInvalid() &&
(mInPreLayout || !holder.isRemoved())) {
if (type != INVALID_TYPE && holder.getItemViewType() != type) {
Log.e(TAG, "Scrap view for position " + position + " isn't dirty but has" +
" wrong view type! (found " + holder.getItemViewType() +
" but expected " + type + ")");
break;
}
mAttachedScrap.remove(i);
holder.setScrapContainer(null);
if (DEBUG) {
Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
") found exact match in scrap: " + holder);
}
return holder;
}
}
if (mNumAnimatingViews != 0) {
View view = getAnimatingView(position, type);
if (view != null) {
// ending the animation should cause it to get recycled before we reuse it
mItemAnimator.endAnimation(getChildViewHolder(view));
}
}
// Search in our first-level recycled view cache.
final int cacheSize = mCachedViews.size();
for (int i = 0; i < cacheSize; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder.getPosition() == position) {
mCachedViews.remove(i);
if (holder.isInvalid() &&
(type != INVALID_TYPE && holder.getItemViewType() != type)) {
// Can't use it. We don't know where it's been.
if (DEBUG) {
Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
") found position match, but holder is invalid with type " +
holder.getItemViewType());
}
if (holder.isRecyclable()) {
getRecycledViewPool().putRecycledView(holder);
}
// Even if the holder wasn't officially recycleable, dispatch that it
// was recycled anyway in case there are resources to unbind.
dispatchViewRecycled(holder);
// Drop out of the cache search and try something else instead,
// we won't find another match here.
break;
}
if (DEBUG) {
Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
") found match in cache: " + holder);
}
return holder;
}
}
// Give up. Head to the shared pool.
if (DEBUG) {
Log.d(TAG, "getScrapViewForPosition(" + position + ", " + type +
") fetching from shared pool");
}
return type == INVALID_TYPE ? null : getRecycledViewPool().getRecycledView(type);
}
ViewHolder getScrapViewForId(long id, int type) {
// Look in our attached views first
final int count = mAttachedScrap.size();
for (int i = 0; i < count; i++) {
final ViewHolder holder = mAttachedScrap.get(i);
if (holder.getItemId() == id) {
if (type == holder.getItemViewType()) {
mAttachedScrap.remove(i);
holder.setScrapContainer(null);
return holder;
} else {
break;
}
}
}
// Search the first-level cache
final int cacheSize = mCachedViews.size();
for (int i = 0; i < cacheSize; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder.getItemId() == id) {
mCachedViews.remove(i);
return holder;
}
}
// That didn't work, look for an unordered view of the right type instead.
// The holder's position won't match so the calling code will need to have
// the adapter rebind it.
return getRecycledViewPool().getRecycledView(type);
}
void dispatchViewRecycled(ViewHolder holder) {
if (mRecyclerListener != null) {
mRecyclerListener.onViewRecycled(holder);
}
if (mAdapter != null) {
mAdapter.onViewRecycled(holder);
}
if (DEBUG) Log.d(TAG, "dispatchViewRecycled: " + holder);
}
void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) {
clear();
getRecycledViewPool().onAdapterChanged(oldAdapter, newAdapter);
}
void offsetPositionRecordsForInsert(int insertedAt, int count) {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null && holder.getPosition() >= insertedAt) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForInsert cached " + i + " holder " +
holder + " now at position " + (holder.mPosition + count));
}
holder.offsetPosition(count);
}
}
}
void offsetPositionRecordsForRemove(int removedFrom, int count) {
final int removedEnd = removedFrom + count;
final int cachedCount = mCachedViews.size();
for (int i = cachedCount - 1; i >= 0; i--) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
if (holder.getPosition() >= removedEnd) {
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove cached " + i +
" holder " + holder + " now at position " +
(holder.mPosition - count));
}
holder.offsetPosition(-count);
} else if (holder.getPosition() >= removedFrom) {
// Item for this view was removed. Dump it from the cache.
if (DEBUG) {
Log.d(TAG, "offsetPositionRecordsForRemove cached " + i +
" holder " + holder + " now placed in pool");
}
mCachedViews.remove(i);
getRecycledViewPool().putRecycledView(holder);
dispatchViewRecycled(holder);
}
}
}
}
void setRecycledViewPool(RecycledViewPool pool) {
if (mRecyclerPool != null) {
mRecyclerPool.detach();
}
mRecyclerPool = pool;
if (pool != null) {
mRecyclerPool.attach(getAdapter());
}
}
RecycledViewPool getRecycledViewPool() {
if (mRecyclerPool == null) {
mRecyclerPool = new RecycledViewPool();
}
return mRecyclerPool;
}
ViewHolder findViewHolderForPosition(int position) {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null && holder.getPosition() == position) {
mCachedViews.remove(i);
return holder;
}
}
return null;
}
ViewHolder findViewHolderForItemId(long id) {
if (!mAdapter.hasStableIds()) {
return null;
}
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null && holder.getItemId() == id) {
mCachedViews.remove(i);
return holder;
}
}
return null;
}
void viewRangeUpdate(int positionStart, int itemCount) {
final int positionEnd = positionStart + itemCount;
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder == null) {
continue;
}
final int pos = holder.getPosition();
if (pos >= positionStart && pos < positionEnd) {
holder.addFlags(ViewHolder.FLAG_UPDATE);
}
}
}
void markKnownViewsInvalid() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
if (holder != null) {
holder.addFlags(ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
}
}
void clearOldPositions() {
final int cachedCount = mCachedViews.size();
for (int i = 0; i < cachedCount; i++) {
final ViewHolder holder = mCachedViews.get(i);
holder.clearOldPosition();
}
}
}
public static abstract class Adapter {
private final AdapterDataObservable mObservable = new AdapterDataObservable();
private boolean mHasStableIds = false;
public abstract VH onCreateViewHolder(ViewGroup parent, int viewType);
public abstract void onBindViewHolder(VH holder, int position);
public final VH createViewHolder(ViewGroup parent, int viewType) {
final VH holder = onCreateViewHolder(parent, viewType);
holder.mItemViewType = viewType;
return holder;
}
public final void bindViewHolder(VH holder, int position) {
holder.mPosition = position;
if (hasStableIds()) {
holder.mItemId = getItemId(position);
}
onBindViewHolder(holder, position);
holder.setFlags(ViewHolder.FLAG_BOUND,
ViewHolder.FLAG_BOUND | ViewHolder.FLAG_UPDATE | ViewHolder.FLAG_INVALID);
}
public int getItemViewType(int position) {
return 0;
}
public void setHasStableIds(boolean hasStableIds) {
if (hasObservers()) {
throw new IllegalStateException("Cannot change whether this adapter has " +
"stable IDs while the adapter has registered observers.");
}
mHasStableIds = hasStableIds;
}
public long getItemId(int position) {
return NO_ID;
}
public abstract int getItemCount();
public final boolean hasStableIds() {
return mHasStableIds;
}
public void onViewRecycled(VH holder) {
}
public void onViewAttachedToWindow(VH holder) {
}
public void onViewDetachedFromWindow(VH holder) {
}
public final boolean hasObservers() {
return mObservable.hasObservers();
}
public void registerAdapterDataObserver(AdapterDataObserver observer) {
mObservable.registerObserver(observer);
}
public void unregisterAdapterDataObserver(AdapterDataObserver observer) {
mObservable.unregisterObserver(observer);
}
public final void notifyDataSetChanged() {
mObservable.notifyChanged();
}
public final void notifyItemChanged(int position) {
mObservable.notifyItemRangeChanged(position, 1);
}
public final void notifyItemRangeChanged(int positionStart, int itemCount) {
mObservable.notifyItemRangeChanged(positionStart, itemCount);
}
public final void notifyItemInserted(int position) {
mObservable.notifyItemRangeInserted(position, 1);
}
public final void notifyItemRangeInserted(int positionStart, int itemCount) {
mObservable.notifyItemRangeInserted(positionStart, itemCount);
}
public final void notifyItemRemoved(int position) {
mObservable.notifyItemRangeRemoved(position, 1);
}
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
}
public static abstract class LayoutManager {
RecyclerView mRecyclerView;
@Nullable
SmoothScroller mSmoothScroller;
public void requestLayout() {
if(mRecyclerView != null) {
mRecyclerView.requestLayout();
}
}
public boolean supportsPredictiveItemAnimations() {
return false;
}
public void onAttachedToWindow(RecyclerView view) {
}
public void onDetachedFromWindow(RecyclerView view) {
}
public void onLayoutChildren(Recycler recycler, State state) {
Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) ");
}
public abstract LayoutParams generateDefaultLayoutParams();
public boolean checkLayoutParams(LayoutParams lp) {
return lp != null;
}
public LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
if (lp instanceof LayoutParams) {
return new LayoutParams((LayoutParams) lp);
} else if (lp instanceof MarginLayoutParams) {
return new LayoutParams((MarginLayoutParams) lp);
} else {
return new LayoutParams(lp);
}
}
public LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
return new LayoutParams(c, attrs);
}
public int scrollHorizontallyBy(int dx, Recycler recycler, State state) {
return 0;
}
public int scrollVerticallyBy(int dy, Recycler recycler, State state) {
return 0;
}
public boolean canScrollHorizontally() {
return false;
}
public boolean canScrollVertically() {
return false;
}
public void scrollToPosition(int position) {
if (DEBUG) {
Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract");
}
}
public void smoothScrollToPosition(RecyclerView recyclerView, State state,
int position) {
Log.e(TAG, "You must override smoothScrollToPosition to support smooth scrolling");
}
public void startSmoothScroll(SmoothScroller smoothScroller) {
if (mSmoothScroller != null && smoothScroller != mSmoothScroller
&& mSmoothScroller.isRunning()) {
mSmoothScroller.stop();
}
mSmoothScroller = smoothScroller;
mSmoothScroller.start(mRecyclerView, this);
}
public boolean isSmoothScrolling() {
return mSmoothScroller != null && mSmoothScroller.isRunning();
}
public int getLayoutDirection() {
return ViewCompat.getLayoutDirection(mRecyclerView);
}
public void addView(View child, int index) {
if (mRecyclerView.mAnimatingViewIndex >= 0) {
if (index > mRecyclerView.mAnimatingViewIndex) {
throw new IndexOutOfBoundsException("index=" + index + " count="
+ mRecyclerView.mAnimatingViewIndex);
}
mRecyclerView.mAnimatingViewIndex++;
}
final ViewHolder holder = getChildViewHolderInt(child);
if (holder.isScrap()) {
holder.unScrap();
mRecyclerView.attachViewToParent(child, index, child.getLayoutParams());
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
} else {
mRecyclerView.addView(child, index);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
lp.mInsetsDirty = true;
final Adapter adapter = mRecyclerView.getAdapter();
if (adapter != null) {
adapter.onViewAttachedToWindow(getChildViewHolderInt(child));
}
mRecyclerView.onChildAttachedToWindow(child);
if (mSmoothScroller != null && mSmoothScroller.isRunning()) {
mSmoothScroller.onChildAttachedToWindow(child);
}
}
}
public void addView(View child) {
if (mRecyclerView.mAnimatingViewIndex >= 0) {
addView(child, mRecyclerView.mAnimatingViewIndex);
} else {
addView(child, -1);
}
}
public void removeView(View child) {
final Adapter adapter = mRecyclerView.getAdapter();
if (adapter != null) {
adapter.onViewDetachedFromWindow(getChildViewHolderInt(child));
}
mRecyclerView.onChildDetachedFromWindow(child);
mRecyclerView.removeView(child);
if (mRecyclerView.mAnimatingViewIndex >= 0) {
mRecyclerView.mAnimatingViewIndex--;
}
}
public void removeViewAt(int index) {
final View child = mRecyclerView.getChildAt(index);
if (child != null) {
final Adapter adapter = mRecyclerView.getAdapter();
if (adapter != null) {
adapter.onViewDetachedFromWindow(getChildViewHolderInt(child));
}
mRecyclerView.onChildDetachedFromWindow(child);
mRecyclerView.removeViewAt(index);
if (mRecyclerView.mAnimatingViewIndex >= 0) {
mRecyclerView.mAnimatingViewIndex--;
}
}
}
public void removeAllViews() {
final Adapter adapter = mRecyclerView.getAdapter();
// only remove non-animating views
final int childCount = mRecyclerView.getChildCount() - mRecyclerView.mNumAnimatingViews;
for (int i = 0; i < childCount; i++) {
final View child = mRecyclerView.getChildAt(i);
if (adapter != null) {
adapter.onViewDetachedFromWindow(getChildViewHolderInt(child));
}
mRecyclerView.onChildDetachedFromWindow(child);
}
for (int i = childCount - 1; i >= 0; i--) {
mRecyclerView.removeViewAt(i);
if (mRecyclerView.mAnimatingViewIndex >= 0) {
mRecyclerView.mAnimatingViewIndex--;
}
}
}
public int getPosition(View view) {
return ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewPosition();
}
public View findViewByPosition(int position) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (getPosition(child) == position) {
return child;
}
}
return null;
}
public void detachView(View child) {
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchStartTemporaryDetach(child);
}
mRecyclerView.detachViewFromParent(child);
}
public void detachViewAt(int index) {
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchStartTemporaryDetach(mRecyclerView.getChildAt(index));
}
mRecyclerView.detachViewFromParent(index);
if (mRecyclerView.mAnimatingViewIndex >= 0) {
--mRecyclerView.mAnimatingViewIndex;
}
}
public void attachView(View child, int index, LayoutParams lp) {
mRecyclerView.attachViewToParent(child, index, lp);
if (mRecyclerView.mAnimatingViewIndex >= 0) {
++mRecyclerView.mAnimatingViewIndex;
}
if (DISPATCH_TEMP_DETACH) {
ViewCompat.dispatchFinishTemporaryDetach(child);
}
}
public void attachView(View child, int index) {
attachView(child, index, (LayoutParams) child.getLayoutParams());
}
public void attachView(View child) {
attachView(child, -1);
}
public void removeDetachedView(View child) {
mRecyclerView.removeDetachedView(child, false);
}
public void detachAndScrapView(View child, Recycler recycler) {
detachView(child);
recycler.scrapView(child);
}
public void detachAndScrapViewAt(int index, Recycler recycler) {
final View child = getChildAt(index);
detachViewAt(index);
recycler.scrapView(child);
}
public void removeAndRecycleView(View child, Recycler recycler) {
removeView(child);
recycler.recycleView(child);
}
public void removeAndRecycleViewAt(int index, Recycler recycler) {
final View view = getChildAt(index);
removeViewAt(index);
recycler.recycleView(view);
}
public int getChildCount() {
return mRecyclerView != null ?
mRecyclerView.getChildCount() - mRecyclerView.mNumAnimatingViews : 0;
}
public View getChildAt(int index) {
return mRecyclerView != null ? mRecyclerView.getChildAt(index) : null;
}
public int getWidth() {
return mRecyclerView != null ? mRecyclerView.getWidth() : 0;
}
public int getHeight() {
return mRecyclerView != null ? mRecyclerView.getHeight() : 0;
}
public int getPaddingLeft() {
return mRecyclerView != null ? mRecyclerView.getPaddingLeft() : 0;
}
public int getPaddingTop() {
return mRecyclerView != null ? mRecyclerView.getPaddingTop() : 0;
}
public int getPaddingRight() {
return mRecyclerView != null ? mRecyclerView.getPaddingRight() : 0;
}
public int getPaddingBottom() {
return mRecyclerView != null ? mRecyclerView.getPaddingBottom() : 0;
}
public int getPaddingStart() {
return mRecyclerView != null ? ViewCompat.getPaddingStart(mRecyclerView) : 0;
}
public int getPaddingEnd() {
return mRecyclerView != null ? ViewCompat.getPaddingEnd(mRecyclerView) : 0;
}
public boolean isFocused() {
return mRecyclerView != null && mRecyclerView.isFocused();
}
public boolean hasFocus() {
return mRecyclerView != null && mRecyclerView.hasFocus();
}
public int getItemCount() {
final Adapter a = mRecyclerView != null ? mRecyclerView.getAdapter() : null;
return a != null ? a.getItemCount() : 0;
}
public void offsetChildrenHorizontal(int dx) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenHorizontal(dx);
}
}
public void offsetChildrenVertical(int dy) {
if (mRecyclerView != null) {
mRecyclerView.offsetChildrenVertical(dy);
}
}
public void detachAndScrapAttachedViews(Recycler recycler) {
final int childCount = getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final View v = getChildAt(i);
detachViewAt(i);
recycler.scrapView(v);
}
}
void removeAndRecycleScrapInt(Recycler recycler, boolean remove) {
final int scrapCount = recycler.getScrapCount();
for (int i = 0; i < scrapCount; i++) {
final View scrap = recycler.getScrapViewAt(i);
if (remove) {
mRecyclerView.removeDetachedView(scrap, false);
}
recycler.quickRecycleScrapView(scrap);
}
recycler.clearScrap();
if (remove && scrapCount > 0) {
mRecyclerView.invalidate();
}
}
public void measureChild(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(),
getPaddingLeft() + getPaddingRight() + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(),
getPaddingTop() + getPaddingBottom() + heightUsed, lp.height,
canScrollVertically());
child.measure(widthSpec, heightSpec);
}
public void measureChildWithMargins(View child, int widthUsed, int heightUsed) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final Rect insets = mRecyclerView.getItemDecorInsetsForChild(child);
widthUsed += insets.left + insets.right;
heightUsed += insets.top + insets.bottom;
final int widthSpec = getChildMeasureSpec(getWidth(),
getPaddingLeft() + getPaddingRight() +
lp.leftMargin + lp.rightMargin + widthUsed, lp.width,
canScrollHorizontally());
final int heightSpec = getChildMeasureSpec(getHeight(),
getPaddingTop() + getPaddingBottom() +
lp.topMargin + lp.bottomMargin + heightUsed, lp.height,
canScrollVertically());
child.measure(widthSpec, heightSpec);
}
public static int getChildMeasureSpec(int parentSize, int padding, int childDimension,
boolean canScroll) {
int size = Math.max(0, parentSize - padding);
int resultSize = 0;
int resultMode = 0;
if (canScroll) {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else {
// MATCH_PARENT can't be applied since we can scroll in this dimension, wrap
// instead using UNSPECIFIED.
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
} else {
if (childDimension >= 0) {
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.FILL_PARENT) {
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
public int getDecoratedMeasuredWidth(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredWidth() + insets.left + insets.right;
}
public int getDecoratedMeasuredHeight(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getMeasuredHeight() + insets.top + insets.bottom;
}
public void layoutDecorated(View child, int left, int top, int right, int bottom) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
child.layout(left + insets.left, top + insets.top, right - insets.right,
bottom - insets.bottom);
}
public int getDecoratedLeft(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getLeft() - insets.left;
}
public int getDecoratedTop(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getTop() - insets.top;
}
public int getDecoratedRight(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getRight() + insets.right;
}
public int getDecoratedBottom(View child) {
final Rect insets = ((LayoutParams) child.getLayoutParams()).mDecorInsets;
return child.getBottom() + insets.bottom;
}
public View onFocusSearchFailed(View focused, int direction, Recycler recycler,
State state) {
return null;
}
public View onInterceptFocusSearch(View focused, int direction) {
return null;
}
public boolean requestChildRectangleonScreen(RecyclerView parent, View child, Rect rect,
boolean immediate) {
final int parentLeft = getPaddingLeft();
final int parentTop = getPaddingTop();
final int parentRight = getWidth() - getPaddingRight();
final int parentBottom = getHeight() - getPaddingBottom();
final int childLeft = child.getLeft() + rect.left;
final int childTop = child.getTop() + rect.top;
final int childRight = childLeft + rect.right;
final int childBottom = childTop + rect.bottom;
final int offScreenLeft = Math.min(0, childLeft - parentLeft);
final int offScreenTop = Math.min(0, childTop - parentTop);
final int offScreenRight = Math.max(0, childRight - parentRight);
final int offScreenBottom = Math.max(0, childBottom - parentBottom);
// Favor the "start" layout direction over the end when bringing one side or the other
// of a large rect into view.
final int dx;
if (ViewCompat.getLayoutDirection(parent) == ViewCompat.LAYOUT_DIRECTION_RTL) {
dx = offScreenRight != 0 ? offScreenRight : offScreenLeft;
} else {
dx = offScreenLeft != 0 ? offScreenLeft : offScreenRight;
}
// Favor bringing the top into view over the bottom
final int dy = offScreenTop != 0 ? offScreenTop : offScreenBottom;
if (dx != 0 || dy != 0) {
if (immediate) {
parent.scrollBy(dx, dy);
} else {
parent.smoothScrollBy(dx, dy);
}
return true;
}
return false;
}
public boolean onRequestChildFocus(RecyclerView parent, View child, View focused) {
return false;
}
public void onAdapterChanged(Adapter oldAdapter, Adapter newAdapter) {
}
public boolean onAddFocusables(RecyclerView recyclerView, ArrayList views,
int direction, int focusableMode) {
return false;
}
public void onItemsAdded(RecyclerView recyclerView, int positionStart, int itemCount) {
}
public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int itemCount) {
}
public int computeHorizontalScrollExtent(State state) {
return 0;
}
public int computeHorizontalScrollOffset(State state) {
return 0;
}
public int computeHorizontalScrollRange(State state) {
return 0;
}
public int computeVerticalScrollExtent(State state) {
return 0;
}
public int computeVerticalScrollOffset(State state) {
return 0;
}
public int computeVerticalScrollRange(State state) {
return 0;
}
public void onMeasure(Recycler recycler, State state, int widthSpec, int heightSpec) {
final int widthMode = MeasureSpec.getMode(widthSpec);
final int heightMode = MeasureSpec.getMode(heightSpec);
final int widthSize = MeasureSpec.getSize(widthSpec);
final int heightSize = MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
switch (widthMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
width = widthSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
width = getMinimumWidth();
break;
}
switch (heightMode) {
case MeasureSpec.EXACTLY:
case MeasureSpec.AT_MOST:
height = heightSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
height = getMinimumHeight();
break;
}
setMeasuredDimension(width, height);
}
public void setMeasuredDimension(int widthSize, int heightSize) {
mRecyclerView.setMeasuredDimension(widthSize, heightSize);
}
public int getMinimumWidth() {
return ViewCompat.getMinimumWidth(mRecyclerView);
}
public int getMinimumHeight() {
return ViewCompat.getMinimumHeight(mRecyclerView);
}
public Parcelable onSaveInstanceState() {
return null;
}
public void onRestoreInstanceState(Parcelable state) {
}
void stopSmoothScroller() {
if (mSmoothScroller != null) {
mSmoothScroller.stop();
}
}
private void onSmoothScrollerStopped(SmoothScroller smoothScroller) {
if (mSmoothScroller == smoothScroller) {
mSmoothScroller = null;
}
}
void removeAndRecycleAllViews(Recycler recycler) {
for (int i = getChildCount() - 1; i >= 0; i--) {
removeAndRecycleViewAt(i, recycler);
}
}
}
public static abstract class ItemDecoration {
public void onDraw(Canvas c, RecyclerView parent) {
}
public void onDrawOver(Canvas c, RecyclerView parent) {
}
public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
outRect.set(0, 0, 0, 0);
}
}
public interface onItemTouchListener {
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e);
public void onTouchEvent(RecyclerView rv, MotionEvent e);
}
public interface onScrollListener {
public void onScrollStateChanged(int newState);
public void onScrolled(int dx, int dy);
}
public interface RecyclerListener {
public void onViewRecycled(ViewHolder holder);
}
public interface onItemClickListener {
void onItemClick(View view, int position);
}
public static onItemClickListener monItemClickListener = null;
public void setonItemClickListener(onItemClickListener listener) {
monItemClickListener = listener;
}
public final onItemClickListener getonItemClickListener() {
return mOnItemClickListener;
}
public static abstract class ViewHolder implements OnClickListener{
public final View itemView;
int mPosition = NO_POSITION;
int mOldPosition = NO_POSITION;
long mItemId = NO_ID;
int mItemViewType = INVALID_TYPE;
static final int FLAG_BOUND = 1 << 0;
static final int FLAG_UPDATe = 1 << 1;
static final int FLAG_INVALID = 1 << 2;
static final int FLAG_REMOVED = 1 << 3;
static final int FLAG_NOT_RECYCLABLE = 1 << 4;
private int mFlags;
private int mIsRecyclableCount = 0;
// If non-null, view is currently considered scrap and may be reused for other data by the
// scrap container.
private Recycler mScrapContainer = null;
@Override
public void onClick(View v) {
if (monItemClickListener != null) {
mOnItemClickListener.onItemClick(itemView, getPosition());
}
}
public ViewHolder(View itemView) {
if (itemView == null) {
throw new IllegalArgumentException("itemView may not be null");
}
this.itemView = itemView;
this.itemView.setonClickListener(this);
}
void offsetPosition(int offset) {
if (mOldPosition == NO_POSITION) {
mOldPosition = mPosition;
}
mPosition += offset;
}
void clearOldPosition() {
mOldPosition = NO_POSITION;
}
public final int getPosition() {
return mOldPosition == NO_POSITION ? mPosition : mOldPosition;
}
public final long getItemId() {
return mItemId;
}
public final int getItemViewType() {
return mItemViewType;
}
boolean isScrap() {
return mScrapContainer != null;
}
void unScrap() {
mScrapContainer.unscrapView(this);
mScrapContainer = null;
}
void setScrapContainer(Recycler recycler) {
mScrapContainer = recycler;
}
boolean isInvalid() {
return (mFlags & FLAG_INVALID) != 0;
}
boolean needsUpdate() {
return (mFlags & FLAG_UPDATE) != 0;
}
boolean isBound() {
return (mFlags & FLAG_BOUND) != 0;
}
boolean isRemoved() {
return (mFlags & FLAG_REMOVED) != 0;
}
void setFlags(int flags, int mask) {
mFlags = (mFlags & ~mask) | (flags & mask);
}
void addFlags(int flags) {
mFlags |= flags;
}
void clearFlagsForSharedPool() {
mFlags = 0;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("ViewHolder{" +
Integer.toHexString(hashCode()) + " position=" + mPosition + " id=" + mItemId);
if (isScrap()) sb.append(" scrap");
if (isInvalid()) sb.append(" invalid");
if (!isBound()) sb.append(" unbound");
if (needsUpdate()) sb.append(" update");
if (isRemoved()) sb.append(" removed");
sb.append("}");
return sb.toString();
}
public final void setIsRecyclable(boolean recyclable) {
mIsRecyclableCount = recyclable ? mIsRecyclableCount - 1 : mIsRecyclableCount + 1;
if (mIsRecyclableCount < 0) {
mIsRecyclableCount = 0;
Log.e(VIEW_LOG_TAG, "isRecyclable decremented below 0: " +
"unmatched pair of setIsRecyable() calls");
} else if (!recyclable && mIsRecyclableCount == 1) {
mFlags |= FLAG_NOT_RECYCLABLE;
} else if (recyclable && mIsRecyclableCount == 0) {
mFlags &= ~FLAG_NOT_RECYCLABLE;
}
}
public final boolean isRecyclable() {
return (mFlags & FLAG_NOT_RECYCLABLE) == 0 &&
!ViewCompat.hasTransientState(itemView);
}
}
private static class UpdateOp {
public static final int ADD = 0;
public static final int REMOVE = 1;
public static final int UPDATE = 2;
static final int POOL_SIZE = 30;
public int cmd;
public int positionStart;
public int itemCount;
public UpdateOp(int cmd, int positionStart, int itemCount) {
this.cmd = cmd;
this.positionStart = positionStart;
this.itemCount = itemCount;
}
}
UpdateOp obtainUpdateOp(int cmd, int positionStart, int itemCount) {
UpdateOp op = mUpdateOpPool.acquire();
if (op == null) {
op = new UpdateOp(cmd, positionStart, itemCount);
} else {
op.cmd = cmd;
op.positionStart = positionStart;
op.itemCount = itemCount;
}
return op;
}
void recycleUpdateOp(UpdateOp op) {
mUpdateOpPool.release(op);
}
public static class LayoutParams extends MarginLayoutParams {
ViewHolder mViewHolder;
final Rect mDecorInsets = new Rect();
boolean mInsetsDirty = true;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(MarginLayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(LayoutParams source) {
super((ViewGroup.LayoutParams) source);
}
public boolean viewNeedsUpdate() {
return mViewHolder.needsUpdate();
}
public boolean isViewInvalid() {
return mViewHolder.isInvalid();
}
public boolean isItemRemoved() {
return mViewHolder.isRemoved();
}
public int getViewPosition() {
return mViewHolder.getPosition();
}
}
public static abstract class AdapterDataObserver {
public void onChanged() {
// Do nothing
}
public void onItemRangeChanged(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeInserted(int positionStart, int itemCount) {
// do nothing
}
public void onItemRangeRemoved(int positionStart, int itemCount) {
// do nothing
}
}
public static abstract class SmoothScroller {
private int mTargetPosition = RecyclerView.NO_POSITION;
private RecyclerView mRecyclerView;
private LayoutManager mLayoutManager;
private boolean mPendingInitialRun;
private boolean mRunning;
private View mTargetView;
private final Action mRecyclingAction;
public SmoothScroller() {
mRecyclingAction = new Action(0, 0);
}
void start(RecyclerView recyclerView, LayoutManager layoutManager) {
mRecyclerView = recyclerView;
mLayoutManager = layoutManager;
if (mTargetPosition == RecyclerView.NO_POSITION) {
throw new IllegalArgumentException("Invalid target position");
}
mRecyclerView.mState.mTargetPosition = mTargetPosition;
mRunning = true;
mPendingInitialRun = true;
mTargetView = findViewByPosition(getTargetPosition());
onStart();
mRecyclerView.mViewFlinger.postonAnimation();
}
public void setTargetPosition(int targetPosition) {
mTargetPosition = targetPosition;
}
public LayoutManager getLayoutManager() {
return mLayoutManager;
}
final protected void stop() {
if (!mRunning) {
return;
}
onStop();
mRecyclerView.mState.mTargetPosition = RecyclerView.NO_POSITION;
mTargetView = null;
mTargetPosition = RecyclerView.NO_POSITION;
mPendingInitialRun = false;
mRunning = false;
// trigger a cleanup
mLayoutManager.onSmoothScrollerStopped(this);
// clear references to avoid any potential leak by a custom smooth scroller
mLayoutManager = null;
mRecyclerView = null;
}
public boolean isPendingInitialRun() {
return mPendingInitialRun;
}
public boolean isRunning() {
return mRunning;
}
public int getTargetPosition() {
return mTargetPosition;
}
private void onAnimation(int dx, int dy) {
if (!mRunning || mTargetPosition == RecyclerView.NO_POSITION) {
stop();
}
mPendingInitialRun = false;
if (mTargetView != null) {
// verify target position
if (getChildPosition(mTargetView) == mTargetPosition) {
onTargetFound(mTargetView, mRecyclerView.mState, mRecyclingAction);
mRecyclingAction.runInNecessary(mRecyclerView);
stop();
} else {
Log.e(TAG, "Passed over target position while smooth scrolling.");
mTargetView = null;
}
}
if (mRunning) {
onSeekTargetStep(dx, dy, mRecyclerView.mState, mRecyclingAction);
mRecyclingAction.runInNecessary(mRecyclerView);
}
}
public int getChildPosition(View view) {
return mRecyclerView.getChildPosition(view);
}
public int getChildCount() {
return mRecyclerView.getChildCount();
}
public View findViewByPosition(int position) {
return mRecyclerView.mLayout.findViewByPosition(position);
}
public void instantScrollToPosition(int position) {
mRecyclerView.scrollToPosition(position);
}
protected void onChildAttachedToWindow(View child) {
if (getChildPosition(child) == getTargetPosition()) {
mTargetView = child;
if (DEBUG) {
Log.d(TAG, "smooth scroll target view has been attached");
}
}
}
protected void normalize(PointF scrollVector) {
final double magnitute = Math.sqrt(scrollVector.x * scrollVector.x + scrollVector.y *
scrollVector.y);
scrollVector.x /= magnitute;
scrollVector.y /= magnitute;
}
abstract protected void onStart();
abstract protected void onStop();
abstract protected void onSeekTargetStep(int dx, int dy, State state, Action action);
abstract protected void onTargetFound(View targetView, State state, Action action);
public static class Action {
public static final int UNDEFINED_DURATION = Integer.MIN_VALUE;
private int mDx;
private int mDy;
private int mDuration;
private Interpolator mInterpolator;
private boolean changed = false;
// we track this variable to inform custom implementer if they are updating the action
// in every animation callback
private int consecutiveUpdates = 0;
public Action(int dx, int dy) {
this(dx, dy, UNDEFINED_DURATION, null);
}
public Action(int dx, int dy, int duration) {
this(dx, dy, duration, null);
}
public Action(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
}
private void runInNecessary(RecyclerView recyclerView) {
if (changed) {
validate();
if (mInterpolator == null) {
if (mDuration == UNDEFINED_DURATION) {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy);
} else {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration);
}
} else {
recyclerView.mViewFlinger.smoothScrollBy(mDx, mDy, mDuration, mInterpolator);
}
consecutiveUpdates ++;
if (consecutiveUpdates > 10) {
// A new action is being set in every animation step. This looks like a bad
// implementation. Inform developer.
Log.e(TAG, "Smooth Scroll action is being updated too frequently. Make sure"
+ " you are not changing it unless necessary");
}
changed = false;
} else {
consecutiveUpdates = 0;
}
}
private void validate() {
if (mInterpolator != null && mDuration < 1) {
throw new IllegalStateException("If you provide an interpolator, you must"
+ " set a positive duration");
} else if (mDuration < 1) {
throw new IllegalStateException("Scroll duration must be a positive number");
}
}
public int getDx() {
return mDx;
}
public void setDx(int dx) {
changed = true;
mDx = dx;
}
public int getDy() {
return mDy;
}
public void setDy(int dy) {
changed = true;
mDy = dy;
}
public int getDuration() {
return mDuration;
}
public void setDuration(int duration) {
changed = true;
mDuration = duration;
}
public Interpolator getInterpolator() {
return mInterpolator;
}
public void setInterpolator(Interpolator interpolator) {
changed = true;
mInterpolator = interpolator;
}
public void update(int dx, int dy, int duration, Interpolator interpolator) {
mDx = dx;
mDy = dy;
mDuration = duration;
mInterpolator = interpolator;
changed = true;
}
}
}
static class AdapterDataObservable extends Observable {
public boolean hasObservers() {
return !mObservers.isEmpty();
}
public void notifyChanged() {
// since onChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onChanged();
}
}
public void notifyItemRangeChanged(int positionStart, int itemCount) {
// since onItemRangeChanged() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeChanged(positionStart, itemCount);
}
}
public void notifyItemRangeInserted(int positionStart, int itemCount) {
// since onItemRangeInserted() is implemented by the app, it could do anything,
// including removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeInserted(positionStart, itemCount);
}
}
public void notifyItemRangeRemoved(int positionStart, int itemCount) {
// since onItemRangeRemoved() is implemented by the app, it could do anything, including
// removing itself from {@link mObservers} - and that could cause problems if
// an iterator is used on the ArrayList {@link mObservers}.
// to avoid such problems, just march thru the list in the reverse order.
for (int i = mObservers.size() - 1; i >= 0; i--) {
mObservers.get(i).onItemRangeRemoved(positionStart, itemCount);
}
}
}
static class SavedState extends baseSavedState {
Parcelable mLayoutState;
SavedState(Parcel in) {
super(in);
mLayoutState = in.readParcelable(LayoutManager.class.getClassLoader());
}
SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeParcelable(mLayoutState, 0);
}
private void copyFrom(SavedState other) {
mLayoutState = other.mLayoutState;
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
public static class State {
private int mTargetPosition = RecyclerView.NO_POSITION;
private ArrayMap mPreLayoutHolderMap =
new ArrayMap();
private ArrayMap mPostLayoutHolderMap =
new ArrayMap();
private SparseArray
以上所述是小编给大家介绍的解决RecyclerView无法onItemClick问题的两种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!



