Recyclerview指定Item悬浮顶部

1.直接上图   我们需要在和recyclerview 同级别的位置放置一个同样的悬浮框  recyclerview 滑动到第4个item时显示 没滑到则隐藏

Recyclerview指定Item悬浮顶部_第1张图片

 

2.RecyclerView添加滑动监听事件

private LinearLayoutManager linearLayoutManager;
    private int mCurrentPosition = 0;
/**
     * 初始化Listener
     */
    private void initListener() {

        xRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mCurrentPosition != linearLayoutManager.findFirstVisibleItemPosition()) {
                    mCurrentPosition = linearLayoutManager.findFirstVisibleItemPosition();
                    //第3个开始   这个就是你需要从第几个开始悬浮
                    if(mCurrentPosition<3){
                        //这个是在recyclerview同级别的悬浮
                        mBinding.tabIndex.setVisibility(View.GONE);
                    }else if(mCurrentPosition>=3){
                        mBinding.tabIndex.setVisibility(View.VISIBLE);
                        //这个是将同级别的悬浮  放置在顶部的距离  距离顶部多少dp  sumHeight我已经计算好了
                        mBinding.tabIndex.setTop(sumHeight);
                    }

                }
            }
        });
    }





//获取距离顶部的距离
 private void getHeight() {
         mBinding.rlTitleBar.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                mBinding.rlTitleBar.getViewTreeObserver().removeOnPreDrawListener(this);
                sumHeight += mBinding.rlTitleBar.getMeasuredHeight();
                return true;
            }
        });
        mBinding.topSearch.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                mBinding.topSearch.getViewTreeObserver().removeOnPreDrawListener(this);
                sumHeight += mBinding.topSearch.getMeasuredHeight();
                return true;
            }
        });
    }

 

你可能感兴趣的:(Recyclerview指定Item悬浮顶部)