在活动中使用Menu(笔记)

    xiaoxiao2026-10-05  6

    在活动中使用Menu

       //创建菜单    @Override       public boolean onCreateOptionsMenu(Menu menu) {           //第一个参数是引用自己创建的菜单布局文件,如下,第二个参数是添加到哪一个menu中,目前是直接使用onCreateOptionsMenu中传入的menu参数         getMenuInflater().inflate(R.menu.xxxx, menu);          return true;  //true表示允许创建的菜单显示出来,如果返回了false,创建的菜单将无法显示     }  

    getMmenuInflater()方法得到的是MenuInflater对象,再调用它的inflate()方法就可以给当前活动创建菜单了。

    新建xml文件

    <menu xmlns:android="http://schemas.android.com/apk/res/android" >       <item           android:id="@+id/add_item"           android:title="Add"/>       <item           android:id="@+id/remove_item"           android:title="Remove"/>   </menu> 

    再重写onOptionsItemSelected()方法来定义菜单响应事件

    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;   }  

    转载请注明原文地址: https://ju.6miu.com/read-1312636.html
    最新回复(0)