In  previous posts we explored two types of android menus: Options menu and submenus. In this post we’re going to see another menu type: Context menus.

Context Menu:


Context menus are the menus that appear when you right-click in windows.
In android Context menu are attached to widgets and the appear when you click on the widget for a long time (long click).

To add context menus to widgets you have to do two things:
  1. Register the widget for a context menu.
  2. Add menu items to the context menu.
So to register a context menu with a TextView you do it like this:
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        txt=(TextView)findViewById(R.id.txt);
        registerForContextMenu(txt);
    }

We call registerForContextMenu(View V) method to tell the activity that the view is going to have a context menu.

Then we add items to the context menu by overriding the onCreateContext method:
@Override
    public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo info)
    {
     menu.setHeaderTitle("Context Menu");
     menu.add("Item");
    }

When you make a long click on the text view the context menu will appear like this:


The onCreateContextMenu method has the following parameters:
  1. Context Menu: an instance of the context menu.
  2. View: the view to which the context menu is attached.
  3. ContextMenuInfo: carries additional information regarding the creation of the context menu.
To handle the context menu items click events you can implement the callback method onContextItemSelected.
We do it the same way we handle onOptionsItemSelected.
@Override
    public boolean onContextItemSelected(MenuItem item)
    {
     txt.setText(item.getTitle());
     return true;
    }