demo
res/menu/menu.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <menu xmlns:android="http://schemas.android.com/apk/res/android" > 3 4 <item 5 android:id="@+id/menu_new" 6 android:icon="@android:drawable/ic_menu_help" 7 android:title="新建"/> 8 <item 9 android:id="@+id/menu_delete" 10 android:icon="@android:drawable/ic_menu_delete" 11 android:title="删除"/> 12 <item android:title="子菜单"> 13 <menu > 14 <item android:id="@+id/menu_sub1" 15 android:title="子菜单1"/> 16 <item android:id="@+id/menu_sub2" 17 android:title="子菜单2"/> 18 </menu> 19 </item> 20 21 </menu>
MainActivity
1 package com.android.hzy.menu; 2 3 import android.app.Activity; 4 import android.os.Bundle; 5 import android.view.Menu; 6 import android.view.MenuInflater; 7 import android.view.MenuItem; 8 import android.widget.Toast; 9 10 public class MainActivity extends Activity { 11 12 private static final int MENU_NEW_ID = 0; 13 private static final int MENU_DELETE_ID = 1; 14 private static final int MENU_SUB1_ID = 2; 15 private static final int MENU_SUB2_ID = 3; 16 17 @Override 18 protected void onCreate(Bundle savedInstanceState) { 19 super.onCreate(savedInstanceState); 20 setContentView(R.layout.activity_main); 21 } 22 23 // 创建菜单 24 @Override 25 public boolean onCreateOptionsMenu(Menu menu) { 26 // menu.add(0, MENU_NEW_ID, 0, "新建"); 27 // menu.add(0, MENU_DELETE_ID, 0, "删除"); 28 // // 创建的子菜单 29 // SubMenu subMenu = menu.addSubMenu("子菜单"); 30 // subMenu.add(1, MENU_SUB1_ID, 0, "子菜单1"); 31 // subMenu.add(2, MENU_SUB2_ID, 0, "子菜单2"); 32 33 // 通过配置文件来创建menu菜单 34 MenuInflater mInflater = getMenuInflater(); 35 mInflater.inflate(R.menu.menu, menu); 36 return super.onCreateOptionsMenu(menu); 37 } 38 39 @Override 40 public boolean onOptionsItemSelected(MenuItem item) { 41 // TODO Auto-generated method stub 42 int id = item.getItemId(); 43 switch (id) { 44 case MENU_NEW_ID: 45 Toast.makeText(this, "您选择了 :" + item.getTitle(), 0).show(); 46 break; 47 case MENU_DELETE_ID: 48 Toast.makeText(this, "您选择了 :" + item.getTitle(), 0).show(); 49 break; 50 case MENU_SUB1_ID: 51 Toast.makeText(this, "您选择了 :" + item.getTitle(), 0).show(); 52 break; 53 case MENU_SUB2_ID: 54 Toast.makeText(this, "您选择了 :" + item.getTitle(), 0).show(); 55 break; 56 57 default: 58 Toast.makeText(this, "您选择了 :" + item.getTitle(), 0).show(); 59 break; 60 } 61 return super.onOptionsItemSelected(item); 62 } 63 64 }
示例图: