Android科普知识之recyclerView与标题栏的滑动变色

来源:互联网 发布:程序员表白代码 编辑:程序博客网 时间:2024/05/18 07:54

这种情况就不说了,很多购物的商城都有这样的情况,刚开始标题栏是不存在的,透明的,在列表滑动的时候,开始发生变化,划到一定距离整个标题栏完全出现了。

就是一个透明度的问题,刚开始透明度设置成为1 ,在滑动的时候开始增加这个透明度值。等增加到一定程度,当然就完全显示里。


直接上代码

xml文件:

<?xml version="1.0" encoding="utf-8"?><layout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:omi="http://schemas.android.com/apk/res-auto"    >    <RelativeLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="@color/white"        >        <android.support.v7.widget.RecyclerView            android:id="@+id/recyclerView"            android:layout_width="match_parent"            android:layout_height="wrap_content">        </android.support.v7.widget.RecyclerView>        <com.omi.ui.widget.TopNavigationBar            android:id="@+id/topNavigationBar"            style="@style/TopBarStyle"            omi:centerText="@string/omilive"            omi:leftClick="@{@string/top_left_click}"            omi:leftSrc="@mipmap/back_btn"            omi:rightClick="@{@string/top_right_click}"            omi:rightSrc="@mipmap/sort"            />    </RelativeLayout></layout>

初始化控件之后,声明一个成员变量:float  alpha;  就是透明度

给标题栏设置透明度的方法:

public void setAlpha(float alpha) {    if (alpha == this.alpha) return;    this.alpha = alpha;    myliveBinding.topNavigationBar.setBackgroundAlpha(alpha);}

将透明度赋值给标题栏,并开启滑动监听:

//滑动变色myliveBinding.topNavigationBar.setBackgroundAlpha(alpha);myliveBinding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {    @Override    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();        int position = layoutManager.findFirstVisibleItemPosition();        if (position > 0) {            setAlpha(1);        } else {            View firstView = layoutManager.findViewByPosition(position);            int top = firstView.getTop();            int height = myliveBinding.topNavigationBar.getHeight();            int firstHeight = firstView.getHeight();            setAlpha(Math.min(1f, (float) -top / (float) (firstHeight - height)));        }    }});


0 0