Android onMenuItemClick() - 检测点击了哪个菜单?

时间:2015-11-07 14:01:34

标签: android button view menu popup

我目前正在编写一个简单的应用程序,该应用程序使用2个按钮与弹出菜单相关联,按下按钮时将显示该按钮。这很简单,但是我遇到了onMenuItemClick()方法的问题,我想用它将按钮的文本更改为单击的菜单项。

由于我有两个Pop Up菜单,每个都有3个项目,这是否意味着我必须在onMenuItemClick()中编写6个不同的if语句,每个语句都试图检测单击哪个菜单的菜单?或者有更简单的方法,例如指定2个onMenuItemClick()方法,每个方法都链接到单独的2个菜单?

public class MainActivity extends AppCompatActivity implements OnMenuItemClickListener {

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

    public void showColourPopUpMenu(View v){
        PopupMenu coloursPopUpMenu = new PopupMenu(this, v);
        coloursPopUpMenu.setOnMenuItemClickListener(this);
        coloursPopUpMenu.inflate(R.menu.colours_menu);
        coloursPopUpMenu.show();
    }

    public void showShapePopUpMenu(View v){
        PopupMenu shapesPopUpMenu = new PopupMenu(this, v);
        shapesPopUpMenu.setOnMenuItemClickListener(this);
        shapesPopUpMenu.inflate(R.menu.shape_menu);
        shapesPopUpMenu.show();
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        //How to determine which menu clicked?
        return false;
    }
}

3 个答案:

答案 0 :(得分:3)

在对齐时创建侦听器。

popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        return true;
    }
});

答案 1 :(得分:2)

@Override
public boolean onMenuItemClick(MenuItem item) {
    int id = item.getItemId()
    switch(id) {
     case R.id.item1:
          return true;
     case R.id.item2:
          return true;
     default:
          return false;
    }
}

答案 2 :(得分:2)

直接不可能。您至少需要将项目ID item.getItemId()映射到他们所连接的菜单(按钮)。

也许有点简单可能会使用以下组: menu / colours_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <group android:id="@+id/colours_menu" >
        <item android:id="@+id/item1" ... />
        <item android:id="@+id/item2" ... />
        <item android:id="@+id/item3" ... />
    </group>
</menu>

使用item.getGroupId(),您将获得组ID,只需将这些映射到按钮:

@Override
public boolean onMenuItemClick(MenuItem item) {
    if (item.getGroupId() == R.id.colours_menu) {
        // edit colors menu
    } else {
        // edit shape menu
    }
}