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

Android 菜單機制全解:Options Menu、Context Menu 與動態菜單

編輯:Android 開發教學

簡介

Android 提供三類菜單:options menu、context menu 與 sub menu。

options menu 透過按鍵喚出;context menu 則需在某个 view 上長按約兩秒才會出現。這兩種菜單都可以掛子菜單,但子菜單不能再生出下一層。options menu 在螢幕最下方最多顯示 6 個選項,稱為 icon menu,且不能包含可勾選項;超過 6 個的部分會以 more 圖示收攏,稱為 expanded menu。options menu 由 Activity 的 onCreateOptionsMenu 建立,而這個方法只在菜單首次生成時被呼叫一次;因此任何想動態調整菜單內容的需求,都必須寫在菜單顯示前才會觸發的 onPrepareOptionsMenu 裡。至於選中項目的處理,則交給 onOptionsItemSelected。

context menu 與具體的 view 綁定,需在 Activity 中以 registerForContextMenu 為某個 view 註冊。它顯示前同樣會先呼叫 onCreateContextMenu 生成菜單,點選事件則由 onContextItemSelected 接手。

此外,Android 還支援菜單分組:把功能相近的項目歸在同一組,就能用 setGroupCheckable、setGroupEnabled、setGroupVisible 一次設定整組屬性,不必逐項處理。

Options Menu

Notepad 範例同時用到了 options menu 與 context menu。先看生成 options menu 的 onCreateOptionsMenu:

 menu.add(0, MENU_ITEM_INSERT, 0, R.string.menu_insert)
 .setShortcut('3', 'a')
 .setIcon(android.R.drawable.ic_menu_add);

這是插入一個菜單項的標準寫法,項目 id 為 MENU_ITEM_INSERT。真正有意思的是下面這幾行:

 Intent intent = new Intent(null, getIntent().getData());
 intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
 menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
 new ComponentName(this, NotesList.class), null, intent, 0, null);

這段程式在做什麼?其實這是一種動態菜單技術,機制上還有點像外掛。規則是這樣的:如果某個 Activity 的類型標記為 "android.intent.category.ALTERNATIVE",且資料型別為 "vnd.android.cursor.dir/vnd.google.note",系統就會自動為它補上一個菜單項。翻遍 AndroidManifest.xml 會發現,沒有任何 Activity 同時滿足這兩個條件,所以這段程式碼實際上並沒有動態掛出任何項目。

為了驗證上述推斷,我們可以動手做個實驗:修改 AndroidManifest.xml,看看菜單項是否會被動態生成。

實驗一

先建立一個新 Activity 作為目標,取名 HelloAndroid,不做什麼功能,就是把一個介面顯示出來:

 public class HelloAndroid extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 this.setContentView(R.layout.main);
 }
 }

對應的版面配置如下:

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent" >
 <TextView android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:id="@+id/TextView01"/>
 <Button android:id="@+id/Button01"
 android:layout_height="wrap_content"
 android:layout_width="fill_parent"
 android:text="@string/txtInfo"></Button>
 </LinearLayout>

接著在 AndroidManifest.xml 中加入下面這段設定,讓 HelloAndroid 滿足前述兩個條件:

 <activity android:name="HelloAndroid" android:label="@string/txtInfo">
 <intent-filter>
 <action android:name="com.android.notepad.action.HELLO_TEST" />
 <category android:name="android.intent.category.ALTERNATIVE"/>
 <data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />
 </intent-filter>
 </activity>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved