您的位置:首页 > 其它

RecyclerView定位,点击项自动滑动到中央

2016-12-29 17:57 295 查看
http://stackoverflow.com/questions/38416146/recyclerview-smoothscroll-to-position-in-the-center-android

改写SmoothScroller计算距离,达到smooth滑动到指定位置的效果,解决指定位置可见就不滑动的问题

public class CenterLayoutManager extends LinearLayoutManager {

public CenterLayoutManager(Context context) {
super(context);
}

public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}

public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}

private static class CenterSmoothScroller extends LinearSmoothScroller {

CenterSmoothScroller(Context context) {
super(context);
}

@Override
public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