6
4

2 回答 2

4

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.

于 2018-09-24T17:32:25.603 回答
0

要拥有多个 Toolbar(或 BottomAppBar),您必须手动为另一个充气。当您调用setSupportActionBar()onCreateOptionsMenu()时,您实际上是在这样做:

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);
}

其中R.id.bottomAppBar是 BottomAppBar 的 id,而 R.menu.menu_bottom菜单项的 id。

在你为主工具栏充气后在你的onCreateOptionsMenu()中调用这个方法,你会很高兴的。所有的项目点击都将由onOptionsItemSelected()方法正常处理。

如果您正在制作两个或更多常规工具栏,这也将起作用。

于 2019-09-08T21:40:37.520 回答