Pages

Android Contextual Action Bar

Context menu let's you can show the user a set of actions that can be performed in that context.

There are two types of contextual action menu. A popup menu and an action bar. Here you can find out how to create context menu in action bar.


Step 1: create menu resource for your context menu

res/menu/context_menu.xml
1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/context_menu_item" android:title="Menu Item" />
</menu>

MainActivity.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class MainActivity extends AppCompatActivity {
    // Step 2: declare this variable
    ActionMode actionMode;

    // skipped other implementation details


    // Step 3: implement ActionMode Callback
    private ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // here load your menu from the xml file
            MenuInflater inflater = mode.getMenuInflater();
            inflater.inflate(R.menu.context_menu_main, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // this will be called only when action bar is invalidate
            // know this that this method won't be called after onCreateMethod()
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.context_menu_item:
                    // handle menu event
                    break;
                default:
                    return false;
            }

            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            // will be called when user exits action menu by clicking on <- (back) button
            // or if exited programmitically through actionMode.finish()
        }
    };

    // Step 4: calling this method will show the contextual action bar
    public void showContextMenu () {
        actionMode = startActionMode(actionModeCallback);
    }
}