Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appropriate alternative to PopupMenu for pre-Honeycomb

Tags:

android

I've implemented PopupMenu for a menu that is displayed after pressing an item on the ActionBar. I am wondering what alternatives there are for SDK versions before 11?

Possibly use something resembling a context menu. What are your thoughts?

My current implementation though, is to load a new Activity with the menu items.

like image 657
gak Avatar asked Mar 26 '12 20:03

gak


2 Answers

As @sastraxi suggested, a good solution is using an AlertDialog with CHOICE_MODE_SINGLE.

AlertDialog.Builder builder = new AlertDialog.Builder(MyAndroidAppActivity.this);
builder.setTitle("Pick color");
builder.setItems(R.array.colors, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
           // The 'which' argument contains the index position
           // of the selected item
       }
});
builder.setInverseBackgroundForced(true);
builder.create();
builder.show();

And the strings.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="colors">
        <item >blue</item>
        <item >white</item>
    </string-array>
</resources>

Reference: Adding a List

like image 57
gak Avatar answered Nov 05 '22 21:11

gak


Alternatively, you could use a floating context menu.


(3 years later, actually reads that floating context menu only works for long clicks and hastily edits answer).

You'd need to register your view for the context menu, open the menu, then unregister it (so that long-clicks on the action item didn't trigger it again):

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.my_menu_item) {
        View view = item.getActionView();
        registerForContextMenu(view);
        openContextMenu(view);
        unregisterForContextMenu(view);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

and of course, implement onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) as per the documentation linked.

The better choice would be, as OP wrote, to use an AlertDialog in this particular case if you wanted a centred dialog, or a PopupMenu if you want the menu to be anchored to the action item. The popup menu might be weird though, because it'll feel like an overflow menu.

like image 37
ataulm Avatar answered Nov 05 '22 20:11

ataulm