Android:menu的使用

来源:互联网 发布:加盟代理淘宝店 编辑:程序博客网 时间:2024/06/10 22:49

据我知道的有两种创建menu的方式:

一、 使用xml定义Menu
首先在res下新建menu菜单,然后添加item;
这里写图片描述

<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android">    <item        android:id="@+id/eat"        android:title="吃饭" />    <item        android:id="@+id/drink"        android:title="喝水"        /></menu>
  @Override    public boolean onCreateOptionsMenu(Menu menu) {        //getMenuInflater()方法能够得到 MenuInflater 对象,再调用它的 inflate()方法就可以给当前活动创建菜单了.        getMenuInflater().inflate(R.menu.main,menu);        return true;    }
 @Override    public boolean onOptionsItemSelected(MenuItem item) {        switch (item.getItemId())        {            case R.id.eat:                Toast.makeText(this, "你点击了吃饭", Toast.LENGTH_SHORT).show();                Intent  intent = new Intent(MainActivity.this,FirstActivity.class);                startActivity(intent);                break;            case R.id.drink:                Toast.makeText(this, "你点击了喝水", Toast.LENGTH_SHORT).show();                break;            default:        }        return true;    }}

这里写图片描述

这里写代码片

二、使用代码定义Menu

add方法的三个参数含义:
第一个int类型的group ID参数,代表的是组概念,你可以将几个菜单项归为一组,以便更好的以组的方式管理你的菜单按钮。

第二个int类型的item ID参数,代表的是项目编号。这个参数非常重要,一个item ID对应一个menu中的选项。在后面使用菜单的时候,就靠这个item ID来判断你使用的是哪个选项。

第三个int类型的order ID参数,代表的是菜单项的显示顺序。默认是0,表示菜单的显示顺序就是按照add的显示顺序来显示。

第四个String类型的title参数,表示选项中显示的文字。

 public boolean onCreateOptionsMenu(Menu menu) {        menu.add(0,0,0,R.string.menu_namezero);        menu.add(0,1,1,R.string.menu_nameone);        return true;    }
 @Override    public boolean onOptionsItemSelected(MenuItem item) {        switch (item.getItemId())        {            case 0:             Toast.makeText(this,"zero",Toast.LENGTH_SHORT).show();            case 1:            Toast.makeText(this,"one",Toast.LENGTH_SHORT).show();        }        return true;    }}

这里写图片描述

这里写图片描述

0 0
原创粉丝点击