本例示範了如何從Menu 資源(XML 定義)展開功能表項目。這個例子的onCreate 採用了使用代碼來建立Activity 介面的方法 而通常的方法是採用Layout資源的方法。如果你有興趣瞭解一下如何使用代碼建立UI,可以參考本例的onCreate方法,但這不是 本例的示範目的。
使用XML 菜單資源來展開菜單的一般步驟是
1. 在/res/menu目錄下定義菜單資源,本例中定義 了10種不同風格的功能表項目:”Title only”, “Title and Icon”, “Submenu”, “Groups”,”Checkable”, “Shortcuts” , “Order”, “Category and Order”,”Visible”, “Disabled”。
最簡單的Menu資源定義如下:只包括id 和title 定義。
<menu xmlns:android=”http://schemas.android.com/apk/res/android”>
<item android:id=”@+id/jump”
android:title=”@string/jump” />
<item android:id=”@+id/centere”
android:title=”@string/centere” />
</menu>
2. 展開菜單資源,Android支援兩大類菜單Option Menu(主菜單),Context Menu (內容相關性功能表)。本例使用Option Menu ,可以在public boolean onCreateOptionsMenu(Menu menu) 方法中使用MenuInflater 展開菜單資源:
@Override public boolean onCreateOptionsMenu(Menu menu) { // Hold on to this mMenu = menu; // Inflate the currently selected menu XML resource. MenuInflater inflater = getMenuInflater(); inflater.inflate (sMenuExampleResources[mSpinner.getSelectedItemPosition()], menu); // Disable the spinner since we've already created the menu and the user // can no longer pick a different menu XML. mSpinner.setEnabled(false); // Change instructions mInstructionsText.setText(getResources().getString( R.string.menu_from_xml_instructions_go_back)); return true; }
3. 為菜單添加處理事件的方法。
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.jump: ... default: ..
但使用者選擇某個菜單時將觸發onOptionsItemSelected 事件,參數item為使用者選擇的Menu Item,可以根據Menu 的 Id來實現功能表項目對應的操作。
本例菜單使用10種不同的風格,基本使用方法是都是一樣的,不同是定義在XML item的屬 性。
Title only
最簡單的菜單,菜單只含有文本描述。