RecyclerView的原生方法
1. smoothScrollToPosition( int position )方法 平滑滚动
2. scrollToPosition(int position) 直接显示,没有平滑效果
查看源码,发现滑动平滑效果,可改变。然后自定义一个LinearLayoutManager ,平滑时间
public class SmoothScrollLayoutManager extends LinearLayoutManager {
public SmoothScrollLayoutManager(Context context) {
super(context);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, final int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
// 返回:滑过1px时经历的时间(ms)。
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 100f / displayMetrics.densityDpi;
}
@Override
protected int getHorizontalSnapPreference() {
return SNAP_TO_START;//具体见源码注释
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;//具体见源码注释
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
}
调用方式:
LinearLayoutManager linelarLayoutManager = new SmoothScrollLayoutManager(this); recycler.setLayoutManager(linelarLayoutManager);
定位时调用:
recycler.smoothScrollToPosition(i);
因为这里的滑动效果是自己定义的,可以根据需要修改滑动时间并置顶。 希望对你用帮助,亲测可用
如果转载,请注明出处https://me.youkuaiyun.com/fepengwang
本文介绍如何自定义RecyclerView的LinearLayoutManager来实现平滑滚动效果。通过重写smoothScrollToPosition方法,可以调整滑动速度和时间,实现更佳的用户体验。
2412

被折叠的 条评论
为什么被折叠?



