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

Android 菜單全景解析:OptionsMenu、ContextMenu 與 PopupMenu 一次搞懂

編輯:關於 Android 開發

Android 菜單項完整指南

一、菜單是什麼

菜單是應用介面裡再熟悉不過的元件,幾乎每個 App 都會用到它來承載常用操作。在 Android 3.0 之前,裝置上都配有一顆實體「Menu」按鍵來喚出菜單;而從 3.0 開始,取而代之的是 ActionBar(操作欄)來實現同樣的功能。

官方文件:https://developer.android.com/guide/topics/ui/menus.html

二、菜單的分類

1. OptionsMenu(選項菜單)

在 Android 2.3.x 及更早版本中,使用者按下實體「菜單」鍵後,選項菜單會出現在螢幕底部;而在 3.0 及更高版本中,菜單項會直接呈現在操作欄裡。預設情況下,系統會把項目收進操作溢出菜單,使用者可透過右側的溢出圖示(或菜單鍵)展開;但若你在 XML 中設定 android:showAsAction="ifRoom",就能把指定項目直接提升到操作欄顯示。

* 並非所有 App 都會把菜單放進操作欄,這取決於 App 是否使用自訂的操作欄設計。

透過重寫 onCreateOptionsMenu() 即可建立選項菜單:

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu); // 加載菜單資源
    menu.add("新增選項菜單");                        // 直接添加一級菜單
    menu.addSubMenu("新增選項菜單子菜單");            // 添加子菜單
    menu.findItem(R.id.action_settings).setTitle("設置"); // 查詢並修改屬性
    return true;
}

處理點擊事件時,系統會呼叫 Activity 的 onOptionsItemSelected(),透過 getItemId() 辨識被選中的項目:

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.new_game:
            newGame();
            return true;
        case R.id.help:
            showHelp();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

2. ContextMenu(上下文菜單)

上下文菜單提供針對介面中特定項目的操作,通常用於 ListView、GridView 等集合型視圖的每一個項目上。Android 提供了兩種實現方式。

(1)浮動式上下文菜單

使用者長按某個宣告支援上下文菜單的視圖時,會彈出一個類似對話框的浮動列表,一次可對一個項目操作。

建立步驟:

1、呼叫 registerForContextMenu() 將菜單綁定到具體 View。若 View 是 ListView 或 GridView,菜單會綁定到所有 item。

2、在 Activity 中實作 onCreateContextMenu(),於註冊視圖收到長按事件時被觸發。

3、實作 onContextItemSelected() 處理選擇事件:

public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.context_menu_1:
            Toast.makeText(getApplicationContext(), "選擇菜單1,你要做什麼,自己做...", 0).show();
            return true;
        default:
            return super.onContextItemSelected(item);
    }
}
(2)上下文操作模式(ActionMode)

此模式會在螢幕頂部顯示上下文操作欄,允許使用者一次對多個項目執行操作。

為單一視圖啟用步驟:實作 ActionMode.Callback 接口,並在需要時呼叫 startActionMode()。

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }
    @Override
    public void onDestroyActionMode(ActionMode mode) {
        actionMode = null; // 方便記憶體回收
    }
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater menuInflater = mode.getMenuInflater();
        menuInflater.inflate(R.menu.context_menu, menu);
        return true;
    }
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.context_menu_1:
                button2.setText(item.getTitle());
                actionMode.finish(); // 完成任務後釋放 ActionMode
                return true;
            default:
                return false;
        }
    }
};

若要在 ListView 或 GridView 中啟用批次操作,可使用 setMultiChoiceModeListener() 並將選擇模式設為 CHOICE_MODE_MULTIPLE_MODAL:

listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
lv = (ListView) findViewById(R.id.lv);
strings = new ArrayList<String>();
strings.add("item1");
strings.add("item2");
strings.add("item3");
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
lv.setAdapter(adapter);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
lv.setMultiChoiceModeListener(new MultiChoiceModeListener() {
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater menuInflater = mode.getMenuInflater();
        menuInflater.inflate(R.menu.context_menu, menu);
        return true;
    }
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.context_menu_1:
                strings.add("item4");
                adapter.notifyDataSetChanged();
                return true;
            default:
                return false;
        }
    }
    // 其餘回調方法省略
});

小提示:若擔心使用者沒發現長按操作,可額外加上核取方塊等 UI 元素,透過 setItemChecked() 主動觸發上下文操作模式。

3. PopupMenu(彈出式菜單)

錨定到某個 View 的模態菜單,空間足夠時顯示在該視圖下方,否則顯示在上方。常見場景包括:為特定內容提供溢出式操作(如 Gmail 郵件標頭)、作為命令的延伸選項,或提供類似 Spinner 但不保留選擇的下拉菜單。

ImageView iv1 = (ImageView) findViewById(R.id.iv1);
iv1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, v);
        MenuInflater menuInflater = popupMenu.getMenuInflater();
        menuInflater.inflate(R.menu.popup_menu, popupMenu.getMenu());
        popupMenu.show();
        popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.popup_menu_1:
                        return true;
                    default:
                        return false;
                }
            }
        });
    }
});

若想要更靈活的自訂菜單,則可採用 PopupWindow,它能指定自繪的 View 作為彈出內容,並精確控制出現位置:

Button btn3 = (Button) findViewById(R.id.btn3);
btn3.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        View contentView = LayoutInflater.from(v.getContext()).inflate(
                R.layout.popup_menu, null);
        PopupWindow popupWindow = new PopupWindow(contentView,
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        // 若不設定背景,點擊外部或按 Back 鍵都無法關閉彈框
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.q2));
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(v, Gravity.TOP, (int) v.getX(), (int) v.getY());
    }
});

* 要實現點擊外部關閉的功能,以下兩行程式碼缺一不可:

popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.q2));
popupWindow.setOutsideTouchable(true);

遮罩效果則可透過在根佈局加上半透明背景色(如 #b0000000),並監聽觸摸事件判斷點擊位置來實現:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/ll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#b0000000"
    android:orientation="vertical">

final PopupWindow popupWindow = new PopupWindow(inflate,
        RelativeLayout.LayoutParams.MATCH_PARENT,
        RelativeLayout.LayoutParams.WRAP_CONTENT);
// 針對使用者可視範圍之外的點擊,讓視窗消失
inflate.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        int height = inflate.findViewById(tv).getTop();
        int y = (int) event.getY();
        if (event.getAction() == MotionEvent.ACTION_UP) {
            if (y < height) {
                popupWindow.dismiss();
            }
        }
        return true;
    }
});
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved