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

后端 未结 2 1669
情书的邮戳
情书的邮戳 2021-01-12 14:53

I was trying out Android Navigation Architecture Component and was also looking into Material design guidelines. I really got inspired by the design below:

相关标签:
2条回答
  • 2021-01-12 15:34

    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.

    0 讨论(0)
  • 2021-01-12 15:51

    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.

    0 讨论(0)
提交回复
热议问题