Handling popup menu items click
Asked Answered
E

2

18

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>
Esra answered 25/5, 2015 at 10:36 Comment(0)
O
28

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;
                    }
                });
Oden answered 25/5, 2015 at 10:39 Comment(0)
C
2

If you need to take a click of the popup menu on the basis of id, below is the right way to do this:

 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;
        });
Calculation answered 16/3, 2021 at 5:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.