在res文件夹下新建一个menu文件夹,在menu文件夹下新建一xml文件,xml文件代码如下:
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <group android:id="@+id/grout_main" > <item android:id="@+id/menu_1" android:title="This 1"/> <item android:id="@+id/menu_2" android:title="This 2"/> </group> </menu>
此为一级菜单,如果想实现二级菜单徐需要menu,group,item嵌套使用
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <group android:id="@+id/grout_main" > <item android:id="@+id/menu_1" android:title="This 1"/> <item android:id="@+id/menu_2" android:title="This 2"> <menu > <group android:id="@+id/grout_2" > <item android:id="@+id/menu_2_1" android:title="This 3"/> <item android:id="@+id/menu_2_2" android:title="This 4"/> </group>
</menu> </item> </group> </menu>
重写activity中的menu方法如下:
public boolean onCreateOptionsMenu(Menu menu) { // TODO Auto-generated method stub MenuInflater menuflater = getMenuInflater(); menuflater.inflate(R.menu.menu_file, menu);//读取xml文件 menu.add(0, 3, 3, "html");//添加一个menu项其Id为3 return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated method stub switch (item.getItemId()) { case R.id.menu_1: Toast.makeText(this, "m1", Toast.LENGTH_SHORT).show(); showdigo(); break; case R.id.menu_2: Toast.makeText(this, "m2", Toast.LENGTH_SHORT).show(); this.finish(); break; case 3: Intent in = new Intent(); in.putExtra("str", "欢迎测试"); in.setClass(TestActivity02Activity.this, TestActivtiy03.class); TestActivity02Activity.this.startActivity(in); // Toast.makeText(TestActivity02Activity.this, "跳转activity", Toast.LENGTH_LONG).show(); break; default: break; } return super.onOptionsItemSelected(item); }