Android Toolbar Action icon not working

落爺英雄遲暮 提交于 2019-12-25 04:43:04

问题


I have two Material Toolbars in my app, and I have two menu_main.xml and menu_main2.xml. The icon shows properly in both toolbars, but the action on one of the toolbar doesn't work. How can I fix it?

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

    //Setup Toolbar
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);
    toolbar2 = (Toolbar) findViewById(R.id.tool_bar2);
    toolbar2.inflateMenu(R.menu.menu_main2);

This is my onCreateOptions,

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

and onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    web1 = (WebView) findViewById(R.id.web1);
    web2 = (WebView) findViewById(R.id.web2);
    web3 = (WebView) findViewById(R.id.web3);

This action works, it is from Toolbar,

   if (id == R.id.action_google) {
        web1.setVisibility(View.GONE);
        web2.setVisibility(View.GONE);
        web3.setVisibility(View.VISIBLE);
    }

This is from Toolbar2, which doesn't work...

    if (id == R.id.action_naver) {
        web1.setVisibility(View.VISIBLE);
        web2.setVisibility(View.GONE);
        web3.setVisibility(View.GONE);
    }

回答1:


toolbar2.setOnMenuItemClickListener(new OnMenuItemClickListener() {

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

            }
            return false;
        }
    });



回答2:


Only the first toolbar will be picked up by onOptionsItemSelected since that's the only one you set as a supportActionBar. For the other toolbar, you will have to set click listeners for your items. As heloisasim suggested, you can use the setOnMenuItemClickListener method to do this.



来源:https://stackoverflow.com/questions/31128809/android-toolbar-action-icon-not-working

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