Set menus for multiple toolbars on android

送分小仙女□ 提交于 2020-01-21 02:41:48

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/31128698/set-menus-for-multiple-toolbars-on-android

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