Android Create a simple menu programmatically

后端 未结 5 927
遥遥无期
遥遥无期 2021-02-01 12:36

I\'m trying to create a simple menu with one button that will call a method to clear the array. I don\'t want to use xml because all I need is one button.

Something like

5条回答
  •  执笔经年
    2021-02-01 13:02

    If you're looking for generated popup items with callbacks, used this.

    Java

    public static void popupMenu(final Context context, View anchor, final LinkedHashMap 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

    
    
    
    
    
    

    Example

    LinkedHashMap menu_items = new LinkedHashMap<>();
    menu_items.put("Item Name", new Utils.IPopupMenu() {
             @Override
             public void onClick() {
                //do your code
             }
    });
    menu_items.put("Clear Array", new Utils.IPopupMenu() {
             @Override
             public void onClick() {
                //clear array
             }
    });
    
    popupMenu(context,button,menu_items);
    

提交回复
热议问题