Create context menu on menu item click

1.7k views Asked by At

I am in strange situation and I tried to search everywhere but i didn't find anything useful. May be I am following bad design. But here is my situation:

I have AppBar in my app and I have added ActionButton on app bar which we do normally. Now I want to display context menu when user clicks on any of the action button of app bar.

For example: If I have setting button on app bar and if user clicks on that button then I want to display context menu having multiple options. I know how to create context menu and handle context menu item clicks but i don't know how to transfer control from action button click which lead to display ContextMenu.

Here is my code:

//inflating context menu which will display when user clicks app bar button example like setting

    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu_sort, menu);
    }

//handling context menu item clicks
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        return super.onContextItemSelected(item);
    }

But I am not sure how to handle app bar button clicks which will display context menu:

//Below code is to handle app bar item clicks

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        //handling the menu clicks on menu.xml
        switch (id){
//on below action_add click i want to display context menu
            case R.id.action_add:
//not sure what to code here
                break;
}

Thanks for your help

1

There are 1 answers

0
beeb On

If i am understanding you right you want to show a submenu? Then you need to add a menu tag in your R.menu.context_menu_sort.

Like this:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/file"
          android:title="@string/file" >
        <!-- "file" submenu -->
        <menu>
            <item android:id="@+id/create_new"
                  android:title="@string/create_new" />
            <item android:id="@+id/open"
                  android:title="@string/open" />
        </menu>
    </item>
</menu>

For more informations see https://developer.android.com/guide/topics/ui/menus.html