Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set menus for multiple toolbars on android

In my activity I use the following code for my two toolbars.

 @Override
 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Creating The Toolbar and setting it as the Toolbar for the activity
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("My title");

    toolbar2 = (Toolbar) findViewById(R.id.tool_bar_bottom);
    setSupportActionBar(toolbar2);
    ...
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
 }

I want it to use menu_main.xml for the top toolbar and menu_bottom for bottom toolbar but for both top and bottom toolbar it uses menu_main.xml.

Can somebody explain how to do it correctly?

like image 709
partiz Avatar asked Jun 30 '15 02:06

partiz


People also ask

Which method is used to add menu to the toolbar?

This is going to be in res/menu/main_menu . Right click the res folder and choose New > Android Resource File. Type main_menu for the File name. Choose Menu for the Resource type.

What is the difference between action bar and toolbar in Android?

An Action bar is traditionally a part of an Activity opaque window decor controlled by the framework but a Toolbar may be placed at any level of nesting within a view hierarchy. The toolbar provides more feature than ActionBar . A Toolbar may contain a combination of elements from start to end.

How do I show the toolbar on Android?

You can similarity assign to Main Menu-> View-> Toolbar and show toolbar again on Android studio IDE. Alternatively, after the main menu opened, click VIEW-> Toolbar tab.


1 Answers

As you are using two ToolBars set the menu like this

toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("My title");

The above toolbar inflate menu from onCreateOptionsMenu, menu CallBack listener will be onOptionsItemSelected

Now Second ToolBar

 toolbar2 = (Toolbar) findViewById(R.id.tool_bar_bottom);
 toolbar2.inflateMenu(R.menu.bottom_menu);//changed
 //toolbar2 menu items CallBack listener 
 toolbar2.setOnMenuItemClickListener(new OnMenuItemClickListener() {

    @Override
    public boolean onMenuItemClick(MenuItem arg0) {
        if(arg0.getItemId() == R.id.item_id){

        }
        return false;
    }
});
like image 185
Bharatesh Avatar answered Oct 18 '22 20:10

Bharatesh