1.通过XML布局添加菜单
首先在项目目录res下建立文件夹menu,然后在新建的menu文件夹下添加
menu.xml
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/about" android:title="About" /> <item android:id="@+id/exit" android:title="Exit" /> </menu>
在ActivityMain中添加菜单
ACtivityMain.java
package ly.exercise; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; public class ActivityMain extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } /*覆写下面两个方法*/ /*添加菜单*/ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater=getMenuInflater(); inflater.inflate(R.menu.menu, menu);//指定使用的XML return true; } /*处理菜单事件*/ @Override public boolean onOptionsItemSelected(MenuItem item) { int item_id=item.getItemId();//得到当前选中MenuItem的ID switch(item_id){ case R.id.about:{ //事件处理代码 } case R.id.exit:{ //事件处理代码 } } return true; } }
2.通过Menu.add方法添加菜单
在ActivityMain中添加菜单
ACtivityMain.java
package ly.exercise; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class ActivityMain extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } /*覆写下面两个方法*/ /*添加菜单*/ @Override public boolean onCreateOptionsMenu(Menu menu) { /*menu.add(组ID,项ID,显示顺序,显示标题)*/ menu.add(0,0,0,"About"); menu.add(0,1,1,"Exit"); return true; } /*处理菜单事件*/ @Override public boolean onOptionsItemSelected(MenuItem item) { int item_id=item.getItemId();//得到当前选中MenuItem的ID switch(item_id){ case 0:{ //事件处理代码 } case 1:{ //事件处理代码 } } return true; } }