Google 官網教學 - Menus | Android Developer

game_menu.xml: 定義 actionbar menu layout (Defining a Menu in XML)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"
          android:icon="@drawable/ic_new_game"
          android:title="@string/new_game"
          android:showAsAction="ifRoom"/>
    <item android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help" />
</menu>

onCreateOptionsMenu: 在 Activity 裡用 MenuInflater 指名哪一種 actionbar menu layout (Creating an Options Menu)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);   
    return true;
}

onOptionsItemSelected: 撰寫各個 icon 按下後的動作 (Handling click events)

處理動作欄(Action Bar)的用戶選項操作, onOptionsItemSelected()

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

Comments

comments powered by Disqus
Copyright © 2013 Andro Chen
Powered by Logdown and Greyshade
Favicon from The Noun Project