menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" > <!-- 嵌套菜单 1.在item中添加menu标签,menu标签中再添加item标签 2.二级菜单以对话框形式出现,最多两级菜单--> <item android:id="@+id/menu_1" android:title="早餐"/> <item android:id="@+id/menu_2" android:title="午餐"/> <item android:id="@+id/menu_3" android:title="晚餐"> <menu> <item android:id="@+id/menu3_1" android:title="鱼香肉丝"/> <item android:id="@+id/menu3_2" android:title="香酥鸡块"/> <item android:id="@+id/menu3_3" android:title="皮蛋瘦肉粥"/> </menu> </item> </menu>
xml文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.menudemo.SubMenuDemo" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout>
源代码:
package com.example.menudemo; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.widget.Toast; public class SubMenuDemo extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_submenu); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. /**用xml文件加载菜单栏 * getMenuInflater().inflate(R.menu.sub_menu_demo, menu); */
/**通过代码的方式添加菜单 * 通过代码添加带有子菜单的菜单 */
SubMenu file = menu.addSubMenu("文件"); file.add(1, 1, 1, "新建"); file.add(1, 2, 1, "打开"); file.add(1, 3, 1, "保存"); file.setHeaderIcon(R.drawable.ic_launcher); file.setHeaderTitle("文件操作"); SubMenu edit = menu.addSubMenu("编辑"); edit.add(2,1,1,"复制"); edit.add(2,2,1,"粘贴"); edit.add(2,3,1,"剪切"); edit.setHeaderIcon(R.drawable.ic_launcher); edit.setHeaderTitle("编辑操作"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch(item.getGroupId()){ case 1:{ if(item.getItemId()==1){ Toast.makeText(this,"点击了新建" , Toast.LENGTH_SHORT).show(); }else if(item.getItemId()==2){ Toast.makeText(this,"点击了打开" , Toast.LENGTH_SHORT).show(); }if(item.getItemId()==3){ Toast.makeText(this,"点击了保存" , Toast.LENGTH_SHORT).show(); } break; }case 2: if(item.getItemId()==1){ Toast.makeText(this,"点击了复制" , Toast.LENGTH_SHORT).show(); }else if(item.getItemId()==2){ Toast.makeText(this,"点击了粘贴" , Toast.LENGTH_SHORT).show(); }if(item.getItemId()==3){ Toast.makeText(this,"点击了剪切" , Toast.LENGTH_SHORT).show(); } } return super.onOptionsItemSelected(item); } }