Android菜单的使用

来源:互联网 发布:js监听函数 编辑:程序博客网 时间:2024/04/29 11:33

有多种方法可以设置菜单,这里采用的方法是以menu配置文件的方式来设置菜单。

menu.xml文件(放在menu文件夹下):

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto">    <item        android:id="@+id/add_message"        android:icon="@mipmap/add_white_icon"        android:title="添加"        app:showAsAction="always" />    <item        android:id="@+id/search_message"        android:icon="@mipmap/search_white_icon"        android:title="搜索"        app:showAsAction="always" /></menu></span>
上面的showAsAction属性是标识其是否显示,Always表示始终显示在界面上。
然后在Activity中重写onCreateOptionsMenu:
<span style="font-size:18px;">@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, menu);        return true;    }</span>
这样就可以显示菜单了。

设置menu的点击事件,需要重写onOptionsItemSelected方法:

@Override    public boolean onOptionsItemSelected(MenuItem item) {        int id = item.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }
这样就可以监听到菜单的点击事件了。==


0 0