Quick Pop-up with Context Menu in Android

During the creation of an android application, sometimes it is required to show a popup menu to get quick action from the user. For example, when a user long presses on any view we have to show some options and the user is able to pick one of them, and based on the selection we have to perform some tasks. To show this kind of pop-up android provides context menu API. Let's check how we can use it with an example.

The context 
menu provides an ability to bind any view with it. You can also change the subject of the menu if it is required.
 
To show a pop-up menu first, you have to register that view with registerForContextMenu().
For now, Don't get confused with the method. Later we are going to check how to use it in the application but for now, just remember that to show the context menu we have to register it with the above method.

Add Items to the Menu

To add the items in the menu you have to override the onCreateContextMenu in the activity shown in the example below :

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.setHeaderTitle("Context Menu Example ");
    menu.add(0, v.getId(), 0, "Item One");
    menu.add(0, v.getId(), 0, "Item Two");
}

So now all the items are added in the context menu and ready to show to the user. To register the view we are using the below code in the onCreate method of the activity:-
registerForContextMenu(yourView)


Handle Item Click

Now if you run the application, you can check that the menu is registered and show when the user long press on view. But to start your task based on user choice you have to handle the context menu. For that, you have to override onContextItemSelected.Here is the example to get the menu item click :

@Override
public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle() == "Item One") {
        // do your coding

      return true;
    }
    return false;

}

Comments