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>
PopupMenu - A modal menu that is anchored to a particular view within an activity. The menu appears below that view when it is selected. Used to provide an overflow menu that allows for secondary actions on an item. PopupWindow - A simple dialog box that gains focus when appearing on screen.
The contextual action mode displays action items that affect the selected content in a bar at the top of the screen and allows the user to select multiple items. See the section about Creating Contextual Menus. A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu.
Go to app > res > right-click > New > Android Resource Directory and give Directory name and Resource type as menu. Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it as popup_menu.
Pop-up menus appear over the application in a vertical orientation while the user is clicking an item, and then they disappear from the screen. You can programmatically invoke a pop-up menu, or you can arrange for a right-mouse click to automatically invoke a pop-up menu tied to a window or a control.
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;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With