简单介绍
CoordinatorLayout布局是原名协调布局,顾名思义他在Android中扮演子View滑动过程中协调者的作用,可以把它理解为一个容器,继承ViewGroup,最初是在Material Design风格中提出来的,用来处理很多复杂布局滑动相关的功能,最常见的是搭配AppBarLayout、NestedScrollView、RecyclerView等布局
配置说明
引入MaterialDesign包,一般AndroidStudio3.0以上新建项目默认是会引入
implementation 'com.google.android.material:material:1.3.0'
这个包是基于AndroidX的项目,如果你的项目还没有切换AndroidX则需要引入非AndroidX的materDesign包
实例讲解
先来看一下示例效果
布局xml文件如下
<?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:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@color/gray"
android:gravity="center"
android:text="滑动隐藏区域"
android:textColor="@android:color/white"
android:textSize="30sp"
app:layout_scrollFlags="scroll" />
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/green"
android:gravity="center"
android:text="滑动固定区域"
android:textColor="@android:color/white"
android:textSize="20sp" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:id="@+id/rv_demo1_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#fff"
android:text="@string/geci"
android:textSize="20sp" />
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
这里要说明一下
CoordinatorLayout要实现子View联动就必须要求子View实现NestedScrollingChild接口,像NestedScrollView、RecyclerView这类组件就已经实现NestedScrollingChild,NestedScrollingChild这个接口其实是为了解决内部View滑动冲突的,有兴趣可以百度了解一下,同时,子View需要添加app:layout_behavior属性才能实现联动效果,但是上述代码中AppBarLayout没有实现这个属性是因为AppBarLayout默认自带这个属性,可以查看源码了解
接下来重点说明一下滑动效果属性
app:layout_scrollFlags这个属性是添加在滑动隐藏区域组件上的,其对应的设置参数如下
app:layout_scrollFlags=“scroll” 这是基础滑动属性,要实现滑动必须设置此值,下面其他值都是必须在实现此值的基础上添加,当下拉时,等到NestedScrollView中的内容全部拉下来才开始下来滑动隐藏区域
app:layout_scrollFlags=“scroll|enterAlways” 当下来时,先下拉滑动隐藏区域后再下拉NestedScrollView中的内容
**app:layout_scrollFlags=“scroll|enterAlways|enterAlwaysCollapsed” ** 需要配合android:minHeight="20dp"属性一起使用,当下拉时,滑动隐藏区域先显示最小的高度后,开始下拉NestedScrollView中的内容,等其内容下拉完成后再下来滑动隐藏区域
**app:layout_scrollFlags=“scroll|enterAlways|exitUntilCollapsed” ** 这个与上面相反,当上拉时滑动隐藏区域固定一个显示的最小高度
**app:layout_scrollFlags=“scroll|snap” ** 当下拉滑动区域超过75%会自动全部显示滑动区域,当上拉滑动隐藏只剩25%,会自动隐藏滑动隐藏区域
appBarLayout.setExpanded(true); 打开AppBarLayout
appBarLayout.setExpanded(false); 关闭AppBarLayout
最后附上项目Demo
点击获取项目源码