您的位置:首页 > 移动开发 > Android开发

Android studio 使用Menu(菜单)

2015-07-02 10:11 639 查看
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,运行程序,如下显示:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: