Recyclview实现仿京东淘宝金刚位带滚动进度条

首先先上效果图

Recyclview实现仿京东淘宝金刚位带滚动进度条_第1张图片

整体是一个recycleview列表 下面滚动条是单独的view

监听recycleview列表的滑动,来控制view的滑动

先上布局

 
//滚动条
                    
                        
//背景
                            
//滑块
                            
                        
                    

然后主界面的相关代码

   //金刚位
        icon_bg=mView.findViewById(R.id.icon_bg);
        bar_line = mView.findViewById(R.id.main_line);
        int defpadding = DensityUtil.dip2px(getActivity(), 24);
        double horizontalSpacing = defpadding;
        rcy_icon = mView.findViewById(R.id.rcy_icon);
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.HORIZONTAL, false);
        rcy_icon.setLayoutManager(layoutManager);
        GridSpacingItemDecoration gridSpacingItemDecoration = GridSpacingItemDecoration.newGridItemDecoration(layoutManager, DensityUtil.dip2px(getActivity(), 12f), (int) horizontalSpacing, true);
        if (rcy_icon.getItemDecorationCount() == 0) {
            rcy_icon.addItemDecoration(gridSpacingItemDecoration);
        }
        menuAdapter = new HomeMenuAdapter(getActivity());
        rcy_icon.setAdapter(menuAdapter);

        setScrollBar();




  //金刚位底部滚动条
    private void setScrollBar() {

        rcy_icon.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);

                //当前RcyclerView显示区域的高度。水平列表屏幕从左侧到右侧显示范围
                int extent = recyclerView.computeHorizontalScrollExtent();
                //整体的高度,注意是整体,包括在显示区域之外的。
                int range = recyclerView.computeHorizontalScrollRange();

                //已经滚动的距离,为0时表示已处于顶部。
                int offset = recyclerView.computeHorizontalScrollOffset();
                if (extent==range){
                    bar_line.setVisibility(View.GONE);
                }else {
                    bar_line.setVisibility(View.VISIBLE);
                    //计算出溢出部分的宽度,即屏幕外剩下的宽度
                    float maxEndX = range - extent;
                    //计算比例
                    float proportion = offset / maxEndX;
                    int layoutWidth = icon_bg.getWidth();
                    int indicatorViewWidth = bar_line.getWidth();
                    //可滑动的距离
                    int scrollableDistance = layoutWidth - indicatorViewWidth;
                    //设置滚动条移动
                    bar_line.setTranslationX(scrollableDistance * proportion);
                }
            }

        });
    }

列表很简单  主要是下面滚动条的监听滑动

代码里都有详细的注释  看一下很容易就懂得

放个毒鸡汤  

只有自己强大了  才不会畏惧困难

你可能感兴趣的:(android,android,studio)