Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android Material Design 新 UI 元件指南(三):AppBarLayout 與 CollapsingToolbarLayout

編輯:關於 Android 程式設計

前言

在認識 NavigationView、TextInputLayout、Snackbar、FloatingActionButton、TabLayout 與 CoordinatorLayout 之後,本文接著分析 AppBarLayout 與 CollapsingToolbarLayout。這兩種元件常用於打造具有滑動回應效果的應用程式頂部。

AppBarLayout

AppBarLayout 是繼承自 LinearLayout 的容器元件,預設以垂直方向排列子元件。它能讓 Toolbar、TabLayout 等內容成為 AppBar 的一部分,並支援手勢滑動,管理內容滾動時的顯示與隱藏行為。

使用時,通常會把 Toolbar 與 TabLayout 放入 AppBarLayout,且 AppBarLayout 必須作為 Toolbar 的父層容器。

CoordinatorLayout 與 AppBarLayout 的結合

AppBarLayout 的手勢回應通常需要 CoordinatorLayout 搭配。下圖展示常見結構:上方是 Toolbar 與 TabLayout,中間是 ViewPager,右下角則是 FloatingActionButton。

CoordinatorLayout 可視為增強版 FrameLayout,透過 layout_gravity 屬性即可把子元件放在指定位置。若希望 Toolbar 在向上滑動時隱藏,可設定 layout_scrollFlags。

  • scroll:讓元件能隨內容滾動離開畫面。
  • enterAlways:向下滑動時立即顯示,向上滑動時隱藏。
  • enterAlwaysCollapsed:搭配 minHeight,讓元件先以最小高度出現,再逐步展開。
  • exitUntilCollapsed:搭配 minHeight,讓元件在達到最小高度後停止退出。

此外,可滾動內容必須能被 CoordinatorLayout 感知。常見做法是讓 RecyclerView 或 NestedScrollView 等可滾動元件設定 layout_behavior,例如 appbar_scrolling_view_behavior。ListView 與 ScrollView 本身不支援此機制。

CollapsingToolbarLayout 可折疊的 Toolbar

若只需要簡單隱藏或顯示 Toolbar,動畫效果有限。CollapsingToolbarLayout 能讓標題、背景與子元件在折疊過程中呈現更細緻的過渡,因此適合用於詳情頁或具有大圖區塊的頁面。

CollapsingToolbarLayout 通常包含一個 Toolbar,並作為 AppBarLayout 的子元件。其常見屬性與用法如下:

  • Collapsing title:在 CollapsingToolbarLayout 上設定標題,展開時字體較大,折疊後縮小。
  • Content scrim:Toolbar 折疊到頂部後的背景。
  • Status bar scrim:狀態列背景。
  • Parallax scrolling children:子元件視差滾動效果,可透過 collapseParallaxMultiplier 調整。
  • collapseMode:pin 會固定於頂端,parallax 則產生視差折疊。
  • layout_anchor 與 layout_anchorGravity:讓懸浮元件依附於指定視圖。

實作時需特別注意:AppBarLayout 高度不宜使用 wrap_content,否則動畫可能不自然;FloatingActionButton 可透過 anchor 屬性,使其隨折疊手勢一起移動。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved