Context Menu

  • Context menu is a menu that is dedicated to a particular item in the screen. It is generally opened on long taping the item but that's not necessary. It's on you how you want the context menu to be opened.

    Step 1. Decide how you want to open the context menu. According to your decision, choose the listener. For example if you want the menu to be opened on single clicking the item, use onClickListener. Similarly if you want it to be opened on long clicking, use onLongClickListener.

    We are using onLongClickLitener on a view that is in variable but1.
  • but1.setOnLongClickListener(new OnLongClickListener() {


    public boolean onLongClick(View arg0) {

    // TODO Auto-generated method stub


    return false;



  • Use above code in onCreate() method of the activity. This long click listener registers the view but1 for context menu and also opens the context menu. So now clicking on the item but1, a context menu will be opened. Now we will add title and items to the context menu.
  • Note: If you are using long click listener, above code will automatically open the context menu. But if you are using some other listener, add the following statement to the code-
  • openContextMenu(but1);

    Step 2. Use a method onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) of the class Activity, to create the context menu. The first parameter of this method represents the context menu and it will be used to configure the menu. Second parameter represents the view that is registered for this context menu. In our case, this view is 'but1'.


    public void onCreateContextMenu(ContextMenu menu, View v,

    ContextMenuInfo menuInfo) {

    // TODO Auto-generated method stub

    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle("Choose one option");

    menu.add("First Item");

    menu.add("Second Item");

    menu.add("Third Item");


  • Above code sets a title for the context menu and adds three items to it.
  • By here, your context menu is ready to be displayed. But it will be displayed only. It's item will not work at all. To make them work, we have to use a different mehod.
  • Step 3. Use a method onContextItemSelected(MenuItem item) of the class Activity to define the function that will be performed on clicking the items of the context menu. It has one parameter which represents the item of the menu that has been clicked.


    public boolean onContextItemSelected(MenuItem item) {

    // TODO Auto-generated method stub

    Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();

    return super.onContextItemSelected(item);