有多种方法可以设置菜单,这里采用的方法是以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); }
1611

被折叠的 条评论
为什么被折叠?



