Android ApiDemos樣本解析(25) App->Menu->Inflate from XML

來源:互聯網
上載者:User

本例示範了如何從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

最簡單的菜單,菜單只含有文本描述。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.