Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Menu Items in Android PopupMenu

Tech 1

Create a PopupMenu instance anchroed to a UI component:

View anchorElement = findViewById(R.id.context_trigger);
PopupMenu actionMenu = new PopupMenu(getApplicationContext(), anchorElement);

Add entries to the menu programmatically:

Menu menuContainer = actionMenu.getMenu();
menuContainer.add("Export Data");
menuContainer.add("Archive Item");
menuContainer.add("Configure Settings");

Define click handling for menu options:

actionMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem selectedItem) {
        String command = selectedItem.getTitle().toString();
        if ("Export Data".equals(command)) {
            // Export functionality
        } else if ("Archive Item".equals(command)) {
            // Archiving process
        } else if ("Configure Settings".equals(command)) {
            // Settings navigation
        }
        return true;
    }
});

Display the menu when triggered:

actionMenu.show();

Complete implementation:

View anchorElement = findViewById(R.id.context_trigger);
PopupMenu actionMenu = new PopupMenu(getApplicationContext(), anchorElement);

Menu menuContainer = actionMenu.getMenu();
menuContainer.add("Export Data");
menuContainer.add("Archive Item");
menuContainer.add("Configure Settings");

actionMenu.setOnMenuItemClickListener(item -> {
    String command = item.getTitle().toString();
    if ("Export Data".equals(command)) {
        // Export functionality
    } else if ("Archive Item".equals(command)) {
        // Archiving process
    } else if ("Configure Settings".equals(command)) {
        // Settings navigation
    }
    return true;
});

actionMenu.show();

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.