一、CoordinatorLayout 的作用
CoordinatorLayout 作為一個 “super-powered FrameLayout”,主要有以下兩個作用:
- 作為頂層布局;
- 作為協調子 View 之間交互的容器。
使用 CoordinatorLayout 需要在 build.gradle 加入:
compile 'com.android.support:design:25.1.0'
二、CoordinatorLayout 與 FloatingActionButton
2.1 FloatingActionButton(以下簡稱 FAB) 單獨使用,布局如下:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contentView"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:onClick="onClick"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"/>
</RelativeLayout>
點擊 FAB,彈出一個 Snackbar:
public void onClick(View v) {
switch (v.getId()) {
case R.id.fab:
Snackbar.make(findViewById(R.id.contentView), "Snackbar", Snackbar.LENGTH_SHORT).show();
break;
}
}
效果如下:
FAB 會被 Snackbar 遮擋,此時需要使用到 CoordinatorLayout。
2.2 與 CoordinatorLayout 一起使用,布局調整如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/contentView"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/anchorView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"/>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_anchor="@id/anchorView"
app:layout_anchorGravity="bottom|right"
android:onClick="onClick"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"/>
</android.support.design.widget.CoordinatorLayout>
CoordinatorLayout 提供了兩個屬性用來設置 FAB 的位置:
- layout_anchor:設置 FAB 的錨點,我們熟悉的 PopupWindow 也有類似概念。
- layout_anchorGravity:設置相對錨點的位置,如
bottom|right
表示 FAB 位于錨點的右下角。
再次運行程序,Snackbar 顯示和隱藏的時候,CoordinatorLayout 會動態調整 FAB 的位置:
這里暫不介紹原理,涉及到另外一個概念:Behavior,后面會講解。
CoordinatorLayout 最簡單的使用例子就是和 FAB 一起使用了,我們接著往下看其它用法。
三、CoordinatorLayout 與 AppBarLayout
AppBarLayout 是一個垂直布局的 LinearLayout,它主要是為了實現 “Material Design” 風格的標題欄的特性,比如:滾動。
上面這個效果在不少 APP 中都很常見,標題欄會隨著視圖的滾動:顯示和隱藏。
不使用 CoordinatorLayout,實現這個效果的方案有兩種:
- 自己處理觸摸事件的分發,來改變標題欄的位置。
- 使用 support.v4 引入的 NestedScrolling 機制。
關于上面兩種實現方式,可以參考我的另外一篇文章:Android NestedScrolling機制。
這里,NestedScrolling 兩個重要的概念提及一下:
- NestedScrollingParent
- NestedScrollingChild
巧合的是 CoordinatorLayout 已經實現了 NestedScrollingParent 接口,所以我們配合一個實現了 NestedScrollingChild 接口的 View 就可以輕松的實現以上效果。
簡單起見,我們使用 NestedScrollView 包裹 TextView 來實現上面的效果:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="標題"
android:textSize="20sp"
android:gravity="center"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:textColor="@android:color/white"
android:background="@color/colorPrimary"
app:layout_scrollFlags="scroll"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:gravity="center_horizontal"/>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
1、CoordinatorLayout 中可滾動的視圖(如本例中的 NestedScrollView),需要設置以下屬性:
app:layout_behavior="@string/appbar_scrolling_view_behavior"
這個固定字符串是系統提供的,表示使用android.support.design.widget.AppBarLayout$ScrollingViewBehavior
來處理 NestedScrollView 與 AppBarLayout 的關系,這里暫不介紹,后面會講解。
2、AppBarLayout 中的 View,如要想要滾動到屏幕外,必須設置以下屬性:
app:layout_scrollFlags="scroll"
- scroll: 隱藏的時候,先整體向上滾動,直到 AppBarLayout 完全隱藏,再開始滾動 Scrolling View;顯示的時候,直到 Scrolling View 頂部完全出現后,再開始滾動 AppBarLayout 到完全顯示。
scroll
除了 scroll,還有下面幾個取值,這些屬性都必須與 scroll 一起使用 “|” 運算符。 - enterAlways:與 scroll 類似(
scroll|enterAlways
),只不過向下滾動先顯示 AppBarLayout 到完全,再滾動 Scrolling View。
-
enterAlwaysCollapsed:需要和 enterAlways 一起使用(
scroll|enterAlways|enterAlwaysCollapsed
),和 enterAlways 不一樣的是,不會顯示 AppBarLayout 到完全再滾動 Scrolling View,而是先滾動 AppBarLayout 到最小高度,再滾動 Scrolling View,最后再滾動 AppBarLayout 到完全顯示。注意:需要定義 View 的最小高度(minHeight)才有效果:
android:minHeight="10dp" app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed"
-
exitUntilCollapsed:顧名思義,定義了 AppBarLayout 消失的規則。發生向上滾動事件時,AppBarLayout 向上滾動退出直至最小高度(minHeight),然后 Scrolling View 開始滾動。也就是,AppBarLayout 不會完全退出屏幕。
android:minHeight="10dp" app:layout_scrollFlags="scroll|exitUntilCollapsed"
enterAlwaysCollapsed 與 exitUntilCollapsed 在實際的使用中,更多的是與 CollapsingToolbarLayout 一起使用,我們繼續往下看。
四、CoordinatorLayout 與 CollapsingToolbarLayout
CollapsingToolbarLayout 繼承自 FrameLayout,它是用來實現 Toolbar 的折疊效果,一般它的直接子 View 是 Toolbar,當然也可以是其它類型的 View。
如果你不使用 Toolbar,有些效果沒法直接實現,比如下圖的“My files”文字在折疊和展開的時候,有一個過渡效果:
也就是 CollapsingToolbarLayout 設置 title 的相關方法無效,比如:
setTitle、setCollapsedTitleTextColor、setExpandedTitleGravity
等,更多方法可以自行查閱 API 。
另外,exitUntilCollapsed 屬性也會失效,即使你設置了 minHeight,所以官方也說明了CollapsingToolbarLayout 是為了配合 Toolbar 而設計:
CollapsingToolbarLayout is a wrapper for {@link Toolbar} which implements a collapsing app bar.
所以,我們使用 Toolbar 來實現一些常見的效果吧~
4.1 CollapsingToolbarLayout & enterAlwaysCollapsed
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="@color/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways|enterAlwaysCollapsed">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_collapseMode="pin"
android:minHeight="10dp"
android:background="@color/colorPrimary"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:gravity="center_horizontal"/>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
我們將 AppBarLayout 的高度設置大一點,app:layout_collapseMode="pin"
確保 CollapsingToolbarLayout 折疊完成之前,Toolbar 一直固定在頂部不動。
4.2 CollapsingToolbarLayout & exitUntilCollapsed
修改下 CollapsingToolbarLayout 的 layout_scrollFlags:
app:layout_scrollFlags="scroll|exitUntilCollapsed"
4.3 parallax(視差)
layout_collapseMode
除了使用 pin 固定住 View,還可以使用 parallax,視差的意思就是:移動過程中兩個 View 的位置產生了一定的視覺差異。
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/collapsingToolbarLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="@color/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/bg"
android:scaleType="centerCrop"
app:layout_collapseParallaxMultiplier="0.9"
app:layout_collapseMode="parallax"/>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_collapseMode="pin"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:gravity="center_horizontal"/>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
你可以設置視差因子:
app:layout_collapseParallaxMultiplier="0.9"
下圖是視差因子為0.1的效果:
對比 parallax-0.9,可以看出來圖片上移的位置是不同的。
這里還有幾個屬性需要介紹下:
contentScrim:表示 CollapsingToolbarLayout 折疊之后的“前景色”,我們看到 Toolbar 的變色,其實是因為前景色遮擋了而已。
statusBarScrim:表示狀態欄的“前景色”,試驗下來并無效果,知道的同學麻煩告訴下~
五、終極 Boss - Behavior
5.1 介紹
CoodinatorLayout 并不知道 FloatingActionButton 和 AppBarLayout 的工作原理,我們提到過 CoodinatorLayout 實現了 NestedScrollingParent,我們通過一個實現了 NestedScrollingChild 的 scrolling view,就可以輕松的實現:滑動事件的處理與 View 之間的交互。
這其中充當中間橋梁的就是 CoordinatorLayout.Behavior,比如 FloatingActionButton,查看源碼發現它的類注解是這樣的:
@CoordinatorLayout.DefaultBehavior(FloatingActionButton.Behavior.class)
public class FloatingActionButton extends VisibilityAwareImageButton {
// ...
}
FloatingActionButton.Behavior 的主要作用就是防止被 Snackbar 蓋住。
自定義 View 既可以通過注解指定 Behavior,也可以通過在布局 XML 申明:
app:layout_behavior="具體Behavior的類路徑"
5.2 原理分析
以 “三、CoordinatorLayout 與 AppBarLayout” 中的效果來分析:
滑動 NestedScrollView 會觸發 CoodinatorLayout 的 onNestedPreScroll 方法(不知道為什么的看這篇文章:Android NestedScrolling機制);
-
onNestedPreScroll 方法會查找所有定義了 Behavior 的 View,再通過 Behavior 的 onNestedPreScroll 方法去詢問每個 View 需要消耗的距離(部分源碼);
@Override public void onNestedPreScroll(View target, int dx, int dy, int[] consumed) { int xConsumed = 0; int yConsumed = 0; boolean accepted = false; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View view = getChildAt(i); final Behavior viewBehavior = lp.getBehavior(); if (viewBehavior != null) { mTempIntPair[0] = mTempIntPair[1] = 0; viewBehavior.onNestedPreScroll(this, view, target, dx, dy, mTempIntPair); xConsumed = dx > 0 ? Math.max(xConsumed, mTempIntPair[0]) : Math.min(xConsumed, mTempIntPair[0]); yConsumed = dy > 0 ? Math.max(yConsumed, mTempIntPair[1]) : Math.min(yConsumed, mTempIntPair[1]); accepted = true; } } consumed[0] = xConsumed; consumed[1] = yConsumed; }
NestedScrollView 的 Behavior:
AppBarLayout.ScrollingViewBehavor
,它的 onNestedPreScroll 沒有做任何實現;-
那么剩下的就是 AppBarLayout 的 Behavior:
AppBarLayout.Behavior
@Override public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) { if (dy != 0 && !mSkipNestedPreScroll) { int min, max; if (dy < 0) { // We're scrolling down min = -child.getTotalScrollRange(); max = min + child.getDownNestedPreScrollRange(); } else { // We're scrolling up min = -child.getUpNestedPreScrollRange(); max = 0; } consumed[1] = scroll(coordinatorLayout, child, dy, min, max); } }
很好理解,我們滑動 NestedScrollView 的時候,AppBarLayout 會向上滾動,所以就需要消耗部分滾動的距離。
這里,我們只是簡單的分析了部分源碼,有興趣的可以自己去閱讀。
5.3 自定義 Behavior
自定義 Behavior 需要繼承自 CoodinatorLayout.Behavior,我們重點關注以下幾組方法:
(1) 事件攔截
- onInterceptTouchEvent
- onTouchEvent
觸摸事件總是先交給 CoodinatorLayout,它會詢問所有子 View 的 Behavior 是否需要攔截事件。
細心的話,你會注意到直接拖拽 AppBarLayout 也可以滾動,這是因為 AppBarLayout.Behavior 的父類 HeaderBehavior 實現了這兩個方法。
(2) 嵌套滾動
- onNestedPreScroll
- onNestedPreFling
原理分析的時候已經介紹過,可以參考 AppBarLayout.Behavior 的實現。
(3) child 和 dependency
- layoutDependsOn:決定 child 依賴誰(dependency)。
- onDependentViewChanged:dependency 的大小或位置發生了變化。
- onDependentViewRemoved:dependency 從父布局中被移除了。
描述了兩個(或多個)View 之間的依賴關系,表現為一個或多個 child 依賴 dependency。當 dependency 的大小或位置發生了改變,child 可以做出一些你需要的響應(改變位置、大小等)。
這里,我們演示一個 child 在 Y 軸跟隨 dependency 的效果:
1、首先,定義 dependency,讓它可以跟隨手指移動(僅部分代碼):
public class DependencyView extends Button {
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getRawX();
int y = (int) event.getRawY();
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE: {
CoordinatorLayout.MarginLayoutParams layoutParams = (CoordinatorLayout.MarginLayoutParams) getLayoutParams();
int left = layoutParams.leftMargin + x - lastX;
int top = layoutParams.topMargin + y - lastY;
layoutParams.leftMargin = left;
layoutParams.topMargin = top;
setLayoutParams(layoutParams);
requestLayout();
break;
}
}
lastX = x;
lastY = y;
return true;
}
}
2、自定義 Behavior,讓 child 跟隨 dependency:
public class CusBehavior extends CoordinatorLayout.Behavior {
private int width;
public CusBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
DisplayMetrics display = context.getResources().getDisplayMetrics();
width = display.widthPixels;
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency.getId() == R.id.dependency;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
child.setY(dependency.getY() + child.getHeight());
return true;
}
}
3、使用 Behavior:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/child"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_behavior="android.coordinatorlayoutdemo.CusBehavior"
android:text="Child" />
<android.coordinatorlayoutdemo.DependencyView
android:id="@+id/dependency"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dependency" />
</android.support.design.widget.CoordinatorLayout>
是不是很簡單?
其實 FloatingActionButton 示例中:layout_anchor 使用某個 View 作為錨點,就是用了這個原理,具體可以參考:FloatingActionButton.Behavior 。
六、寫在最后
- 本文的效果是在5.0+系統上運行的,所以低版本的系統狀態欄的表現可能不一致。
- 本文只是演示了 CoodinatorLayout 的多數基本用法,實際應用中的效果一般比這個復雜很多。
感謝大家耐心看到最后,本文的源碼可以在這里找到:CoordinatorLayoutDemo。