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

Android SlidingDrawer 抽屜效果的實作指南

編輯:關於 Android 程式設計

SlidingDrawer 能將內容隱藏在螢幕外,並允許使用者透過「手柄」(handle)將其滑出顯示。它可以垂直或水平滑動,由兩個 View 組成:一是可拖動的 handle,二是被隱藏的內容 View。使用時必須在佈局中明確指定 handle 與 content。

步驟一:佈置佈局檔

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <SlidingDrawer
        android:id="@+id/slidingdrawer"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:content="@+id/content"
        android:handle="@+id/handle"
        android:orientation="vertical" >
        <Button
            android:id="@+id/handle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="SlidingDraser" />
        <LinearLayout <!-- 隱藏的內容 -->
            android:id="@+id/content"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#00ffaa" >
            <Button
                android:id="@+id/button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button" />
            <EditText
                android:id="@+id/editText"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </SlidingDrawer>
</LinearLayout>

運行成果

為手柄自訂樣式

可在 drawable 中透過 selector 為手柄定義不同狀態下的圖形,讓抽屜在常態、按下、獲得焦點時呈現不同外觀:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/handle_normal" />
    <item android:state_pressed="true" android:drawable="@drawable/handle_pressed" />
    <item android:state_focused="true" android:state_enabled="true" android:drawable="@drawable/handle_focused" />
    <item android:state_enabled="true" android:drawable="@drawable/handle_normal" />
    <item android:state_focused="true" android:drawable="@drawable/handle_focused" />
</selector>

重要屬性

• android:allowSingleTap:是否可透過 handle 點擊開關。

• android:animateOnClick:點擊 handle 開關時是否播放動畫。

• android:content:隱藏的內容。

• android:handle:手柄。

重要方法

• animateClose():關閉時實現動畫。

• close():立即關閉。

• getContent():取得內容。

• isOpened():是否已全部打開。

• lock() / unlock():屏蔽 / 解除屏蔽觸摸事件。

• toggle():切換抽屜的開啟與關閉。

• setOnDrawerOpenListener / setOnDrawerCloseListener / setOnDrawerScrollListener:監聽抽屜的開啟、關閉與滑動。

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