一、CoordinatorLayout 的作用
CoordinatorLayout 作为一个 “super-powered FrameLayout”,主要有以下两个作用:
- 作为顶层布局;
- 作为协调子 View 之间交互的容器。
使用 CoordinatorLayout 需要在 build.gradle 加入:
4.3 parallax(视差)
layout_collapseMode
除了使用 pin 固定住 View,还可以使用 parallax,视差的意思就是:移动过程中两个 View 的位置产生了一定的视觉差异
app:layout_collapseMode="pin" 固定于顶部 app:layout_collapseMode="parallax" 可随着控件的滑动而滑动 app:contentScrim="?attr/colorPrimaryDark" 设置滑动的颜色 app:layout_behavior="@string/appbar_scrolling_view_behavior" 联动 app:layout_collapseParallaxMultiplier="1" 视差因子 contentScrim:表示 CollapsingToolbarLayout 折叠之后的“前景色”,我们看到 Toolbar 的变色,其实是因为前景色遮挡了而已。 statusBarScrim:表示状态栏的“前景色”
二、AppbarLayout的作用
它可以用来包裹一个Toolbar来用,它主要的特点是滑动,它需要配合俩个控件一起使用,那就是 CoordinatorLayout和CollapsingToolbarLayout
AppbarLayout要实现酷炫的滑动效果必须依赖于CoordinatorLayout使用,作为CoordinatorLayout的直接子view,如果父view是其他的viewGroup是没有效果的.滑动的特效用如下俩种方式设置
app:layout_scrollFlags和setScrollFlags
layout_scrollFlags有5种动作,分别是scroll,enterAlways,enterAlwaysCollapsed,exitUntilCollapsed,snap
1,scroll,子View 添加layout_scrollFlags属性 的值scroll 时,这个View将会随着可滚动View(如:ScrollView,以下都会用ScrollView 来代替可滚动的View )一起滚动,就好像子View 是属于ScrollView的一部分一样。
2,enterAlways,子View 添加layout_scrollFlags属性 的值有enterAlways 时, 当ScrollView 向下滑动时,子View 将直接向下滑动,而不管ScrollView 是否在滑动。注意:要与scroll 搭配使用,否者是不能滑动的。
3,enterAlwaysCollapsed, enterAlwaysCollapsed 是对enterAlways 的补充,当ScrollView 向下滑动的时候,滑动View(也就是设置了enterAlwaysCollapsed 的View)下滑至折叠的高度,当ScrollView 到达滑动范围的结束值的时候,滑动View剩下的部分开始滑动。这个折叠的高度是通过View的minimum height (最小高度)指定的。
4,exitUntilCollapsed, 当ScrollView 滑出屏幕时(也就时向上滑动时),滑动View先响应滑动事件,滑动至折叠高度,也就是通过minimum height 设置的最小高度后,就固定不动了,再把滑动事件交给 scrollview 继续滑动。
5,snap,意思是:在滚动结束后,如果view只是部分可见,它将滑动到最近的边界。比如,如果view的底部只有25%可见,它将滚动离开屏幕,而如果底部有75%可见,它将滚动到完全显示。
三、 CollapsingToolbarLayout的作用
就是这样一个把各种toolbar的效果组合起来的布局,它可以实现toolbar的折叠效果,要实现这样的效果还需要CoordinatorLayout+AppBarLayout的配合,属性都可以在一块使用
以下为样例代码: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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=".ui.activity.commodity.CommodityDetails"> <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="@dimen/dp_250" android:fitsSystemWindows="true"> <com.google.android.material.appbar.CollapsingToolbarLayout android:id="@+id/collapsing" android:layout_width="match_parent" android:layout_height="match_parent" app:collapsedTitleTextAppearance="@style/Tex