一、認識CoordinatorLayout
CoordinatorLayout作為support:design庫里的核心控件,在它出現(xiàn)之前,要實現(xiàn)View之間嵌套滑動等交互操作可不是件容易的事,復(fù)雜、難度大,基本繞不開View的事件機制,CoordinatorLayout很大程度上解決了這個痛點,方便我們實現(xiàn)各種炫酷的交互效果。
如果你還沒用過CoordinatorLayout,可先了解它的基本用法。
CoordinatorLayout為何如此強大呢?因為它的內(nèi)部類Behavior,這也是CoordinatorLayout的精髓所在。
二、不可不知的Behavior
使用CoordinatorLayout時,會在xml文件中用它作為根布局,并給相應(yīng)的子View添加一個類似app:layout_behavior="@string/appbar_scrolling_view_behavior"的屬性,當(dāng)然屬性值也可以是其它的。進一步可以發(fā)現(xiàn)@string/appbar_scrolling_view_behavior的值是android.support.design.widget.AppBarLayout$ScrollingViewBehavior,不就是support包下一個類的路徑嘛!玄機就在這里,通過CoordinatorLayout之所以可以實現(xiàn)炫酷的交互效果,Behavior功不可沒。既然如此,我們也可以自定義Behavior,來定制我們想要的效果。
要自定義Behavior,首先認識下它:
public static abstract class Behavior<V extends View> {
public Behavior() {
}
public Behavior(Context context, AttributeSet attrs) {
}
//省略了若干方法
}
其中有一個泛型,它的作用是指定要使用這個Behavior的View的類型,可以是Button、TextView等等。如果希望所有的View都可以使用則指定泛型為View即可。
自定義Behavior可以選擇重寫以下的幾個方法有:
-
onInterceptTouchEvent():是否攔截觸摸事件 -
onTouchEvent():處理觸摸事件 -
layoutDependsOn():確定使用Behavior的View要依賴的View的類型 -
onDependentViewChanged():當(dāng)被依賴的View狀態(tài)改變時回調(diào) -
onDependentViewRemoved():當(dāng)被依賴的View移除時回調(diào) -
onMeasureChild():測量使用Behavior的View尺寸 -
onLayoutChild():確定使用Behavior的View位置 -
onStartNestedScroll():嵌套滑動開始(ACTION_DOWN),確定Behavior是否要監(jiān)聽此次事件 -
onStopNestedScroll():嵌套滑動結(jié)束(ACTION_UP或ACTION_CANCEL) -
onNestedScroll():嵌套滑動進行中,要監(jiān)聽的子View的滑動事件已經(jīng)被消費 -
onNestedPreScroll():嵌套滑動進行中,要監(jiān)聽的子View將要滑動,滑動事件即將被消費(但最終被誰消費,可以通過代碼控制) -
onNestedFling():要監(jiān)聽的子View在快速滑動中 -
onNestedPreFling():要監(jiān)聽的子View即將快速滑動
三、實踐
通常自定義Behavior分為兩種情況:
某個
View依賴另一個View,監(jiān)聽其位置、尺寸等狀態(tài)的變化。某個
View監(jiān)聽CoordinatorLayout內(nèi)實現(xiàn)了NestedScrollingChild接口的子View的滑動狀態(tài)變化(也是一種依賴關(guān)系)。
先看第一種情況,我們要實現(xiàn)的效果如下:

