Definiert IDs in popupmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/slot1"
app:showAsAction="ifRoom|withText"
android:title="Movies"
android:visible="true"/>
<item
android:id="@+id/slot2"
app:showAsAction="ifRoom|withText"
android:title="Music"
android:visible="true"/>
<item
android:id="@+id/slot3"
app:showAsAction="ifRoom|withText"
android:title="Comedy"
android:visible="true"/>
</menu>
PopupMenu popupMenu = new PopupMenu(FullMenuActivity.this, view);
popupMenu.setOnMenuItemClickListener(FullMenuActivity.this);
popupMenu.getMenu().add(1, R.id.slot1, 1, "slot1");
popupMenu.getMenu().add(1,R.id.slot2,2,"slot2");
popupMenu.getMenu().add(1,R.id.slot3,3,"slot3");
popupMenu.show();
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.slot1:
SessionManager.selected_slot = item.getTitle().toString();
Toast.makeText(this, "slot1 Clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.slot2:
SessionManager.selected_slot = item.getTitle().toString();
Toast.makeText(this, "slot2 Clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.slot3:
SessionManager.selected_slot = item.getTitle().toString();
Toast.makeText(this, "slot3 Clicked", Toast.LENGTH_SHORT).show();
return true;
default:
return true;
}
}
Wenn Sie nach generierten Popup-Elementen mit Rückrufen suchen, verwenden Sie diese Option.
Java
public static void popupMenu(final Context context, View anchor, final LinkedHashMap<String,IPopupMenu> options){ PopupMenu popupMenu = new PopupMenu(context, anchor); for(String key : options.keySet()){ popupMenu.getMenu().add(key); } popupMenu.getMenuInflater().inflate(R.menu.popup_menu,popupMenu.getMenu()); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { options.get(menuItem.getTitle()).onClick(); return true; } }); popupMenu.show(); } public interface IPopupMenu{ void onClick(); }
XML
<?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> </menu>
Beispiel
LinkedHashMap<String,IPopupMenu> menu_items = new LinkedHashMap<>(); menu_items.put("Item Name", new Utils.IPopupMenu() { @Override public void onClick() { //do your code } }); menu_items.put("My Item", new Utils.IPopupMenu() { @Override public void onClick() { //do code } }); //you can anchor the popup menu to whatever you like. i.e Button, TextView, View. popupMenu(context,button,menu_items);
quelle