Brian D
Brian D

Reputation: 10133

How to implement context menus for custom ListViews?

How does one register a ListView for a context menu when using a custom ListView based on BaseAdapter?

I tried registerForContextMenu(getListView());, but this doesn't seem to work. I'm using ListView14.java from API Demos.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setListAdapter(new EfficientAdapter(this));
    registerForContextMenu(getListView());
}




@Override
public void onCreateContextMenu(ContextMenu menu, View v,
                                ContextMenuInfo menuInfo) {
  super.onCreateContextMenu(menu, v, menuInfo);
  MenuInflater inflater = getMenuInflater();
  inflater.inflate(R.menu.tag_context_menu, menu);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
  switch (item.getItemId()) {
  case R.id.tagView:
  //  editNote(info.id);
    return true;
  case R.id.tagRename:
   // deleteNote(info.id);
    return true;
  case R.id.tagDelete:
       // deleteNote(info.id);
        return true;
  default:
    return super.onContextItemSelected(item);
  }
}

Upvotes: 0

Views: 1634

Answers (1)

MacD
MacD

Reputation: 11

Instead of using registerForContextMenu(getListView()), try naming your listview in onCreate and using that reference:

Listview myListView = (Listview) findViewById(R.id.myListView); //or use any other constructor
registerForContextMenu(myListView);

This works for all the items in my adapter-fed Gridview (although it's turning out to be impossible to then properly adding a contextmenu to the gridview itself which registers longclicks on the empty gridview items, but that's another story altogether :) ), and I'd imagine a Listview to work the same.

Upvotes: 1

Related Questions