Question

I'm trying to create a context menu in a DialogPreference for an Android app (targeting API level 8, in case it's relevant). I've managed to get the menu to show (when an item in a ListView is clicked) via a slight hack, but I have no idea how to handle any resulting command. What I have so far is:

  • In my onItemClick handler, I do the following:

    list.setOnCreateContextMenuListener (new ContextMenuGenerator(control, position));
    list.showContextMenuForChild (control);
    list.setOnCreateContextMenuListener (null);
    
  • ContextMenuGenerator does the following:

    public class ContextMenuGenerator implements OnCreateContextMenuListener
    {
        // additional code redacted - not necessary for this question
    
        @Override
        public void onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo)
        {
             new MenuInflater(context).inflate (R.menu.address_set_preference_popup, menu); 
        }
    }
    

This results in the correct menu being displayed at the right time, but I have no idea what happens after I select an item. I presume onContextItemSelected(MenuItem) is called on the Dialog that the DialogPreference creates, but I have no idea how to get from there to code that I can handle that event in -- I don't see any way of subclassing that Dialog, nor does there appear to be a way of attaching an external listener to either it or the ContextMenu. Is there some other way I haven't thought of?

Was it helpful?

Solution

There may be no way to attach a listener to the Dialog or to the ContextMenu itself, but it turns out that the individual MenuItems that the ContextMenu contains do support a listener interface. The answer, therefore, is to modify ContextMenuGenerator thus:

    @Override
    public void onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo)
    {
        new MenuInflater(context).inflate (R.menu.address_set_preference_popup, menu);
        for (int i = 0; i < menu.size (); i ++)
            menu.getItem (i).setOnMenuItemClickListener (listener);
    }

where listener is an OnMenuItemClickListener that I passed in to the constructor and stored in a field.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top