原文鏈接
Mastering the Coordinator Layout
在Google I/0 2015大會上,Google發佈了一個與Material Design相關的控件支持庫,在這個控件庫中我們可以找到很多新的ViewGroup控件,例如 AppBarLayout,CollapsingToolbarLayout和CoordinatorLayout.
考慮到這些新的控件非常有用,因此我決定寫一篇文章來介紹其相關的配置和使用技巧.
CoordinatorLayout
這個控件的作用和它的名字描述一樣,是用來協調它裏面所有子view行爲的控件.
考慮下面的例子:
我們可以看到View之間是相互配合的,View會根據其他View的滑動而做出相應的變化.
舉一個使用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:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_light"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/id_main_appbar"
android:layout_width="match_parent"
android:layout_height="300dp"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="@+id/id_main_collapsing"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="@+id/id_main_backdrop"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="@null"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
android:src="@mipmap/ic_launcher"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="@+id/id_main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="8dp"
android:padding="@dimen/activity_horizontal_margin"
android:text="@string/lorem"
android:textSize="20sp" />
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/activity_horizontal_margin"
android:src="@mipmap/ic_launcher"
app:layout_anchor="@id/id_main_appbar"
app:layout_anchorGravity="bottom|right|end" />
</android.support.design.widget.CoordinatorLayout>
在上面的layout佈局文件中,CoordinatorLayout直接包含了3個子控件,分別是:
AppBarLayout,NestedScrollView和FloatingActionBar.
<CoordinatorLayout>
<AppbarLayout/>
<scrollableView/>
<FloatingActionButton/>
</CoordinatorLayout>
AppBarLayout
AppBarLayout是一個繼承LinearLayout的ViewGroup,默認是垂直方向.它可以控件它裏面子控件的滾動行爲.直接聽起來可能比較疑惑,我用一個git圖片來描述一下:
在上面的gif圖片中,AppBarLayout是那個整體的藍色View,它裏面包含了可以收縮的圖片,一個Toolbar,一個LinearLayout用來包含標題和副標題,以及一個TabLayout.
我們可以通過設置layout_scrollFlags來直接控制AppBarLayout中的子控件.在這個例子中,大部分子View的layout_scrollFlags屬性都設置了scroll,如果沒有設置的話,當可滾動的View進行滾動時,這些沒有設置scroll屬性的View的位置會保持不變.
layout_scrollFlags設置值爲snap,可以避免進入動畫中間狀態,這意味着動畫會一直持續到View完全顯示或者完全隱藏爲止.
LinearLayout其中包含了一個標題和一個副標題,當用戶向上移動時LinearLayout是一直顯示的,直到移出屏幕.而TabLayout是會一直可見的,因爲我們沒有在TabLayout上設置任何滾動屬性.
正如你所見,AppbarLayout的強大管理能力是通過給子View設置不同的Scroll屬性來實現的.
<AppBarLayout>
<CollapsingToolbarLayout
app:layout_scrollFlags="scroll|snap"
/>
<Toolbar
app:layout_scrollFlags="scroll|snap"
/>
<LinearLayout
android:id="+id/title_container"
app:layout_scrollFlags="scroll|enterAlways"
/>
<TabLayout /> <!-- no flags -->
</AppBarLayout>
這些參數的設置需要參考Google Developers docs.我建議大家通過代碼練習來掌握它們,我會在文章的末尾提供幾個Github上的例子來供大家學習參考.
AppbarLayout flags
SCROLL_FLAG_ENTER_ALWAYS: 當任何向下滾動事件發生時,View都會移入,不管scrolling view是否正雜滾動.
SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED: 它是”enterAlways”的附件屬性,它是的View恢復到指定的最小高度後來開始顯示,然後再慢慢展開.
SCROLL_FLAG_EXIT_UNTIL_COLLAPSED:當向上移出屏幕時,View會一直收縮到最小高度後,再移出屏幕.
SCROLL_FLAG_SCROLL:View會根據指定方向進行滾動.
SCROLL_FLAG_SNAP:當滾動結束時,如果這個View只有部分可見,它將會自動滾動到最近的邊界(完全可見或者完全隱藏).
CoordinatorLayout Behaviors
讓我們來做一個小測試,打開Android Studio(大於1.4版本),使用Scrolling Activity模板來創建一個Activity,編譯運行之後如下所示:
當我們來review生成的代碼,不過是layout還是java類中我們都找不到FloatingActionBar滾動變化的源碼.爲什麼呢?
答案在FloatingActionBar的源代碼裏,從Android Studio1.2版本開始,增加了ctrl+click可以查看源代碼,源碼如下:
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Floating action buttons are used for a
* special type of promoted action.
* They are distinguished by a circled icon
* floating above the UI and have special motion behaviors
* related to morphing, launching, and the transferring anchor point.
*
* blah.. blah..
*/
@CoordinatorLayout.DefaultBehavior(
FloatingActionButton.Behavior.class)
public class FloatingActionButton extends ImageButton {
...
public static class Behavior
extends CoordinatorLayout.Behavior<FloatingActionButton> {
private boolean updateFabVisibility(
CoordinatorLayout parent, AppBarLayout appBarLayout,
FloatingActionButton child {
if (a long condition) {
// If the anchor's bottom is below the seam,
// we'll animate our FAB out
child.hide();
} else {
// Else, we'll animate our FAB back in
child.show();
}
}
}
...
}
負責縮放動畫的是design library引入的Behavior新元素,在這個例子中是CoordinatorLayout.Behavior.它會根據一些滾動條件,來判斷是否顯示FloatingActionButton.
SwipeDismissBehavior
繼續深入理解源碼,我們可以在design support library庫的源碼中發現一個public類SwipeDismissBehavior.通過這個Behavior,我們可以通過CoordinatorLayout輕鬆實現滑動刪除的效果.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swipe_behavior);
mCardView = (CardView) findViewById(R.id.swype_card);
final SwipeDismissBehavior<CardView> swipe
= new SwipeDismissBehavior();
swipe.setSwipeDirection(
SwipeDismissBehavior.SWIPE_DIRECTION_ANY);
swipe.setListener(
new SwipeDismissBehavior.OnDismissListener() {
@Override public void onDismiss(View view) {
Toast.makeText(SwipeBehaviorExampleActivity.this,
"Card swiped !!", Toast.LENGTH_SHORT).show();
}
@Override
public void onDragStateChanged(int state) {}
});
LayoutParams coordinatorParams =
(LayoutParams) mCardView.getLayoutParams();
coordinatorParams.setBehavior(swipe);
}
Custom Behaviors
創建一個自定義的Behavior,不像大家想象的那麼難.在開始之前,我們必須明確兩個元素: child和dependency.
Childs and dependencies
child是指使用behavior的view,dependency是behavior的觸發器,並和child進行互動.在這個例子中,child是一個ImageView,dependency是Toolbar,當Toolbar發生了移動,ImageView也跟隨移動.
現在我們已經明確了child和dependency的概念,接下來我們講一下如何實現.
第一步我們需要繼承CoordinatorLayout.Behavoir<\T>,其中T是View對象,在上面的例子中是ImageView.接下來,我們必須重寫兩個方法:
- layoutDependsOn
- onDependentViewChanged
layoutDependsOn方法在layout佈局發生變化時被回調,我們需要在dependency發生變化時返回true.在上面的例子中,當用戶滑動屏幕時這個方法被自動調用,我們需要讓child做出相應的反應.
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, CircleImageView child, View dependency) {
return dependency instance of Toolbar;
}
當layoutDependsOn返回true時,onDependentViewChanged函數就會被調用.在這個方法中,我們需要實現動畫效果.
public boolean onDependentViewChanged(
CoordinatorLayout parent,
CircleImageView avatar,
View dependency) {
modifyAvatarDependingDependencyState(avatar, dependency);
}
private void modifyAvatarDependingDependencyState(
CircleImageView avatar, View dependency) {
// avatar.setY(dependency.getY());
// avatar.setBlahBlat(dependency.blah / blah);
}
完整的自定義Behavior代碼:
public static class AvatarImageBehavior
extends
CoordinatorLayout.Behavior<CircleImageView> {
@Override
public boolean layoutDependsOn(
CoordinatorLayout parent,
CircleImageView, child,
View dependency) {
return dependency instanceof Toolbar;
}
public boolean onDependentViewChanged(
CoordinatorLayout parent,
CircleImageView avatar,
View dependency) {
modifyAvatarDependingDependencyState(avatar, dependency);
}
private void modifyAvatarDependingDependencyState(
CircleImageView avatar, View dependency) {
// avatar.setY(dependency.getY());
// avatar.setBlahBlah(dependency.blah / blah);
}
}
Resources
Coordinator Behavior Example - Github
Coordinator Examples - Github
Introduction to coordinator layout on Android - Grzesiek Gajewski