标题栏随RecyclerView滑动动态修改透明度

 

标题栏随RecyclerView滑动动态修改透明度,其使用是使标题栏覆盖在RecyclerView上方,添加以下方法监听滑动时y轴的变化

 

    private int height = 640;// 滑动开始变色的高,真实项目中此高度是由广告轮播或其他首页view高度决定
    private int overallXScroll = 0;
    recyclerView.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);
                overallXScroll = overallXScroll + dy;// 累加y值 解决滑动一半y值为0
                if (overallXScroll <= 0) {   //设置标题的背景颜色
                    llSearch.setBackgroundColor(Color.argb((int) 0, 41, 193, 246));
                } else if (overallXScroll > 0 && overallXScroll <= height) { //滑动距离小于banner图的高度时,设置背景和字体颜色颜色透明度渐变
                    float scale = (float) overallXScroll / height;
                    float alpha = (255 * scale);
                    llSearch.setBackgroundColor(Color.argb((int) alpha, 41, 193, 246));
                } else {
                    llSearch.setBackgroundColor(Color.argb((int) 255, 41, 193, 246));
                }
            }
        });

如上是之前获取渐变距离的方式,在某些手机上会存在兼容性问题,可以采用如下方式来实现

获取当前position距顶部的距离

  public int getScollYDistance() {
        if (mRecyclerView.getLayoutManager() != null && mRecyclerView.getLayoutManager() instanceof LinearLayoutManager) {
            LinearLayoutManager manager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
            int position = manager.findFirstVisibleItemPosition();
            View firstVisiableChildView = manager.findViewByPosition(position);
            int itemHeight = firstVisiableChildView.getHeight();
            return (position) * itemHeight - firstVisiableChildView.getTop();
        }
        return 0;
    }

使用也是同样的逻辑,这里展示一种隐藏和显示的逻辑,需要可以按照之前的方式改成想要的效果

    mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int range = AutoUtils.getPercentHeightSize(260); //渐变点
            
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                int distance = getScollYDistance();
                if (distance <= range) {
                    setTitleVisible(layout_title_header, false);
                } else {
                    setTitleVisible(layout_title_header, true);
                }
            }
        });

 

 

 

你可能感兴趣的:(Android)