androidonitemclicklistenerpopupmenu

Handling popup menu items click


I've implemented a popup menu to my android application. I've created a xml for popup menu and code also works fine. Now what i cant figure out is how to handle popup menu items click. I've tried using PopupMenu.OnMenuItemClickListener but was not successful. How can i do this?

My code for popup menu

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>

Solution

  • Before showing the PopupMenu add a listener for PopupMenu for handling the click events.

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