android menu
一:
activity 中添加菜单可以复写 public boolean onCreateOptionsMenu(Menu menu);
public boolean onCreateOptionsMenu(Menu menu) { // -------------向menu中添加子菜单------------- SubMenu p = menu.addSubMenu("测试"); SubMenu prog = menu.addSubMenu("启动程序"); // 设置菜单头的图标 p.setHeaderIcon(R.drawable.tools); p.setHeaderTitle("测试标题"); MenuItem item1 = p.add("启动other"); item1.setIntent(new Intent(this , OtherActivity.class)); prog.setHeaderIcon(R.drawable.tools); // 设置菜单头的标题 prog.setHeaderTitle("选择您要启动的程序"); // 添加菜单项 MenuItem item = prog.add("查看经典Java EE"); //为菜单项设置关联的Activity item.setIntent(new Intent(this , OtherActivity.class)); return super.onCreateOptionsMenu(menu); }
xml配置文件的菜单项
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="@string/font_size" android:icon="@drawable/font"> <menu> <!-- 定义一组单选菜单项 --> <group android:checkableBehavior="single"> <!-- 定义多个菜单项 --> <item android:id="@+id/font_10" android:title="@string/font_10"/> <item android:id="@+id/font_12" android:title="@string/font_12"/> <item android:id="@+id/font_14" android:title="@string/font_14"/> <item android:id="@+id/font_16" android:title="@string/font_16"/> <item android:id="@+id/font_18" android:title="@string/font_18"/> </group> </menu> </item> <!-- 定义一个普通菜单项 --> <item android:id="@+id/plain_item" android:title="@string/plain_item"> </item> <item android:title="@string/font_color" android:icon="@drawable/color"> <menu> <!-- 定义一组允许复选的菜单项 --> <group> <!-- 定义3个菜单项 --> <item android:id="@+id/red_font" android:title="@string/red_title"/> <item android:id="@+id/green_font" android:title="@string/green_title"/> <item android:id="@+id/blue_font" android:title="@string/blue_title"/> </group> </menu> </item> </menu>
在activity中复写 public boolean onCreateOptionsMenu(Menu menu)
@Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflator = new MenuInflater(this); // 状态R.menu.context对应的菜单,并添加到menu中 inflator.inflate(R.menu.my_menu, menu); return super.onCreateOptionsMenu(menu); } // 选项菜单的菜单项被单击后的回调方法 public boolean onOptionsItemSelected(MenuItem mi) { if(mi.isCheckable()) { mi.setChecked(true); //② } // 判断单击的是哪个菜单项,并针对性的作出响应。 switch (mi.getItemId()) { case R.id.font_10: txt.setTextSize(10 * 2); break; case R.id.font_12: txt.setTextSize(12 * 2); break; case R.id.font_14: txt.setTextSize(14 * 2); break; case R.id.font_16: txt.setTextSize(16 * 2); break; case R.id.font_18: txt.setTextSize(18 * 2); break; case R.id.red_font: txt.setTextColor(Color.RED); mi.setChecked(true); break; case R.id.green_font: txt.setTextColor(Color.GREEN); mi.setChecked(true); break; case R.id.blue_font: txt.setTextColor(Color.BLUE); mi.setChecked(true); break; case R.id.plain_item: Toast toast = Toast.makeText(MenuResTest.this, "您单击了普通菜单项", Toast.LENGTH_SHORT); toast.show(); break; } return true; }