在百度上面看到两种实现方式
第一种是将目标item分为是否在第一个可见的item之前(即是否已经被滑动到屏幕上方),或是在第一个item之后,最后一个item之前,或在最后一个可见的item之后(这种方式我并没有去做过)
item在第一个可见item之前,直接用smoothScrollToPosition,则当该item移动到可见范围时,它就在RecyclerView顶部
item在可见范围内,即在第一个可见item之后,最后一个可见item之前,那么这时scrollToPosition失效,需要手动计算该item的view距离顶部的距离,用scrollBy自行移动到置顶位置
item在最后一个可见item之后,用smoothScrollToPosition滑动到可见范围 (此时该item在最后一个位置),再获取该item的view,计算到顶部距离,再监听RecyclerView的滑动,对其进行二次滑动到顶部
贴上该方法主要的实现代码
@From:https://blog.csdn.net/weixin_39428125/article/details/89032646
//标记是否需要二次滑动
private boolean shouldMove;
//需要滑动到的item位置
private int mPosition;
/**
* RecyclerView滑动到指定item函数
*/
private void smoothMoveToPosition(RecyclerView recyclerView, final int position) {
// 获取RecyclerView的第一个可见位置
int firstItem = recyclerView.getChildLayoutPosition(recyclerView.getChildAt(0));
// 获取RecyclerView的最后一个可见位置
int lastItem = recyclerView.getChildLayoutPosition(recyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
if (position < firstItem) {
// 指定item在第一个可见item之前
recyclerView.smoothScrollToPosition(position);
} else if (position <= lastItem) {
// 指定item在可见范围内,即在第一个可见item之后,最后一个可见item之前
int position = position - firstItem;
if (position >= 0 && position < recyclerView.getChildCount()) {
// 计算指定item的view到顶部的距离
int top = recyclerView.getChildAt(position).getTop();
// 手动滑动到顶部
recyclerView.smoothScrollBy(0, top);
}
} else {
// 指定item在最后一个可见item之后,用smoothScrollToPosition滑动到可见范围
// 再监听RecyclerView的滑动,对其进行二次滑动到顶部
recyclerView.smoothScrollToPosition(position);
mPositon = position;
shouldMove = true;
}
}
…………
/**
* 监听RecyclerView的滑动,对需要进行二次滑动的item进行滑动
**/
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if ( shouldMove && RecyclerView.SCROLL_STATE_IDLE == newState) {
shouldMove = false;
smoothMoveToPosition(mRecyclerView, mPosition);
}
}
});
第二种方式就比较的简单,继承LinearSmoothScroll,然后重写里面的getHorizontalSnapPreference(),getVerticalSnapPreference()
这两个方法即
public class TopSmoothScroller extends LinearSmoothScroller {
public TopSmoothScroller(Context context) {
super(context);
}
@Override
protected int getHorizontalSnapPreference() {
return SNAP_TO_START;
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START; // 将子view与父view顶部对齐
}
然后在使用的地方
TopSmoothScroller topSmoothScroller = new TopSmoothScroller(GridViewActivity.this);
topSmoothScroller.setTargetPosition(5);
gridView.getLayoutManager().startSmoothScroll(topSmoothScroller);
就可实现将目标item显示在列表的最前方
此文仅为作为笔记
From https://blog.csdn.net/weixin_39428125/article/details/89032646