Android studio 使用Menu(菜单)

1,打开res目录下的mune文件夹,如下图


2,在menu_main.xml中添加如下代码:

<menu xmlns:android="http://schemas.android.com/apk/res/android"  xmlns:app="http://schemas.android.com/apk/res-auto"  xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <item android:id="@+id/add_item" android:title="Add" />
    <item android:id="@+id/remove_item" android:title="Remove" />
</menu>
3,在MainActivity中重写onCreatOptionsMenu()方法,如下:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.  getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
4,在MainActivity中重写on=OptionsItemSelected()方法,如下:

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch(item.getItemId()){
           case R.id.add_item:
               Toast.makeText(this,"you clicked Add",Toast.LENGTH_SHORT).show();
               break;
           case R.id.remove_item:
               Toast.makeText(this,"you clicked Remove",Toast.LENGTH_SHORT).show();
               break;
           default:
       }
            return true;

    }
}
5,运行程序,如下显示:








你可能感兴趣的:(Android studio 使用Menu(菜单))