向上滑動列表時,
title(TextView)自動下滑,當(dāng)title全部顯示時,列表頂部和title底部恰好重合,繼續(xù)上滑列表時title固定;下滑列表時,當(dāng)列表頂部和title底部重合時,title開始自動上滑直到完全隱藏。
首先我們定義一個SampleTitleBehavior:
public class SampleTitleBehavior extends CoordinatorLayout.Behavior<View> {
// 列表頂部和title底部重合時,列表的滑動距離。
private float deltaY;
public SampleTitleBehavior() {
}
public SampleTitleBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, View child, View dependency) {
return dependency instanceof RecyclerView;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
if (deltaY == 0) {
deltaY = dependency.getY() - child.getHeight();
}
float dy = dependency.getY() - child.getHeight();
dy = dy < 0 ? 0 : dy;
float y = -(dy / deltaY) * child.getHeight();
child.setTranslationY(y);
return true;
}
}
注意不要忘了重寫兩個參數(shù)的構(gòu)造函數(shù),否則無法在xml文件中使用該Behavior,我們重寫了兩個方法:
-
layoutDependsOn():使用該Behavior的View要監(jiān)聽哪個類型的View的狀態(tài)變化。其中參數(shù)parant代表CoordinatorLayout,child代表使用該Behavior的View,dependency代表要監(jiān)聽的View。這里要監(jiān)聽RecyclerView。 -
onDependentViewChanged():當(dāng)被監(jiān)聽的View狀態(tài)變化時會調(diào)用該方法,參數(shù)和上一個方法一致。所以我們重寫該方法,當(dāng)RecyclerView的位置變化時,進而改變title的位置。
一般情況這兩個方法是一組,這樣一個簡單的Behavior就完成了,使用也很簡單,仿照系統(tǒng)的用法,先在strings.xml中記錄其全包名路徑(當(dāng)然不是必須的,下一遍會講到):
<string name="behavior_sample_title">com.othershe.behaviortest.test1.SampleTitleBehavior</string>
然后是布局文件
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.othershe.behaviortest.test1.TestActivity1">
<android.support.design.widget.AppBarLayout
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:contentScrim="#00ffffff"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@mipmap/bg"
android:fitsSystemWindows="true"
android:scaleType="fitXY"
app:layout_collapseMode="parallax"
app:layout_collapseParallaxMultiplier="0.7" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id="@+id/my_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<TextView
android:id="@+id/title"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#ff0000"
android:gravity="center"
android:text="Hello World"
android:textColor="#ffffff"
android:textSize="18sp"
app:layout_behavior="@string/behavior_sample_title" />
</android.support.design.widget.CoordinatorLayout>
我們給TextView設(shè)置了該Behavior。
除了實現(xiàn)title的位置變化,要實現(xiàn)透明度變化也是很簡單的,對SampleTitleBehavior做如下修改即可:
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, View child, View dependency) {
if (deltaY == 0) {
deltaY = dependency.getY() - child.getHeight();
}
float dy = dependency.getY() - child.getHeight();
dy = dy < 0 ? 0 : dy;
float alpha = 1 - (dy / deltaY);
child.setAlpha(alpha);
return true;
}
修改后的效果如下:

第二種情況,我們的目標(biāo)效果如下:

簡單解釋一下,該布局由RecylerView列表和一個TextView組成,其中RecylerView實現(xiàn)了NestedScrollingChild接口,所以TextView監(jiān)聽RecylerView的滑動狀態(tài)。開始向上滑動列表時TextView和列表整體上移,直到TextView全部隱藏停止,再次上滑則列表內(nèi)容上移。之后連續(xù)下滑列表當(dāng)其第一個item全部顯示時列表滑動停止,再次下滑列表時TextView跟隨列表整體下移,直到TextView全部顯示。(有點繞,上手體會下......)
這里涉及兩個自定義Behavior,第一個實現(xiàn)垂直方向滑動列表時,TextView上移或下移的功能,但此時TextView會覆蓋在RecyclerView上(其實CoordinatorLayout有種FrameLayout的即視感),所以第二個的作用就是解決這個問題,實現(xiàn)RecyclerView固定在TextView下邊并跟隨TextView移動,可以發(fā)現(xiàn)這兩個View是相互依賴的。
先看第一個Behavior,代碼如下:
public class SampleHeaderBehavior extends CoordinatorLayout.Behavior<TextView> {
// 界面整體向上滑動,達到列表可滑動的臨界點
private boolean upReach;
// 列表向上滑動后,再向下滑動,達到界面整體可滑動的臨界點
private boolean downReach;
// 列表上一個全部可見的item位置
private int lastPosition = -1;
public SampleHeaderBehavior() {
}
public SampleHeaderBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(CoordinatorLayout parent, TextView child, MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
downReach = false;
upReach = false;
break;
}
return super.onInterceptTouchEvent(parent, child, ev);
}
@Override
public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull TextView child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
return (axes & ViewCompat.SCROLL_AXIS_VERTICAL) != 0;
}
@Override
public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull TextView child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
if (target instanceof RecyclerView) {
RecyclerView list = (RecyclerView) target;
// 列表第一個全部可見Item的位置
int pos = ((LinearLayoutManager) list.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
if (pos == 0 && pos < lastPosition) {
downReach = true;
}
// 整體可以滑動,否則RecyclerView消費滑動事件
if (canScroll(child, dy) && pos == 0) {
float finalY = child.getTranslationY() - dy;
if (finalY < -child.getHeight()) {
finalY = -child.getHeight();
upReach = true;
} else if (finalY > 0) {
finalY = 0;
}
child.setTranslationY(finalY);
// 讓CoordinatorLayout消費滑動事件
consumed[1] = dy;
}
lastPosition = pos;
}
}
private boolean canScroll(View child, float scrollY) {
if (scrollY > 0 && child.getTranslationY() == -child.getHeight() && !upReach) {
return false;
}
if (downReach) {
return false;
}
return true;
}
}
這里主要關(guān)注這兩個重寫的方法(這里涉及NestedScrolling機制,下一篇會講到):
-
onStartNestedScroll():表示是否監(jiān)聽此次RecylerView的滑動事件,這里我們只監(jiān)聽其垂直方向的滑動事件 -
onNestedPreScroll():處理監(jiān)聽到的滑動事件,實現(xiàn)整體滑動和列表單獨滑動(header是否完全隱藏是滑動的臨界點)。
第二個Behavior就簡單了,就是第一種情況,當(dāng)header位置變化時,改變列表y坐標(biāo),代碼如下:
public class RecyclerViewBehavior extends CoordinatorLayout.Behavior<RecyclerView> {
public RecyclerViewBehavior() {
}
public RecyclerViewBehavior(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, RecyclerView child, View dependency) {
return dependency instanceof TextView;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, RecyclerView child, View dependency) {
//計算列表y坐標(biāo),最小為0
float y = dependency.getHeight() + dependency.getTranslationY();
if (y < 0) {
y = 0;
}
child.setY(y);
return true;
}
}
將Behavior加到strings.xml中:
<string name="behavior_sample_header">com.othershe.behaviortest.test2.SampleHeaderBehavior</string>
<string name="behavior_recyclerview">com.othershe.behaviortest.test2.RecyclerViewBehavior</string>
在布局文件中的使用:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.othershe.behaviortest.test2.TestActivity2">
<TextView
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ff0000"
android:gravity="center"
android:text="Hello World"
android:textColor="#ffffff"
android:textSize="18sp"
app:layout_behavior="@string/behavior_sample_header" />
<android.support.v7.widget.RecyclerView
android:id="@+id/my_list"
android:layout_width="match_parent"
app:layout_behavior="@string/behavior_recyclerview"
android:layout_height="wrap_content" />
</android.support.design.widget.CoordinatorLayout>
自定義Behavior的基本用法就這些了,主要就是確定View之間的依賴關(guān)系(也可以理解為監(jiān)聽關(guān)系),當(dāng)被依賴View的狀態(tài)變化時,相應(yīng)View的狀態(tài)進而改變。
掌握了自定義Behavior,可以嘗試實現(xiàn)更復(fù)雜的交互效果,如下demo(原理參考了自定義Behavior的藝術(shù)探索-仿UC瀏覽器主頁),并添加了header滑動手勢、列表下滑展開header的操作:

