简体   繁体   English

Android工具栏操作图标不起作用

[英]Android Toolbar Action icon not working

I have two Material Toolbars in my app, and I have two menu_main.xml and menu_main2.xml . 我的应用程序中有两个menu_main.xml menu_main2.xml ,并且有两个menu_main.xmlmenu_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, 这是我的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. 和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... 这是来自Toolbar2,它不起作用...

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

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

            }
            return false;
        }
    });

Only the first toolbar will be picked up by onOptionsItemSelected since that's the only one you set as a supportActionBar. onOptionsItemSelected将仅拾取第一个工具栏,因为这是您设置为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. 如heloisasim所建议的,您可以使用setOnMenuItemClickListener方法来执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM