Appropriate alternative to PopupMenu for pre-Honeycomb

前端 未结 2 1863
感动是毒
感动是毒 2021-01-02 05:22

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?

相关标签:
2条回答
  • 2021-01-02 05:35

    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

    0 讨论(0)
  • 2021-01-02 05:38

    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.

    0 讨论(0)
提交回复
热议问题