Android进阶之光——Material Design

Material Design

核心思想

Material Design的核心思想,就是将物理世界中的体验带入屏幕,并且去掉物理世界中的杂志,再配合虚拟世界的灵活特性,达到最贴近真实的体验。

Design Support Library 常用控件详解

Snackbar

Snackbar显示在屏幕的底部,包含了文字信息与一个可选的操作按钮,它会在指定时间结束后消失。配合CoordinatorLayout使用,可以在超时之前将它划动删除

  • build.gradle
    implementation 'com.android.support:design:28.0.0'

  • java
 Snackbar.make(activity_main,"SnackBar",Snackbar.LENGTH_LONG)
                .setAction("点击事件", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(MainActivity.this, "SnackBar的点击事件", Toast.LENGTH_SHORT).show();
                    }
                }).setDuration(Snackbar.LENGTH_SHORT).show();

第一个参数是一个View类型的参数,这个View类型的参数是Snackbar的父控件,还有两个参数 一个是显示的文本,一个是持续的时间。setAction是设置点击事件。

TextInputLayout

TextInputLayout是一个容器,和ScrollView一样只接受一个子元素,并且这个子元素是EditText

  • xml布局文件
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TextInpuLayout">
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tl_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        >
        <EditText
            android:id="@+id/et_username"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="username"
            />
    </com.google.android.material.textfield.TextInputLayout>
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/tl_userpwd"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@id/tl_username"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        >
        <EditText
            android:id="@+id/et_userpwd"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="userpwd"
            />
    </com.google.android.material.textfield.TextInputLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

显示错误信息

 tlUserName.setErrorEnabled(true);
 tlUserName.setError("输入错误");

setErrorEnabled():用于显示和隐藏错误提示

FloatingActionButton

负责显示界面基本操作的圆形按钮。可以当作一个Button

  • xml
<com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:backgroundTint="@android:color/holo_red_light"
        android:clickable="true"
        android:elevation="10dp"
        android:src="@drawable/ic_launcher"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/btn_login"
        app:pressedTranslationZ="100dp" />

FloatingActionButton的填充色默认是style.xml文件的colorAccent设定的颜色,当然也可以通过app:backgroundTint来设定背景填充色

  • app:elevation:用来设置正常状态的阴影大小
  • app:pressedTranslationZ:用来设置点击时阴影的大小

TabLayout实现类似网易选项卡的动态滑动效果

  • 配置build.gradle
implementation 'com.google.android.material:material:1.2.1'
  • 主页面布局
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#ADBE107E"
            app:tabMode="scrollable" />


    </com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />
</androidx.appcompat.widget.LinearLayoutCompat>
  • list_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</androidx.recyclerview.widget.RecyclerView>
  • list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/iv_item_card_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars"
        android:src="@drawable/sex"
        />

    <TextView
        android:id="@+id/tv_item_card_main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="TextView"
        app:layout_constraintBottom_toBottomOf="@id/iv_item_card_main"
        app:layout_constraintLeft_toRightOf="@id/iv_item_card_main"
        app:layout_constraintTop_toTopOf="@id/iv_item_card_main" />
</androidx.constraintlayout.widget.ConstraintLayout>

注意这里将TabLayout的app:tabMode="scrollable" 其设置Tab的模式为可滑动的,还可以设置为fixed表示固定不可划动的

  • Java代码
  • Activity

        for (String title : titles) {
            tabs.addTab(tabs.newTab().setText(title));
        }
        ArrayList<Fragment> fragments = new ArrayList<>();
        for (int i = 0; i < titles.size(); i++) {
            fragments.add(new ListFragment());
        }
        FragmentAdapter fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments, titles);
        viewpager.setAdapter(fragmentAdapter);
        //TabLayout联系ViewPager
        tabs.setupWithViewPager(viewpager);
    }
}
  • Fragment
public class ListFragment extends Fragment {

    private RecyclerView mRecycleView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mRecycleView = ((RecyclerView) inflater.inflate(R.layout.list_fragment, container, false));
        return mRecycleView;
    }

    @Override
    public void onViewCreated(@NonNull @org.jetbrains.annotations.NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRecycleView.setLayoutManager(new LinearLayoutManager(mRecycleView.getContext()));
        mRecycleView.setAdapter(new RecycleViewAdapter(getActivity()));
    }
}
  • adapter FragmentAdapter
