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

Android Material Design 元件入門:Toolbar、TabLayout 與 NavigationView

編輯:關於 Android 程式設計

Android Material Design 提供了許多現代化的 UI 元件,例如 Toolbar、TabLayout、AppBarLayout、NavigationView、CoordinatorLayout 與 CollapsingToolbarLayout。本文整理這些元件的常見用法,方便快速回顧與查閱。

使用前,可以先加入 design 支援庫:

compile 'com.android.support:design:23.4.0'

AppBarLayout 嵌套 Toolbar 與 TabLayout

Toolbar 比傳統 ActionBar 更靈活,可以放在畫面的任意位置,也可以搭配 AppBarLayout 與 TabLayout 使用。常見做法是讓 CoordinatorLayout 作為父容器,AppBarLayout 放置 Toolbar 與 TabLayout,中間再用 ViewPager 承載可滾動內容。

使用時要注意 CoordinatorLayout 必須設定 android:fitsSystemWindows="true",否則 Toolbar 可能會與狀態欄重疊。可滾動內容也需要設定 app:layout_behavior,讓 AppBarLayout 能正確協調滾動行為。

若要讓 Toolbar 具備滾動效果,通常需要設定 layout_scrollFlags。常見值包括 scroll、enterAlways、enterAlwaysCollapsed、exitUntilCollapsed 與 snap。其中 scroll 代表該 view 可以隨滾動離開螢幕,enterAlways 代表向下滾動時會立即顯示,exitUntilCollapsed 則常見於折疊式 Toolbar。

AppBarLayout 嵌套 CollapsingToolbarLayout

CollapsingToolbarLayout 可以實現 Toolbar 的折疊效果,常用於需要較大標題區塊的頁面。

它可以設定 collapsing title、content scrim、status bar scrim、parallax scrolling children 與 collapseMode。子 view 可以設定 pin 或 parallax 模式,前者會固定在頂端,後者會產生視差效果。

NavigationView

NavigationView 常用於側滑選單。它可以透過 headerLayout 設定頂部區域,也可以透過 menu 設定選單內容。layout_gravity 則可以控制側滑選單從左側或右側滑出。

Snackbar 與整合效果

Snackbar 是一個輕量級的提示元件,比 Toast 更有互動性,也比 Dialog 更輕量。不過連續點擊按鈕時,可能會不断建立 Snackbar 實例,因此實務上可以加入適度的回收機制。

整體而言,Material Design 元件的強項在於組合性。只要掌握 CoordinatorLayout、AppBarLayout、Toolbar、TabLayout 與 NavigationView 的基本關係,就能快速搭建現代化的 Android 介面。

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