Android App页面滑动标题栏颜色渐变

通常,我们会被要求实现类似支付宝首页的特效:随着界面的滑动,标题栏的背景透明度渐变。
在实际开发中,常见的滑动有列表RecyclerView(ListView)滑动,NestedScrollView(ScrollView)嵌套滑动等等。
本文主要从上述两方面来探讨滑动效果。

一、RecyclerView滑动标题栏渐变

废话不多说,直接撸代码:
布局文件如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@color/white"
    tools:context=".scroll_toolbar.ScrollToolBarActivity">

    <!-- title标题栏-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white">

        <ImageView
            android:id="@+id/ivBack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="@dimen/qb_px_20"
            android:gravity="center_vertical"
            android:src="@drawable/theme_toolbar_btn_back_fg_normal0"
            android:textColor="#ffffff" />

        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#666666"
            android:textSize="16sp"
            android:padding="@dimen/qb_px_20"
            android:text="RecyclerView控制titleBar渐变"/>
    </android.support.v7.widget.Toolbar>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvZhangjie"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="@dimen/qb_px_50"
        android:layout_marginRight="@dimen/qb_px_50"
        android:layout_marginTop="@dimen/qb_px_20"
        android:background="@color/back_ground"/>
</LinearLayout>

Java代码如下:

private void toolBarColor(){
        Toolbar toolbar = findViewById(R.id.toolbar);
        ImageView  ivBack = findViewById(R.id.ivBack);
        TextView tvName = findViewById(R.id.tvName);
        RecyclerView  rvZhangjie = findViewById(R.id.rvZhangjie);
        List<String> stringList = dealData();
        ScrollAdapter scrollAdapter = new ScrollAdapter(this, stringList);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvZhangjie.setLayoutManager(manager);
        rvZhangjie.setAdapter(scrollAdapter);

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

上面代码中的 dealData()方法很简单就是想一个String型List里面添加数据,没什么难度。

关键点在于给rvZhangjie.addOnScrollListener()也就是给RecyclerView设置滑动监听,并复写onScrolled()方法。该方法里面3个参数:

第一个RecyclerView recyclerView,这个很明显就是目标RecyclerView;
第二个int dx,表示RecyclerView在水平X方向的相对滑动量;
第三个int dy,表示RecyclerView在垂直Y方向的相对滑动量;

我们可以通过累加计算RecyclerView滑动的距离相对于指定距离的百分比,来计算透明度的变化量:

mDistanceY += dy;
float scale = (float) mDistanceY / toolbarHeight;
float alpha = scale * 255;

最后再将alpha透明度值设置给ToolBar:

 toolbar.setBackgroundColor(Color.argb((int) alpha, 255, 0, 0));

二、NestedScrollView滑动标题栏渐变

其实NestedScrollView滑动渐变和RecyclerView的滑动渐变原理是一样的,本质上都是监听View滑动的距离,通过距离换算成透明度值。只不过二者的滑动偏移量稍有点不同。

代码细节我就不贴出来了,就说说关键的对NestedScrollView的监听和偏移量的处理:

nsvScroolBack.setOnScrollChangeListener(new View.OnScrollChangeListener() {
        @Override
        public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            //scrollY > oldScrollY:向上滑动
            //scrollY < oldScrollY:向下滑动
            // scrollY:滚动过的距离。
            toolbarHeight = toolbar.getBottom() * 1.5f;
            if (scrollY <= toolbarHeight){
                float scale = (float)scrollY / toolbarHeight;
                float alpha =scale * 255;
                toolbar.setBackgroundColor(Color.argb((int) alpha, 255, 0, 0));
            }else {
                toolbar.setBackgroundColor(Color.BLUE);
            }
        }
    });

通过上面的代码,很容易发现NestedScrollView滑动渐变和RecyclerView的滑动渐变就一回事。代码实现上差别很细微。不同的是RecyclerView的滑动渐变哪里,我们要通过对dy的累加来获得RecyclerView在垂直方向的滑动偏移量。而在NestedScrollView的滑动渐变里面,NestedScrollView在x或者y方向的滑动偏移量,系统已经帮我们计算出来了:scrollX或者scrollY。然后进行透明度的计算即可。

录制了一个小视频,不过没发传上来。。。汗!!!

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现这个效果可以采用两种方案: 1. 使用 CoordinatorLayout 实现 CoordinatorLayout 是一个非常强大的布局容器,它可以协调多个子 View 的交互行为。在这个场景下,我们可以将标题栏作为 CoordinatorLayout 的直接子 View,将 ScrollView 作为标题栏的兄弟 View,然后使用 app:layout_behavior 属性指定标题栏的行为为 AppBarLayout.ScrollingViewBehavior,这样当 ScrollView 滑动时,标题栏就会自动滑动。 示例代码如下: ```xml <androidx.coordinatorlayout.widget.CoordinatorLayout android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"> <com.google.android.material.appbar.MaterialToolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:title="My Title" /> </com.google.android.material.appbar.AppBarLayout> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <!-- Your content here --> </ScrollView> </androidx.coordinatorlayout.widget.CoordinatorLayout> ``` 需要注意的是,这种方案需要使用 AndroidX 库中的 CoordinatorLayout 和 Material Design 组件库中的 AppBarLayout 和 MaterialToolbar。 2. 使用自定义 Behavior 实现 如果你不想使用 CoordinatorLayout,或者你需要实现一些比较特殊的效果,那么可以考虑使用自定义 Behavior 实现。具体来说,我们可以定义一个 Behavior,继承自 AppBarLayout.ScrollingViewBehavior,并重写 onNestedPreScroll 方法,在 ScrollView 滑动之前处理标题栏滑动。 示例代码如下: ```java public class MyBehavior extends AppBarLayout.ScrollingViewBehavior { public MyBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onNestedPreScroll(CoordinatorLayout coordinatorLayout, View child, View target, int dx, int dy, int[] consumed) { // 计算标题栏需要滑动的距离 int distance = Math.min(child.getHeight(), dy); // 滑动标题栏 child.setTranslationY(-distance); // 更新 consumed 数组,表示已经消耗了滑动距离 consumed[1] = distance; return true; } } ``` 然后在布局文件中将标题栏的 Behavior 设置为我们定义的 MyBehavior: ```xml <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_behavior=".MyBehavior"> <com.google.android.material.appbar.MaterialToolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:title="My Title" /> </com.google.android.material.appbar.AppBarLayout> ``` 需要注意的是,这种方案需要手动处理标题栏滑动,因此需要在 onNestedPreScroll 方法中计算标题栏需要滑动的距离,并使用 setTranslationY 方法滑动标题栏。同时,需要更新 consumed 数组,表示已经消耗了滑动距离,这样才能确保滑动事件正确地传递给 ScrollView
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值