將列表滑動到某個item一般都使用scrollToPosition()方法,但是這個方法有個弊端,只要傳入的item索引是當前可見的不管它的位置在頭部尾部還是中間就不會滑動。
效果圖:
我遇到的需求是需要將指定item滑動到可見區域的第一個位置,解決辦法如下:
LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(rvEpisode.getContext()){
@Override
protected int getHorizontalSnapPreference() {
//需要放在末尾則返回SNAP_TO_END
return SNAP_TO_START;
}
@Override
protected int getVerticalSnapPreference() {
//需要放在末尾則返回SNAP_TO_END
return SNAP_TO_START;
}
};
//傳入item索引
linearSmoothScroller.setTargetPosition(position);
manager.startSmoothScroll(linearSmoothScroller);