public class FragmentAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> mFragments;
    private List<String> mTitles;
    public FragmentAdapter(@NonNull @NotNull FragmentManager fm, List<Fragment> fragments,List<String> titles) {
        super(fm,BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        mFragments = fragments;
        mTitles = titles;
    }

    @NonNull
    @NotNull
    @Override
    public Fragment getItem(int position) {
        return mFragments.get(position);
    }

    @Override
    public int getCount() {
        return mFragments.size();
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return mTitles.get(position);
    }
}
  • RecyclerViewAdapter
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {
    private final Context mContext;

    public RecycleViewAdapter(Context mContext) {
        this.mContext = mContext;
    }

    @NonNull
    @NotNull
    @Override
    public RecycleViewAdapter.ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_card_main, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull RecycleViewAdapter.ViewHolder holder, int position) {
        View view = holder.mView;
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "点击了", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public int getItemCount() {
        return 10;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public ViewHolder(@NonNull @NotNull View itemView) {
            super(itemView);
            mView = itemView;
        }
    }

}

用NavigationView实现抽屉菜单

design的抽屉菜单和普通侧拉菜单一样,所有的东西都放在DrawerLayout中,用NavigationView来替代我们此前的自定义控件

  • activity.xml 布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dl_main_drawer"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">
    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"

        >
    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#ADBE107E"
            app:tabMode="fixed" />


    </com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />
    </androidx.appcompat.widget.LinearLayoutCompat>
    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nv_main_navigation"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/navigation_header"
        app:menu="@menu/drawer_view"/>

</androidx.drawerlayout.widget.DrawerLayout>
  • navigation_header.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="288dp"
        android:layout_height="272dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/sex" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="TextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />
</androidx.constraintlayout.widget.ConstraintLayout>
  • drawer_view.xml 菜单文件
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <group android:checkableBehavior="single">

        <item
            android:id="@+id/nav_home"
            android:icon="@drawable/ic_launcher"
            android:title="首页" />

        <item
            android:id="@+id/nav_messages"
            android:icon="@drawable/ic_launcher"
            android:title="事项" />
        <item
            android:id="@+id/nav_friends"
            android:icon="@drawable/ic_launcher"
            android:title="朋友" />
    </group>
    <!--    自动分割线-->
    <item android:title="哈哈">
        <menu>
            <group android:checkableBehavior="single">

                <item
                    android:id="@+id/nav_setting"
                    android:icon="@drawable/ic_launcher"
                    android:title="设置" />
                <item
                    android:id="@+id/nav_other"
                    android:icon="@drawable/ic_launcher"
                    android:title="其他" />
            </group>
        </menu>
    </item>

</menu>
  • java代码
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_neteasy_tab);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        ActionBar ab = getSupportActionBar();
        ab.setTitle("虎牙直播");
//        ab.setHomeAsUpIndicator(android.R.drawable.arrow_down_float);
        ab.setHomeButtonEnabled(true);
        ab.setDisplayHomeAsUpEnabled(true);
        nvMainNavigation.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull @NotNull MenuItem item) {
                item.setChecked(true);
                String title = item.getTitle().toString();
                Toast.makeText(NetEasyTabActivity.this, title, Toast.LENGTH_SHORT).show();
                dlMainDrawer.closeDrawers();
                return true;
            }
        });
        initViewPager();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.drawer_view, menu);
        menu.add("测试动态添加");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_home:
                dlMainDrawer.openDrawer(GravityCompat.START);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

用CoordinatorLayout实现Toolbar隐藏和折叠

CoordinatorLayout是用来组织其子View之间协作的一个父容器View。默认情况下CoordinatorLayout可以理解为一个FrameLayout,它的布局方式默认是一层一层叠上去的。

  • activity布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cdl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#ADBE107E"
            app:tabMode="scrollable" />


    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

app:layout_scrollFlags="scroll|enterAlways"这个属性设置滚动事件,属性里面必须至少启用scroll这个flag,这样这个view才会滚出屏幕,否则将一直固定再顶部

CoordinatorLayout结合CollapsingToolbarLayout实现Toolbar折叠效果

