1、无需设置布局文件
2、创建一个类,基础Activity
3、重写onOptionsItemSelected方法,在这个方法里面添加菜单项
4、如果需要给菜单项添加单击事件,需要重写onOptionsItemSelected方法
实例代码如下:
package com.yyl;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MenuDemoActivity extends Activity {
public static final int EIGHT_ID = Menu.FIRST+1;
public static final int SIXTEEN_ID = Menu.FIRST+2;
public static final int TWENTY_FOUR_ID = Menu.FIRST+3;
public static final int TWO_ID = Menu.FIRST+4;
public static final int THIRTY_TWO_ID = Menu.FIRST+5;
public static final int FORTY_ID = Menu.FIRST+6;
public static final int ONE_ID = Menu.FIRST+7;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//创建OptionsMenu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
this.populateMenu(menu);
return super.onCreateOptionsMenu(menu);
}
//单击事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
System.out.println(itemId);
return super.onOptionsItemSelected(item);
}
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE, "1 Pixel");
menu.add(Menu.NONE, TWO_ID, Menu.NONE, "2 Pixels");
menu.add(Menu.NONE, EIGHT_ID, Menu.NONE, "8 Pixels");
menu.add(Menu.NONE, SIXTEEN_ID, Menu.NONE, "16 Pixels");
menu.add(Menu.NONE, TWENTY_FOUR_ID, Menu.NONE, "24 Pixels");
menu.add(Menu.NONE, THIRTY_TWO_ID, Menu.NONE, "32 Pixels");
menu.add(Menu.NONE, FORTY_ID, Menu.NONE, "40 Pixels");
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
//得到点击的菜单项的ID(此Id是自己设定的)
int itemId = item.getItemId();
if(ONE_ID == itemId)
{
System.out.println("您选择了 1 Pixel 菜单");
}
return super.onMenuItemSelected(featureId, item);
}
}