Android筆記:Menu

來源:互聯網
上載者:User

標籤:

使用菜單選項Menu,需要進行以下操作:
(1)重寫onCreateOptionsMenu方法;

 

public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true;}

 

(2)在menu的main.xml檔案中加入item的聲明.

(3)重寫onOptionsItemSelected方法

 

public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) {     case item1:           break;     case item2:           break;     ...     default:}return true;}

 

範例程式碼模仿自《第一行代碼》

(1)MenuDemo.java的代碼如下:

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestWindowFeature(Window.FEATURE_NO_TITLE);  //消去標題列        setContentView(R.layout.activity_main);    }    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.main, menu);        return true;    }        //定義菜單響應事件    public boolean onOptionsItemSelected(MenuItem item) {         switch(item.getItemId()){         case R.id.riven:               Toast.makeText(this, "斷劍重鑄之日,其勢歸來之時!!",  Toast.LENGTH_SHORT).show();               break;         case  R.id.ezreal:               Toast.makeText(this, "是時候表演真正的技術!!", Toast.LENGTH_SHORT).show();               break;        default:                   }        return true;    }    }

(2)在layout的activity_main.xml:

 <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="歡迎來到召喚師峽穀!\n請點擊菜單鍵顯示菜單選項" />

(3)在menu的main.xml代碼:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >      <item        android:id="@+id/riven"        android:orderInCategory="100"        android:showAsAction="never"        android:title="放逐之刃銳雯"/>      <item        android:id="@+id/ezreal"        android:orderInCategory="100"        android:showAsAction="never"        android:title="@string/ezreal"/></menu>

(4)在values的string.xml中,定義string常量.

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">MenuDemo</string>    <string name="action_settings">Settings</string>    <string name="hello_world">Hello world!</string>    <string name="ezreal">探險家伊澤瑞爾</string></resources>

代碼效果如下:

點擊Menu選項後,顯示如下:

 

Android筆記:Menu

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.