Android Toolbar自定义菜单

1
2
3
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.menu_main); //加载菜单资源
toolbar.setOnMenuItemClickListener(listener); //菜单的点击事件
1
2
3
4
5
6
7
8
9
10
11
private Toolbar.OnMenuItemClickListener listener = new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
startActivity(new Intent(MainActivity.this, NotCarouselActivity.class));
break;
}
return false;
}
};

菜单资源文件:/res/menu/menu_main.mxl

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<item android:id="@+id/action_edit"
android:title="编辑"
android:orderInCategory="80"
android:icon="@mipmap/ab_edit"
app:showAsAction="ifRoom" />

<item android:id="@+id/action_share"
android:title="分享"
android:orderInCategory="90"
android:icon="@mipmap/ab_share"
app:showAsAction="ifRoom" />

<item android:id="@+id/action_settings"
android:title="非循环轮播"
android:orderInCategory="100"
app:showAsAction="never"/>
</menu>

注意不需要使用setSupportActionBar(toolBar),否则菜单不会显示

使用setOnMenuItemClickListener处理菜单点击事件会覆盖onOptionsItemSelected的处理

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :