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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章