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

Android DrawerLayout 抽屜菜單實作:從版面結構到側滑互動

編輯:關於 Android 程式設計

DrawerLayout 同樣來自 V4 支援庫,直接繼承 ViewGroup,本質上是一個容器。它把「漢堡選單」這個互動模式變成一行 XML 就能搞定的事,是近幾年最常被使用的 UI 元件之一。

一、抽屜的擺放由 layout_gravity 決定

抽屜要從左邊還是右邊滑出,透過 android:layout_gravity 控制,可選值為 left / right(或支援 RTL 的 start / end)。

用 XML 佈局時,結構必須是:DrawerLayout 作為父容器 → 第一個子節點是主內容區 → 第二個子節點是抽屜區。這樣一來,內容展示區與抽屜選單區就自然被切開,各自填內容即可。

二、兩個必記的規則

  1. 第一個子 View 是顯示主內容的 View,寬高都要設為 match_parent。
  2. 第二個子 View 是抽屜 View,需要設定 layout_gravity="left|right" 指定滑出方向,高度設為 match_parent,寬度則要「小於螢幕寬度」(例如 80dp 或固定比例),否則抽屜會蓋滿整個畫面。

三、實作範例

<android.support.v4.widget.DrawerLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/drawerlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- 第一個子 View:主內容 -->
    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="content" />

    <!-- 第二個子 View:抽屜(寬度刻意小於螢幕) -->
    <ListView
        android:id="@+id/listview"
        android:layout_width="80dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:background="#FFB5C5" />

</android.support.v4.widget.DrawerLayout>

實現的效果:

四、加上監聽器,抽屜才「活」起來

光有版面只是靜態的側邊欄。Android 提供了 DrawerLayout.DrawerListener(或便利的 ActionBarDrawerToggle),覆寫其中的回呼就能在互動過程中插入自己的邏輯:

drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
    @Override public void onDrawerSlide(View drawerView, float slideOffset) { }
    @Override public void onDrawerOpened(View drawerView) { }   // 抽屜完全打開
    @Override public void onDrawerClosed(View drawerView) { }   // 抽屜完全關閉
    @Override public void onDrawerStateChanged(int newState) { }// Idle / Dragging / Settling
});

實務上最常見的用法,是在 onDrawerOpened 裡同步更新 ActionBar 的標題與圖示(漢堡 → 返回箭頭),並在 onDrawerClosed 還原。

五、幾個實務提醒

  • 若使用 Toolbar,記得把 ActionBarDrawerToggle 建出來並呼叫 syncState(),漢堡圖示才會跟著抽屜狀態旋轉。
  • 抽屜裡選完項目後,記得呼叫 drawerLayout.closeDrawer(...) 收起選單,這是最常被遺漏的一步。
  • 新版專案可改用 androidx.drawerlayout.widget.DrawerLayout,API 用法一致但支援度更好。
  • 抽屜內容若是清單,記得處理與側滑手勢的衝突,必要時用 requestDisallowInterceptTouchEvent() 協調。

以上就是本篇關於 DrawerLayout 抽屜菜單的介紹,希望對你的 Android 開發有所幫助。

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