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

用 DrawerLayout 元件實作側滑抽屜

編輯:關於 Android 程式設計

DrawerLayout 同樣來自 v4 套件,直接繼承自 ViewGroup,本質是個容器。有了它,抽屜效果幾乎不必寫額外程式碼,只要遵守兩條布局約定。

兩條規則

1. 第一個子 View 是內容區。它的 layout_width 與 layout_height 都必須設為 match_parent,因為它會填滿整個螢幕,抽屜是疊在它上面的。

2. 第二個子 View 是抽屜本身。要透過 layout_gravity 指定它從左側還是右側滑出(left 或 right),高度設為 match_parent,寬度則依抽屜內容決定。

布局範例

 <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" >

    <TextView
        android:id="@+id/textview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="content" />

    <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>

運行效果:

幾個實務上的細節

抽屜打開時通常希望使用者無法誤觸底下的內容,可以在程式碼中為 DrawerLayout 設定 setScrimColor() 調整遮罩顏色,或呼叫 setDrawerLockMode() 在特定狀態下鎖住滑動。

若抽屜裡放的是表單類內容,記得讓抽屜可捲動,否則項目一多就會超出螢幕。

另外,抽屜的開合狀態建議監聽 DrawerListener(或 Override onDrawerOpened/onDrawerClosed),在開啟時同步選單的高亮狀態、關閉時歸零——這是使用者判斷「我目前在哪一頁」的主要依據,少了它抽屜會顯得沒有回饋。

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