Activity 在預設的情況中按下選單鍵是沒有反應的, 要讓選單鍵產生作用相當簡單,只要注意以下兩點
1. 複寫 activity的 onCreateOptionsMenu 方法, 在方法中加入想要顯示的選單項目(MenuItem)
2. 複寫 activity的 onOptionsItemSelected 方法, 在方法中加入點選各選單項目(MenuItem)要對應的動作
實作程式碼如下
import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends Activity { public static final int ADD_ID = 0; public static final int DELETE_ID = 1; public static final int ABOUT_ID = 2; public static final int EXIT_ID = 3; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); addMenuItems(menu); return true; } private void addMenuItems(Menu menu) { menu.add(Menu.NONE, ADD_ID, Menu.NONE, R.string.menu_add); menu.add(Menu.NONE, DELETE_ID, Menu.NONE, R.string.menu_delete); menu.add(Menu.NONE, ABOUT_ID, Menu.NONE, R.string.menu_about); menu.add(Menu.NONE, EXIT_ID, Menu.NONE, R.string.menu_exit); } public boolean onOptionsItemSelected(MenuItem item) { selectMenuItemEvents(item); return super.onOptionsItemSelected(item); } private void selectMenuItemEvents(MenuItem item) { switch (item.getItemId()) { case ADD_ID: setTitle(getResources().getString(R.string.menu_add)); break; case DELETE_ID: setTitle(getResources().getString(R.string.menu_delete)); break; case ABOUT_ID: setTitle(getResources().getString(R.string.menu_about)); break; case EXIT_ID: break; } } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > </LinearLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">MENU</string> <string name="menu_add">add item</string> <string name="menu_delete">delete item</string> <string name="menu_about">about</string> <string name="menu_exit">exit</string> <string name="menu_about_msg">message for about...</string> <string name="str_ok">OK</string> <string name="str_cancel">Cancel</string> <string name="menu_exit_msg">exit system?</string> </resources>