android RecyclerView smoothScrollToPosition 每次都能滾動到頂部


直接使用 smoothScrollToPosition(position) 時,如果要定位的數據在集合下半部分,則滾動結束后,需要顯示的數據是在手機界面地步

可以使用 ((LinearLayoutManager) ((RecyclerView)getView(R.id.rv)).getLayoutManager()).scrollToPositionWithOffset(position, 0) 達到每次滾動結束,數據都是在頂部顯示,但是數據不是平滑滾動的。

如果要實現不論哪種情況,都能讓數據平滑滾動到頂部顯示,需要重寫 LinearLayoutManager

1,覆寫 LinearSmoothScroller

public class TopLinearSmoothScroller extends LinearSmoothScroller {
    public TopLinearSmoothScroller(Context context) {
        super(context);
    }

    @Override
    public int getVerticalSnapPreference() {
        return SNAP_TO_START;
    }
}

 

2,重寫 recyclerview.LinearLayoutManager 的 smoothScrollToPosition 方法

TopLinearSmoothScroller scroller = new TopLinearSmoothScroller(rv.getContext());
LinearLayoutManager layoutManager = new LinearLayoutManager(context) {
    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        super.smoothScrollToPosition(recyclerView, state, position);
        scroller.setTargetPosition(position);
        startSmoothScroll(scroller);
    }
};
rv.setLayoutManager(layoutManager);

 

3,最后調用 smoothScrollToPosition 即可

rv.smoothScrollToPosition(position);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM