We use Android context menu to show list of actions that can be taken against an item. We can show a context menu for any view, but they are most often used for items in a ListView, GridView, or other view collections in which the user can perform direct actions on each item.
There are two type to provide contextual actions:
To register a view for context menu, call registerForContextMenu method :
Once a view register for context menu, system call onCreateContextMenu method. This is the place where you will inflate a menu resource for context menu or add a menu item programatically.
When user select an item of context menu, system call onContextItemSelected method. Here, we can take appropriate action based on context item selection.
To start contextual action bar, we should implements ActionMode.Callback Interface. Once, implementation finished, we can start contextual action bar on any event. In below given example, I am starting CAB on itemClick event of a listView.
In this example, I have taken 2 listView. One listView to show list of days and second listView to show list of students.
When user long press an item of Day listView, showing a floating context menu with 3 actions. When user click an item of student listView, showing Contextual action mode with 3 actions.
Step 1: Create a new project in Android Studio and name it Context Menu.
Step 2: Create a folder menu inside res directory if it is not already present.
Step 3: Open res -> menu and add a new menu resource file with a name context_menu.xml. Now, replace the code of context_menu.xml with the below given code.
Step 4: Open res -> layout -> activity_main.xml and replace its code with below given code.
Step 5: Open MainActivity.java and replace its code with below given code.
Step 6: Open res -> values -> styles.xml and write your custom styling of action code. I just changed, the background of default Contextual action bar.
Step 7:Clean and run your project to see the result.