1

I'm not entirely sure this is possible, but I have several activities that use a listview adapter. I want to implement a context menu on the listview items which I have been able to do using

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    vi.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            menu.setHeaderTitle(sf.checkBusinessTitle(businessList.getBusinessName()));
            ....rest of context menu creation code...
        }
}

How can I create the onContextItemSelected from the adapter?

EDIT: I get the error "The method onContextItemSelected(MenuItem) of type MyAdapter must override or implement a supertype method" if I add the following to the adapter:

@Override
public boolean onContextItemSelected(MenuItem item){
}

Any help would be appreciated.

1 Answers1

1

Exactly the same way you would do outside your ArrayAdapter implementation. In the getView() method, simply set:

your_context.registerForContextMenu(convertView);    // Supposing convertView is your View

And define the onContextItemSelected overriding method in the Activity, not in the ArrayAdapter extension.

nKn
  • 13,691
  • 9
  • 45
  • 62
  • So I have to add code to each Activity that uses the listview to handle the onContextItemSelected? No way to get one set of code to handle the selection? – user2610744 Jan 14 '14 at 17:31
  • Not sure what are you trying to do and how, but if you're trying to reuse the same `ListView` on several Activities it can probably be implemented with a `Fragment` or even easier defining a global function (in a class that extends `Application`) where you pass the `ListView` id and it overrides the `onContextItemSelected` method for that View. Hope this helps! – nKn Jan 14 '14 at 17:38
  • Ok - have put it into a `Fragment` .. how do I retrieve the ID of the item in the listview within the onContextItemSelected – user2610744 Jan 14 '14 at 17:46
  • I think this is what you want to do, have a look at this: http://stackoverflow.com/questions/5297842/how-to-handle-oncontextitemselected-in-a-multi-fragment-activity – nKn Jan 14 '14 at 17:48