boolean move = false;
int mIndex = 0;
private void moveToPosition(int index) {
mIndex = index;
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) comment_rl.getLayoutManager();
//获取当前recycleView屏幕可见的第一项和最后一项的Position
int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
int lastItem = linearLayoutManager.findLastVisibleItemPosition();
//然后区分情况
if (index <= firstItem) {
//当要置顶的项在当前显示的第一个项的前面时
comment_rl.scrollToPosition(index);
} else if (index <= lastItem) {
//当要置顶的项已经在屏幕上显示时,计算它离屏幕原点的距离
int top = comment_rl.getChildAt(index - firstItem).getTop();
comment_rl.scrollBy(0, top);
} else {
//当要置顶的项在当前显示的最后一项的后面时
comment_rl.scrollToPosition(index);
//记录当前需要在RecyclerView滚动监听里面继续第二次滚动
move = true;
}
}
private class RcvScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// if (mShouldScroll && newState == RecyclerView.SCROLL_STATE_IDLE) {
// mShouldScroll = false;
// LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getRecyclerView().getLayoutManager();
// int n = nextPosition - linearLayoutManager.findFirstVisibleItemPosition();
// if (n >= 0 && n < getRecyclerView().getChildCount()) {
// //获取要置顶的项顶部距离RecyclerView顶部的距离
// int top = getRecyclerView().getChildAt(n).getTop();
// //进行第二次滚动(最后的距离)
// getRecyclerView().smoothScrollBy(0, top);
// }
// }
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//在这里进行第二次滚动(最后的距离)
if (move) {
move = false;
//获取要置顶的项在当前屏幕的位置,mIndex是记录的要置顶项在RecyclerView中的位置
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) comment_rl.getLayoutManager();
int n = mIndex - linearLayoutManager.findFirstVisibleItemPosition();
if (0 <= n && n < comment_rl.getChildCount()) {
//获取要置顶的项顶部离RecyclerView顶部的距离
int top = comment_rl.getChildAt(n).getTop();
//最后的移动
comment_rl.scrollBy(0, top);
}
}
}
}