Android animation 30天上手 — Day17 CoordinatorLayout

Evan Chen
Evan Android Note
Published in
7 min readNov 14, 2018

CoordinatorLayout是用來協調子View之間動作的一個Layout,能依Layout裡一個View的位置變化,讓其他Layout也跟著移動。在不少的App都可以看到這樣的效果。

這個例子 Head會隨著下方Scrollview 的滑動而隱藏和出現。

CoordinatorLayout 裡包含

  • CollapsingToolbarLayout
  • CollapsingToolbarLayout 裡的Layout
  • ScrollView

在Gradle 加入
compile “com.android.support:design:27.1.1”

CollapsingToolbarLayout

顧名思義,CollapsingToolbarLayout就是可折疊式的ToolbarLayout

屬性 app:layout_scrollFlags

enterAlways:

快速返回模式,只要一往下滑,CollapsingToolbarLayout就會顯示

enterAlwaysCollapsed:

往上滑就隱藏,往下滑至最底才會出現

exitUntilCollapsed

Scrollview 向上滑動時,CollapsingToolbarLayout 會隱藏到 minHeight 的高度,向下滑一點就會出現

snap

CollapsingToolbarLayout 只會有完全隱藏或完全顯示,不會有出現一半的情況

contentScrim
CollapsingToolbarLayout 收縮後的背景顏色。

expandedTitleMarginStart
還沒有收縮時title與左邊間距

expandedTitleMarginEnd
還沒有收縮時title與右邊間距

CollapsingToolbarLayout 裡的Layout屬性

app:layout_collapseMode (折叠模式)

  • pin — 當CollapsingToolbarLayout完全收縮時,Toolbar仍在螢幕上
  • parallax — 在滑動內容時,CollapsingToolbarLayout中的View也會同時滑動
  • app:layout_collapseParallaxMultiplier=”0.7" 變化過程的速度

我們想要完全收縮時仍有ToolBar出現,就需要將
ImageView 設定 app:layout_collapseMode=”parallax”
widget.Toolbar 設定 app:layout_collapseMode=”pin”

<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:title="羅東運動公園"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="24dp"
app:layout_scrollFlags="snap|scroll">
<ImageView
android:id="@+id/header"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/scenery"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="@+id/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>

ScrollView

layout_behavior

在ScrollView相關加上app:layout_behavior,設定AppBarLayout與ScrollView關聯,表示當Scrollview滑動時影響AppBarLayout。
@string/appbar_scrolling_view_behavior,值為 android.support.design.widget.AppBarLayout$ScrollingViewBehavior
用來通知AppBarLayout發生了滑動事件

<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</android.support.v4.widget.NestedScrollView>

完整程式:
https://github.com/evanchen76/CoordinatorLayout

下一篇:Day18 Reveal Effect

--

--