recycleview滚动到指定item,并显示在顶部

项目中要实现这种效果:右边的recycleview需要跟随左边的菜单栏的选择而滚动到指定item,并将该item置顶。其实这种需求很常见。下面来看具体实现代码:

1.滚动到指定item代码:


private boolean needScroll;
private int postion;

private void smoothScrollRecycleviewtoPositionTop(int position) {
        checked = true;
        postion = position;
        //获取第一个和最后一个可见项
        int firstItemPosition = linearLayoutManager.findFirstVisibleItemPosition();
        int lastItemPosition = linearLayoutManager.findLastVisibleItemPosition();
        if (position < firstItemPosition) {
            // 第一种可能:跳转位置在第一个可见位置之前
            rvNav.smoothScrollToPosition(position);
        } else if (position <= lastItemPosition) {
            // 第二种可能:跳转位置在第一个可见位置之后
            rvNav.smoothScrollBy(0, rvNav.getChildAt(position - firstItemPosition).getTop());
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            rvNav.smoothScrollToPosition(position);
            needScroll = true;
        }
    }

2.将item滚动到顶部

        rvNav.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (needScroll == true && (newState == RecyclerView.SCROLL_STATE_IDLE)) {
                    scrollRecycleview();
                }               

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        private void scrollRecycleview() {
                needScroll = false;
               int diff = postion - linearLayoutManager.findFirstVisibleItemPosition();
            if (diff >= 0 && diff < rvNav.getChildCount()) {
            rvNav.smoothScrollBy(0, rvNav.getChildAt(diff).getTop());
        }
    }

------ 本文结束 ------
坚持原创技术分享,您的支持将鼓励我继续创作!