Using context menus in Android

Context menus are used in Android to provide options to the user in response to a long-press or a right-click event. They are commonly used to perform actions on the items displayed in a ListView or a RecyclerView.

To use context menus in Android, you need to follow these steps:

Register the view for which the context menu is to be displayed using the registerForContextMenu() method. For example:

ListView listView = findViewById(R.id.list_view);

registerForContextMenu(listView);

Override the onCreateContextMenu() method to create the context menu and add menu items to it. For example:

@Override

public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

    super.onCreateContextMenu(menu, v, menuInfo);

    getMenuInflater().inflate(R.menu.context_menu, menu);

}

In this example, the R.menu.context_menu resource file contains the menu items to be added to the context menu.

Handle the selection of a menu item in the onContextItemSelected() method. For example:

@Override

public boolean onContextItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.menu_item_delete:

            // Perform the delete operation

            return true;

        case R.id.menu_item_edit:

            // Perform the edit operation

            return true;

        default:

            return super.onContextItemSelected(item);

    }

}

In this example, the R.id.menu_item_delete and R.id.menu_item_edit are the IDs of the menu items added to the context menu in the onCreateContextMenu() method.

Finally, unregister the view for which the context menu was displayed using the unregisterForContextMenu() method. For example:

@Override

public void onDestroy() {

    super.onDestroy();

    unregisterForContextMenu(listView);

} In this example, the listView is the view for which the context menu was displayed.

Apply for Android Apps certification!

https://www.vskills.in/certification/certified-android-apps-developer

Back to Tutorials

Get industry recognized certification – Contact us

Menu