【商城开发一】Android高仿京东标题栏渐变,下拉隐藏(RecyclerView)

开始工作了,第一个项目是一个商城app,分享一下京东商城滑动标题栏渐变,下拉刷新隐藏标题栏的效果。先看看再说

1.先看一下布局文件,是一个刷新控件嵌套一个RecyclerView,head_searche是搜索栏,也就是toolbar了。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.muzi.homepage.SuperSwipeRefreshLayout
        android:id="@+id/superlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </com.muzi.homepage.SuperSwipeRefreshLayout>
    <include layout="@layout/head_searche" />
</RelativeLayout>
2.然后是渐变效果。实例化RecyclerView,重写滑动监听,mDistance是int类型,表示滑动距离。通过判断滑动距离,来改变所搜栏的Alpha值。自己看代码

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

                //当滑动的距离 <= toolbar高度的时候,改变Toolbar背景色的透明度,达到渐变的效果
                if (mDistanceY <= toolbarHeight) {
                    float scale = (float) mDistanceY / toolbarHeight;
                    float alpha = scale * 255;
                    head_search_rr.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                } else {
                    //将标题栏的颜色设置为完全不透明状态
                    head_search_rr.setBackgroundResource(R.color.white);
                }
            }
        });
3.刷新隐藏搜索栏,SuperSwipeRefreshLayout的下拉刷新监听,当滑动的时候设置搜索栏的Visibility为GONE就行了

  /**
         * 下拉刷新
         */
        refreshLayout.setOnPullRefreshListener(new SuperSwipeRefreshLayout.OnPullRefreshListener() {

            @Override
            public void onRefresh() {

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refreshLayout.setRefreshing(false);
                    }
                }, 500);
            }

            @Override
            public void onPullDistance(int distance) {
                if (distance > 0) {
                    head_search_rr.setVisibility(View.GONE);
                } else {
                    head_search_rr.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onPullEnable(boolean enable) {
            }
        });
GitHub代码

猜你喜欢

转载自blog.csdn.net/luckkissmo/article/details/56847998