整体运行效果如下图:
具体实现:
1、创建过程,工程名为Menu
2、在工程目录“res/menu”目录下创建一个名为menu.xml的文件,内容如下:
class="code_img_closed" src="/Upload/Images/2014122216/0015B68B3C38AA5B.gif" alt="" />logs_code_hide('53981756-c4d2-424a-b30b-824af535891f',event)" src="/Upload/Images/2014122216/2B1B950FA3DF188F.gif" alt="" />1 <?xml version="1.0" encoding="utf-8"?> 2 <menu xmlns:android="http://schemas.android.com/apk/res/android" > 3 <item 4 android:id="@+id/help" 5 android:title="帮助"/>" 6 <item 7 android:id="@+id/our" 8 android:title="联系我们"/> 9 </menu>View Code
3、编写MainActivity.java的文件。具体代码如下:
1 package com.example.menu; 2 3 import android.app.Activity; 4 import android.app.ActionBar; 5 import android.app.Fragment; 6 import android.os.Bundle; 7 import android.view.LayoutInflater; 8 import android.view.Menu; 9 import android.view.MenuInflater; 10 import android.view.MenuItem; 11 import android.view.View; 12 import android.view.ViewGroup; 13 import android.os.Build; 14 15 public class MainActivity extends Activity { 16 17 final int ok=1; 18 final int cancle=2; 19 final int about=3; 20 @Override 21 protected void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23 setContentView(R.layout.activity_main); 24 25 if (savedInstanceState == null) { 26 getFragmentManager().beginTransaction() 27 .add(R.id.container, new PlaceholderFragment()).commit(); 28 } 29 } 30 31 @Override 32 public boolean onCreateOptionsMenu(Menu menu) { 33 34 menu.add(0,ok,0,"开始"); 35 menu.add(0,cancle,0,"取消"); 36 Menu file=menu.addSubMenu(0,about,0,"关于"); 37 38 // Inflate the menu; this adds items to the action bar if it is present. 39 getMenuInflater().inflate(R.menu.menu, file); 40 return true; 41 } 42 43 @Override 44 public boolean onOptionsItemSelected(MenuItem item) { 45 // Handle action bar item clicks here. The action bar will 46 // automatically handle clicks on the Home/Up button, so long 47 // as you specify a parent activity in AndroidManifest.xml. 48 int id = item.getItemId(); 49 switch(id){ 50 case ok: 51 this.setTitle("开始"); 52 return true; 53 case cancle: 54 this.setTitle("取消"); 55 return true; 56 case about: 57 this.setTitle("关于"); 58 return true; 59 case R.id.help: 60 this.setTitle("帮助信息"); 61 return true; 62 case R.id.our: 63 this.setTitle("联系我们"); 64 return true; 65 66 } 67 68 return super.onOptionsItemSelected(item); 69 } 70 71 /** 72 * A placeholder fragment containing a simple view. 73 */ 74 public static class PlaceholderFragment extends Fragment { 75 76 public PlaceholderFragment() { 77 } 78 79 @Override 80 public View onCreateView(LayoutInflater inflater, ViewGroup container, 81 Bundle savedInstanceState) { 82 View rootView = inflater.inflate(R.layout.fragment_main, container, 83 false); 84 85 86 return rootView; 87 } 88 } 89 90 }View Code