需求 将recyclerview滑动到指定位置 且该位置为第一个可见位置
方式一 LayoutManager.scrollToPositionWithOffset
int toPosition ((LinearLayoutManager)rvSaleMonth.getLayoutManager()).scrollToPositionWithOffset(toPosition, 0);
方式二 RecyclerView.scrollToPosition RecyclerView.scrollBy RecyclerView.post
private void moveToPosition(int toPosition){
int firstPosition ((LinearLayoutManager)rvSaleMonth.getLayoutManager()).findFirstVisibleItemPosition();
int lastPostition ((LinearLayoutManager)rvSaleMonth.getLayoutManager()).findLastVisibleItemPosition();
if (toPosition firstPosition){
rvSaleMonth.scrollToPosition(toPosition);
}else if (toPosition lastPostition){
int top rvSaleMonth.getChildAt(toPosition - firstPosition).getTop();
rvSaleMonth.scrollBy(0, top);
}else {
//先滑动到可见 需要二次滑动
rvSaleMonth.scrollToPosition(toPosition);
rvSaleMonth.post(() - {
//进行第二次滑动
int first ((LinearLayoutManager)rvSaleMonth.getLayoutManager()).findFirstVisibleItemPosition();
View childView rvSaleMonth.getChildAt(toPosition - first);
if (childView ! null){
int top childView.getTop();
rvSaleMonth.scrollBy(0, top);
}
注
1 要滑动的位置比可见位置小 则直接scrollToPosition即可
2 滑动位置在可见位置区间内 则需要根据子view和父view顶部间距离进行移动
3 要滑动的位置比可见位置大 则需要先通过scrollToPosition移至可见位置 位置非顶部 再根据子view和父view顶部间距离进行移动
4 由于scrollToPosition不触发onScrollListener 不能通过监听滑动状态来进行 3 中的二次滑动 但由于RecyclerView滑动结束才执行post的run方法 可以在run方法中进行二次滑动
5 另外补充一下smoothScrollToPosition方法是回触发OnScrollListener的 使用该方法进行滑动时可以通过监听状态进行二次滑动