CollapsingToolbarLayout的作用是提供一个可以折叠的Toolbar。CollapsingToolbarLayout继承自FrameLayout。它设置layout_scrollFlag属性,可以控制包含再CollapsingToolbarLayout中的控件,将布局中的控件包含起来作为一个可折叠的Toolbar

  • 改造activity布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cdl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fitsSystemWindows="true"
            android:id="@+id/collapsing_toolbar"
            app:contentScrim="@color/yello"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
           >
            <ImageView
                android:id="@+id/iv_backdrop"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:src="@drawable/sex"/>
        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
  • app:contentScrim="" 用来设置CollapsingToolbarLayout收缩后最顶部的颜色
  • app:expandedTitleGravity="left|bottom" 表示将此CollapsingToolbarLayout完全展开后,title所处的位置
  • app:collapsedTitleGravity="left" 表示当头部的视图消失后title将回归到Toolbar的位置
  • app:layout_scrillFlags="" 用来设置滚动事件,属性里面必须至少启用scroll这个flag,这样这个view才会滚动出屏幕,否则它将一直固定再顶部。

关于@string/appbar_scrolling_view_behivor 我们需要定义AppBarLayout与滚动视图之间的联系,Design中包含了一个特殊的字符串资源@string/appbar_scrolling_view_behivor,它和AppBarLayout.ScrollingViewBehivor相匹配,用来通知AppBarLayout何时发生了滚动事件,这个Behaivor需要设置在触发事件的View之上,所以我们需要给RecyclerView设置

自定义Behvior

CoordinatorLayout中最经典的设计就是Behavior,我们也可以自定义Behavior来实现自己的组件和华东交互。

  1. 定义的View监听CoordinatorLayout里的滑动状态
  2. 自定义View监听另一个View的状态变化
  • 布局文件
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/cdl_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".activity.NetEasyTabActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:expanded="false">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentScrim="@color/yello"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/iv_backdrop"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:scaleType="fitStart"
                android:src="@drawable/sex" />

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <androidx.appcompat.widget.LinearLayoutCompat
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@android:color/holo_blue_dark"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="15dp"
<!--添加自定义behavior-->        app:layout_behavior="com.probuing.androidlight.behavior.FooterBehavior">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="自定义Behavior"
            android:textColor="@color/white" />
    </androidx.appcompat.widget.LinearLayoutCompat>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
  • 自定义behavior
package com.probuing.androidlight.behavior;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewPropertyAnimator;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.ViewCompat;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;

import org.jetbrains.annotations.NotNull;

public class FooterBehavior extends CoordinatorLayout.Behavior<View> {
    //滑动距离累加值
    private int directionChange;
    public FooterBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }


    @Override
    public boolean onStartNestedScroll(@NonNull @NotNull CoordinatorLayout coordinatorLayout, @NonNull @NotNull View child, @NonNull @NotNull View directTargetChild, @NonNull @NotNull View target, int axes) {
        return (axes & ViewCompat.SCROLL_AXIS_VERTICAL)!=0;
    }

    @Override
    public void onNestedPreScroll(@NonNull @NotNull CoordinatorLayout coordinatorLayout,
                                  @NonNull @NotNull View child, @NonNull @NotNull View target,
                                  int dx,
                                  int dy,
                                  @NonNull @NotNull int[] consumed,
                                  int type) {
        if (dy>0&&directionChange<0||dy<0&&directionChange>0) {
            child.animate().cancel();
            directionChange=0;
        }
        directionChange+=dy;
        if (directionChange>child.getHeight()&&child.getVisibility()== View.VISIBLE) {
            hide(child);
        }else if(directionChange<0&&child.getVisibility()==View.GONE){
            show(child);
        }
    }

    private void hide(View view) {
        //设置动画
        ViewPropertyAnimator animator = view.animate().translationY(view.getHeight())
                .setInterpolator(new FastOutSlowInInterpolator())
                .setDuration(200);
        animator.setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.GONE);

            }
        } );
        animator.start();
    }

    private void show(View view) {
        //设置动画
        ViewPropertyAnimator animator = view.animate().translationY(0)
                .setInterpolator(new FastOutSlowInInterpolator())
                .setDuration(200);
        animator.setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                view.setVisibility(View.VISIBLE);

            }
        } );
        animator.start();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,734评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,931评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,133评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,532评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,585评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,462评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,262评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,153评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,587评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,792评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,919评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,635评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,237评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,855评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,983评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,048评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,864评论 2 354

推荐阅读更多精彩内容