1.背景
recyclerview不像listview一样,有精确的返回到固定位置的方法。recyclerview触发指定item到顶部,也是通过两部分处理的。
1.让指定的条目出现到屏幕里,然后计算该条目距离父容器顶端的距离,
2.然后执行向上滑动指定距离,也就实现了滑动到顶部的需求。
2.code
//如点击触发,该pos的item 滑动到顶部
smoothMoveToPosition(recyclerView, pos);
//根据不同的情况,让条目滚动到屏幕内,然后计算偏移量。
private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
if (position < 0)
return;
int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
Log.d(TAG, "smoothMoveToPosition: " + position);
if (position < firstItem) {
mRecyclerView.smoothScrollToPosition(position);
} else if (position <= lastItem) {
int movePosition = position - firstItem;
//计算选中的item,距离顶部的偏移量
if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
int top = mRecyclerView.getChildAt(movePosition).getTop();
mRecyclerView.smoothScrollBy(0, top - mTitleHeight);
}
} else {
// 第三种可能:跳转位置在最后可见项之后,则先调用smoothScrollToPosition将要跳转的位置滚动到可见位置
// 再通过onScrollStateChanged控制再次调用smoothMoveToPosition,执行上一个判断中的方法
mRecyclerView.smoothScrollToPosition(position);
mToPosition = position;
mShouldScroll = true;
}
}
//onScrollStateChanged 中,当滚动完成,再次执行滚动
if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == scrollState) {
mShouldScroll = false;
smoothMoveToPosition(recyclerView, mToPosition);
}