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

Android UI 進階:活用 SlidingDrawer 抽屜控制項

編輯:關於 Android 程式設計

最近在開發一個應用時,有個想法:把設定頁面和應用頁面放在一起,讓使用者能即時看到自己調整設定後對 UI 的影響,這樣操作起來會更方便。琢磨了好一陣子,最後發現 SlidingDrawer 這個控制項正好能實現這樣的效果——也就是一個「抽屜」。拉開抽屜會佔據半個螢幕,另外半個螢幕仍顯示應用頁面,效果相當不錯。

其實 Android 的 launcher 本身就是一個抽屜,打開它就能看到已安裝的應用,相信大家都見過、用過。下面我們就來做一個類似的效果,當然只在 UI 呈現上追求相近。

SlidingDrawer 的佈局設定

SlidingDrawer 使用起來非常簡單,基本上在 XML 中設定好即可:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:textSize="20sp" />
    <SlidingDrawer
        android:id="@+id/sd"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:handle="@+id/iv"
        android:content="@+id/myContent"
        android:orientation="vertical">
        <ImageView
            android:id="@+id/iv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/open1" />
        <GridView
            android:id="@id/myContent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numColumns="3"
            android:background="@drawable/background"
            android:gravity="center" />
    </SlidingDrawer>
</RelativeLayout>

在 SlidingDrawer 標籤中,android:handle 指的是抽屜的把手圖片,android:content 則指向抽屜內部的佈局內容。有了這兩個設定,一個抽屜的雛形就出來了。

Activity 中的事件處理

接著在 Activity 中載入佈局,並為抽屜設定開關的監聽事件,讓把手圖片能依狀態切換:

sd.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {
    public void onDrawerOpened() {
        iv.setImageResource(R.drawable.close1); // 開啟時設為向下箭頭
    }
});
sd.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {
    public void onDrawerClosed() {
        iv.setImageResource(R.drawable.open1); // 關閉時恢復
    }
});

抽屜內部我用 GridView 搭配一個自定義的 MyAdapter,來顯示「圖標 + 文字」的項目效果。MyAdapter 繼承 BaseAdapter,在 getView 中透過 LayoutInflater 載入自定義佈局並綁定圖片與文字即可。

以下是最終的執行效果:

SlidingDrawer 是個非常實用的控制項,除了本文所述的應用場景外,還有許多發揮空間。只要善加利用,它一定能為你的應用增添不少亮點。

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