Set menus for multiple toolbars on android-ThrowExceptions

Exception or error:

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?

How to solve:

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

Leave a Reply

Your email address will not be published. Required fields are marked *