How to create context menu


SDK Version: 
M3

There are two main methods that you must implement to get this thing work.
First of all, implement and override the onCreateContextMenu():

  1. @Override
  2.         public void onCreateContextMenu(ContextMenu menu, View v,
  3.                         ContextMenuInfo menuInfo) {
  4.                 super.onCreateContextMenu(menu, v, menuInfo);
  5.                 menu.setHeaderTitle("Choose an option");
  6.                 menu.add(0, v.getId(), 0, "Add to favorites");
  7.                 menu.add(0, v.getId(), 0, "See details");
  8.         }

If you have a ListVew, you must call

  1. registerForContextMenu(myListView);

Last, you have to implement and override onContextItemSelected()

  1.         public boolean onContextItemSelected(MenuItem item) {
  2.                 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
  3.  
  4.                 if (item.getTitle() == "Add to favorites") {
  5.                  // Do something }
  6.                 else if (item.getTitle() == "See details") {
  7.                         // Do something
  8.                 } else {
  9.                         return false;
  10.                 }
  11.                 return true;
  12.         }