先看效果(由于本人不会制作动图,只能给静态图)
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); } } });这就轻松实现了标题栏渐变