RecyclerView滑动时使toolsbar渐变

先看效果(由于本人不会制作动图,只能给静态图)


RecyclerView随着滑动toolsbar颜色开始变化

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <!-- title标题栏-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:actionBarSize">

        <ImageView
            android:id="@+id/iv_back"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_marginLeft="20dp"
            android:gravity="center_vertical"
            android:src="@drawable/icon_back"
            android:textColor="#fff" />

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginRight="40dp"
            android:gravity="center"
            android:textColor="@color/white"
            android:textSize="17sp" />
    </android.support.v7.widget.Toolbar>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_zhangjie"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/title" />


</LinearLayout>
Activity的关键代码

mRecylerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        //滑动的距离
        mDistanceY += dy;
        //toolbar的高度
        int toolbarHeight = mToolbar.getBottom();

        //当滑动的距离 <= toolbar高度的时候,改变Toolbar背景色的透明度,达到渐变的效果
        if (mDistanceY <= toolbarHeight) {
            float scale = (float) mDistanceY / toolbarHeight;
            float alpha = scale * 255;
            mToolbar.setBackgroundColor(Color.argb((int) alpha, 128, 0, 0));
        } else {
            //上述虽然判断了滑动距离与toolbar高度相等的情况,但是实际测试时发现,标题栏的背景色
            //很少能达到完全不透明的情况,所以这里又判断了滑动距离大于toolbar高度的情况,
            //将标题栏的颜色设置为完全不透明状态
            mToolbar.setBackgroundResource(R.color.colorPrimary);
        }

    }
});
这就轻松实现了标题栏渐变




  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值