滚动到指定位置
由于RecyclerView的布局复用,看不到的item是暂时没有添加到RecyclerView中的,所以要滚动到看不到的item所在位置时,调用smoothScrollToPosition(int position)并不能滚动到目标位置。
实现思路,每次滚动到最后一个可见item之前,循环滚动,直到滚动到目标位置为止。
/**
* 优化了 smoothScrollToPosition()
* Created by zhangjianliang on 2017/11/20
*/
public class MyLinearLayoutManager extends LinearLayoutManager {
/** 目标项是否在最后一个可见项之后 */
private boolean mShouldScroll;
/** 记录目标项位置 */
private int mToPosition;
private Context mContext;
private SmoothScrollListener mSmoothScrollListener = new SmoothScrollListener();
/**
* 滑动到指定位置
*/
public void smoothToPosition(RecyclerView recyclerView, final int position) {
if (recyclerView == null || recyclerView.getChildCount() <= 0) {
return;
}
recyclerView.removeOnScrollListener(mSmoothScrollListener);
recyclerView.addOnScrollListener(mSmoothScrollListener);
smoothMoveToPosition(recyclerView, position);
}
private void smoothMoveToPosition(RecyclerView recyclerView, final int position) {
// 第一个可见位置
int firstItem = recyclerView.getChildLayoutPosition(recyclerView.getChildAt(