转载自:Android recyclerview的滑动到指定的item
注意点
1.滑动到指定位置的方法要写在数据真正加载完成以后,而不是加载数据方法的后面。
2.指定的位置是否可见。
快速定位
public static void MoveToPosition(int n) { manager.scrollToPosition(n); }
缓慢定位(借鉴网络上整理)
/** * 缓慢滑动 * <p> * 当指定位置位于第一个可见位置之上时,可以滚动,利用smoothScrollToPosition实现 * 当指定位置位于可视位置之间时,得到距离顶部的距离,然后smoothScrollBy向上滚动固定的距离 * 当指定的位置位于最后一个可见位置之下时,可以滚动,利用利用smoothScrollToPosition实现实现 */ public void moveToPosition(int position) { int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0)); int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1)); if (position < firstItem || position > lastItem) { mRecyclerView.smoothScrollToPosition(position); } else { int movePosition = position - firstItem; int top = mRecyclerView.getChildAt(movePosition).getTop(); mRecyclerView.smoothScrollBy(0, top); } } 另一种获得可见位置的方法 public void moveToPosition(RecyclerView recyclerView, int position) { RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); //因为只有LinearLayoutManager 才有获得可见位置的方法 if (layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager; int firstItem = linearLayoutManager.findFirstVisibleItemPosition(); int lastItem = linearLayoutManager.findLastVisibleItemPosition(); if (position < firstItem || position > lastItem) { mRecyclerView.smoothScrollToPosition(position); } else { int movePosition = position - firstItem; int top = mRecyclerView.getChildAt(movePosition).getTop(); mRecyclerView.smoothScrollBy(0, top); } } }