RecyclerView滑动到指定Position的⽅法
Question
最近在写 SideBar 的时候遇到⼀个问题,当执⾏ Recyclerview 的 smoothScrollToPosition(position) 的时候,Recyclerview看上去并没有滚动到指定位置。Analysis
当然,这并不是⽅法的bug,⽽是 smoothScrollToPosition(position) 的执⾏效果有三种情况,需要区分。·⽬标position在第⼀个可见项之前 。
这种情况调⽤smoothScrollToPosition能够平滑的滚动到指定位置,并且置顶。·⽬标position在第⼀个可见项之后,最后⼀个可见项之前。 这种情况下,调⽤smoothScrollToPosition不会有任何效果····⽬标position在最后⼀个可见项之后。
这种情况调⽤smoothScrollToPosition会把⽬标项滑动到屏幕最下⽅···Solution
鉴于这三种情况,我想⼤多数情况下都⽆法满⾜我们的滑动要求。为了实现 Recyclerview 把指定 item 滑动到屏幕顶端的需求,我们需要对上⾯三种情况分别处理。
/** ⽬标项是否在最后⼀个可见项之后*/ private boolean mShouldScroll; /** 记录⽬标项位置*/ private int mToPosition;
/**
* 滑动到指定位置
* @param mRecyclerView * @param position */
private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) { // 第⼀个可见位置
int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0)); // 最后⼀个可见位置
int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1)); if (position < firstItem) {
// 如果跳转位置在第⼀个可见位置之前,就smoothScrollToPosition可以直接跳转 mRecyclerView.smoothScrollToPosition(position); } else if (position <= lastItem) {
// 跳转位置在第⼀个可见项之后,最后⼀个可见项之前
// smoothScrollToPosition根本不会动,此时调⽤smoothScrollBy来滑动到指定位置 int movePosition = position - firstItem;
if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) { int top = mRecyclerView.getChildAt(movePosition).getTop(); mRecyclerView.smoothScrollBy(0, top); }
}else {
// 如果要跳转的位置在最后可见项之后,则先调⽤smoothScrollToPosition将要跳转的位置滚动到可见位置 // 再通过onScrollStateChanged控制再次调⽤smoothMoveToPosition,执⾏上⼀个判断中的⽅法 mRecyclerView.smoothScrollToPosition(position); mToPosition = position; mShouldScroll = true; } }
再通过onScrollStateChanged控制再次调⽤smoothMoveToPosition
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (mShouldScroll){
mShouldScroll = false;
smoothMoveToPosition(mRecyclerView,mToPosition); } } }); }
⽬前这个解决⽅法有两个已知的问题
1、当⽬标项在最后⼀个可见项之后的时候,由于我们先执⾏smoothScrollToPosition⽅法,然后在OnScrollListener中执⾏smoothMoveToPosition⽅法,在滑动的时候不够连贯。
2、在⼿动滑动的时候执⾏该⽅法,会有极⼩的概率滑动的位置出现偏差。如果你有更好解决办法,希望不吝指教。
以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。