处理弹出菜单项会点击

时间:2015-05-25 10:36:07

标签: android onitemclicklistener popupmenu

我已经为我的Android应用程序实现了一个弹出菜单。我已经为弹出菜单创建了一个xml,代码也可以正常工作。现在我无法弄清楚如何处理弹出菜单项单击。我尝试过使用PopupMenu.OnMenuItemClickListener,但没有成功。我怎么能这样做?

我的弹出式菜单代码

ImageButton button = (ImageButton) view.findViewById(R.id.popUp_song);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                    PopupMenu popup = new PopupMenu(activity, v);
                    Menu m = popup.getMenu();
                    MenuInflater inflater = popup.getMenuInflater();
                    inflater.inflate(R.menu.song_popup, popup.getMenu());

                    if (audio.getDownload().equals("0")) {

                        m.removeItem(R.id.add_download);

                    }

                    popup.show();
                }


            });

XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/ToolBarStyle">

    <item
        android:id="@+id/add_queue"
        android:title="Add to queue" />
    <item
        android:id="@+id/play_next"
        android:title="Add to favourite" />
    <item
        android:id="@+id/add_download"
        android:title="Download" />


</menu>

2 个答案:

答案 0 :(得分:14)

在显示PopupMenu之前为PopupMenu添加一个用于处理点击事件的监听器。

popupMenu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(getApplicationContext(),
                                item.getTitle(), Toast.LENGTH_SHORT).show();
                        return true;
                    }
                });

答案 1 :(得分:0)

如果您需要根据 id 单击弹出菜单,以下是正确的方法:

 popup.setOnMenuItemClickListener(item -> {
           if (item.getItemId() == R.id.miEmail) {
                Toast.makeText(getApplicationContext(), "Email clicked", Toast.LENGTH_SHORT).show();
            } else if (item.getItemId() == R.id.miCall) {
                Toast.makeText(getApplicationContext(), "Call clicked", Toast.LENGTH_SHORT).show();
            }

            return true;
        });