記錄RecyclerView的位置並進行恢復

//監聽RecyclerView滾動狀態
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if(recyclerView.getLayoutManager() != null) {
            getPositionAndOffset();
        }
    }
});
 
/**
 * 記錄RecyclerView當前位置
 */
private void getPositionAndOffset() {
    LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
    //獲取可視的第一個view
    View topView = layoutManager.getChildAt(0);
    if(topView != null) {
        //獲取與該view的頂部的偏移量
        lastOffset = topView.getTop();
        //獲得該View的數組位置
        lastPosition = layoutManager.getPosition(topView);
    }
}
 
/**
 * 讓RecyclerView滾動到指定位置
 */
private void scrollToPosition() {
    if(mRecyclerView.getLayoutManager() != null && lastPosition >= 0) {
        ((LinearLayoutManager) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
    }
}
相關文章
相關標籤/搜索