RecyclerView 代码中滚动方法(设置滚动到位置并置顶)

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.csdn.net/fepengwang

猜你喜欢

转载自blog.csdn.net/fepengwang/article/details/88854557
今日推荐