更新onOptionsItemSelected()而不设置新的侦听器

时间:2016-07-25 16:30:51

标签: java android toolbar

所以我有几个设置片段,当我按下'save'图标时我想做不同的事情,我可以用toolbar.setOnMenuItemClickListener执行此操作,但这意味着为每个其他片段设置另一个侦听器,这感觉不对,做这件事的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,请尝试以下方法:

在您的片段中,覆盖方法onOptionsItemSelected()。如果您已正确分配选项菜单保存按钮和项目ID,您可以编写以下代码以实现您想要的效果。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    switch (id) {
        case R.id.save_button: // Be sure to replace this id with yours!
            // <This is where you should put the code for the button's action>
            return true;
    }

    return super.onOptionsItemSelected(item);
}