我的应用中有两个材质工具栏,我有两个menu_main.xml
和menu_main2.xml
。图标在两个工具栏中都能正确显示,但其中一个工具栏上的操作无效。我该如何解决?
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);
这是我的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;
}
和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);
此操作有效,来自工具栏,
if (id == R.id.action_google) {
web1.setVisibility(View.GONE);
web2.setVisibility(View.GONE);
web3.setVisibility(View.VISIBLE);
}
这是来自Toolbar2,它不起作用......
if (id == R.id.action_naver) {
web1.setVisibility(View.VISIBLE);
web2.setVisibility(View.GONE);
web3.setVisibility(View.GONE);
}
答案 0 :(得分:2)
toolbar2.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem arg0) {
if(arg0.getItemId() == R.id.whatever){
}
return false;
}
});
答案 1 :(得分:0)
onOptionsItemSelected只会拾取第一个工具栏,因为它是您设置为supportActionBar的唯一工具栏。对于其他工具栏,您必须为项目设置单击侦听器。正如heloisasim建议的那样,您可以使用setOnMenuItemClickListener方法来执行此操作。