Two different menus for Top App Bar and Bottom App bar with Navigation Components

谁都会走 提交于 2019-12-01 04:38:02

Just use onCreateOptionsMenu() for the Toolbar as usual: (Kotlin)

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_first, menu)
        return super.onCreateOptionsMenu(menu)
    }

Then declare the Toolbar inside onCreate() and use setSupportActionBar():

val toolbar = findViewById<Toolbar>(R.id.myToolbar)
setSupportActionBar(toolbar)

And after that, replaceMenu() will do the trick: (Inside onCreate())

val bottomBar = findViewById<BottomAppBar>(R.id.bottomAppBar)
bottomBar.replaceMenu(R.menu.menu_main)

Note that if you wanted to use BottomSheetFragment for the NavigationView opening, you'll need setSupportActionBar in order to set menus for the BottomAppBar and I couldn't still find a way to fix this.

To have more than one Toolbar (or BottomAppBar), you will have to inflate the other one manually. When you call setSupportActionBar() and onCreateOptionsMenu(), you are essentially doing this:

private boolean inflateBottomAppBar() {
    BottomAppBar bottomAppBar = findViewById(R.id.bottomAppBar);
    Menu bottomMenu = bottomAppBar.getMenu();
    getMenuInflater().inflate(R.menu.menu_bottom, bottomMenu);
    for (int i = 0; i < bottomMenu.size(); i++) {
        bottomMenu.getItem(i).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {
                return onOptionsItemSelected(menuItem);
            }
        });
    }
    return super.onCreateOptionsMenu(menu);
}

Where R.id.bottomAppBar is the id of the BottomAppBar and R.menu.menu_bottom is the id of the menu items.

Call this method in your onCreateOptionsMenu() after you inflate the main toolbar and you will be good to go. All the item clicks will be handled normally by the onOptionsItemSelected() method.

This will also work if you are making two or more regular toolbars.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!