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

Android 學習指南之四十二:SlidingDrawer 抽屜效果實作

編輯:關於 Android 開發

在研究 Launcher 源碼時,我接觸並學習了 SlidingDrawer 類,也就是一般所說的「抽屜」控制項。

其實 SlidingDrawer 的用法相當簡單,關鍵在於 handle 與 content 兩部分。handle 就是當你點擊它時,content 要嘛被拉出來、要嘛被收起來。廢話不多說,具體步驟如下:

1、新建 Android 工程,命名為 SlidingDrawer。

2、準備素材。這裡我的圖示取自 Launcher2,放在 drawable-hdpi 資料夾中,目錄結構如下圖:

3、設定 main.xml 版面配置,程式碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:background="#808080"
  7. >
  8. <SlidingDrawer
  9. android:id="@+id/slidingdrawer"
  10. android:layout_width="fill_parent"
  11. android:layout_height="fill_parent"
  12. android:orientation="vertical"
  13. android:handle="@+id/handle"
  14. android:content="@+id/content">
  15. <Button
  16. android:id="@+id/handle"
  17. android:layout_width="88dip"
  18. android:layout_height="44dip"
  19. android:background="@drawable/handle"
  20. />
  21. <LinearLayout
  22. android:id="@+id/content"
  23. android:layout_width="fill_parent"
  24. android:layout_height="fill_parent"
  25. android:background="#00ff00">
  26. <Button
  27. android:id="@+id/button"
  28. android:layout_width="wrap_content"
  29. android:layout_height="wrap_content"
  30. android:text="Button"
  31. />
  32. <EditText
  33. android:id="@+id/editText"
  34. android:layout_width="fill_parent"
  35. android:layout_height="wrap_content"
  36. />
  37. </LinearLayout>
  38. </SlidingDrawer>
  39. </LinearLayout>

4、設定 handle 圖示的樣式,在 drawable 裡新增 handle.xml,程式碼如下:

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

5、運行,就會得到如下效果:

本文所講內容較為簡單,若想深入研究 SlidingDrawer 抽屜,可以查閱 Launcher 源碼。

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