How to cancel the creation of a context menu after

2019-05-26 06:53发布

问题:

I have an activity that registers a list view for the creation of the context menu:

registerForContextMenu(getListView());

The problem is that a long click on some items should not present the context menu, because the items are disabled.

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);

    bool bDisplayMenu = isItemEnabled(((AdapterView.AdapterContextMenuInfo) menuInfo).position);

    if(bDisplayMenu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }
    else
    {
        // WHAT SHOUlD I DO HERE TO CANCEL THE CREATION OF THE CONTEXT MENU?
    }

}

I don't see any way to cancel the creation of the context menu once onCreateContextMenu() has been called.

回答1:

Well, it turned out that if I exit from onCreateContextMenu() immediately after calling super, then the context menu doesn't appear at all.

Not sure this is the way to go (I didn't see any documentation regarding this).

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);

    bool bDisplayMenu = isItemEnabled(((AdapterView.AdapterContextMenuInfo) menuInfo).position);

    if(bDisplayMenu)
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
    }
    else
    {
        return; // the context menu will not be displayed
    }

}