再進一步簡化修改,就實現(xiàn)了類似Android版蝦米音樂播放頁的手勢效果:

簡單的分析一下最后一個效果,界面由
header、title、list三部分組成,初始狀態(tài)如下:
title此時在屏幕頂部外,則其初始y坐標(biāo)為-titleHeight;header在屏幕頂部,相當(dāng)于其默認y坐標(biāo)為0;list在header下邊,則其初始y坐標(biāo)是headerHeight。初始狀態(tài)上滑header或list則list上移、title下移,同時header向上偏移,最大偏移值headerOffset。當(dāng)header達到最大偏移值時title全部顯示其底部和list頂部重合,list和title的位移結(jié)束,此時title下移距離為titleHeight,其y坐標(biāo)為0,即y坐標(biāo)的變化范圍從-titleHeight到0;而list的上移距離為headerHeight - titleHeight,此時其y值為titleHeight,y坐標(biāo)的變化范圍從headerHeight到headerHeight - titleHeight(下滑過程也類似,就不分析了)。上滑結(jié)束狀態(tài)如下:
可以發(fā)現(xiàn)我們是以
header向上偏移是否結(jié)束為臨界點,來決定list、title是否繼續(xù)位移,所以可以用header作為被依賴對象,在滑動過程中,計算header的translationY和最大偏移值headerOffset的比例進而計算title和list的y坐標(biāo)來完成位移,剩下就是編寫Behavior了。這里有一點需要注意,list的高度在界面初始化后已經(jīng)完成測量,上滑時根據(jù)header的偏移改變list的y坐標(biāo)使其移動,會出現(xiàn)list顯示不全的問題!
還記得第一個demo嗎,也是header+list的形式,但沒有這個問題,可以參考一下哦,其布局文件中使用了AppBarLayout和它下邊的Behavior名為appbar_scrolling_view_behavior的RecyclerView,其實AppBarLayout也使用了一個Behavior,只不過是通過注解來設(shè)置的(后邊會講到),它繼承自ViewOffsetBehavior,由于ViewOffsetBehavior是包私有的,我們拷貝一份,讓我們header的Behavior也繼承ViewOffsetBehavior,上邊appbar_scrolling_view_behavior對應(yīng)的Behavior繼承自HeaderScrollingViewBehavior,它同樣也是私有的,拷貝一份,讓list的Behavior繼承自它,這樣問題就解決了!這里只是簡單的原理分析,代碼就不貼了,有興趣的可以看源碼!
下一篇,CoordinatorLayout之源碼解析,更深入的學(xué)習(xí)Behavior,有助理解最后的demo,再見!