简体   繁体   中英

Context menu in Android DialogPreference… is it possible?

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?

There may be no way to attach a listener to the Dialog or to the ContextMenu itself, but it turns out that the individual MenuItem s 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM