1.创建menu
<?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/addFriend" android:icon="@drawable/addfriend" android:orderInCategory="80" android:title="添加朋友" app:showAsAction="never" /> <item android:id="@+id/newChat" android:icon="@drawable/morechat" android:orderInCategory="90" android:title="新建群聊" app:showAsAction="never" /> <item android:id="@+id/scan" android:icon="@drawable/scan" android:orderInCategory="100" android:title="扫一扫" app:showAsAction="never"/> <item android:id="@+id/money" android:icon="@drawable/money" android:orderInCategory="100" android:title="收付款" app:showAsAction="never"/> </menu>
2.activity
布局引入toolbar
<androidx.appcompat.widget.Toolbar android:background="@color/blue" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/toolbar"/>
setSupportActionBar(mMainBinding.toolbar); 不调用就不会显示toolbar getSupportActionBar().setTitle("环信 app"); 设置toolbar的标题 mMainBinding.toolbar.setOnMenuItemClickListener(listener); 设置监听器
重写onCreateOptionsMenu 加载menu @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.toolbar, menu); return true; }
重写onPrepareOptionsPanel 加载menu的图标 @Override protected boolean onPrepareOptionsPanel(View view, Menu menu) { if (menu != null) { if (menu.getClass() == MenuBuilder.class) { try { Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE); m.setAccessible(true); m.invoke(menu, true); } catch (Exception e) { } } } return super.onPrepareOptionsPanel(view, menu); }
监听器
private final Toolbar.OnMenuItemClickListener listener = new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.addFriend: Toast.makeText(MainActivity.this, "addFriend", Toast.LENGTH_SHORT).show(); break; case R.id.scan: Toast.makeText(MainActivity.this, "scan", Toast.LENGTH_SHORT).show(); break; case R.id.newChat: Toast.makeText(MainActivity.this, "newChat", Toast.LENGTH_SHORT).show(); //弹出自定义popWindow //popUpMyOverflow(); break; case R.id.money: Toast.makeText(MainActivity.this, "money", Toast.LENGTH_SHORT).show(); break; } return false; } };