简体   繁体   中英

Open a contextual menu bar upon menu click

I'm wondering if there is a way to open a contextual menu bar upon click on the phones menu button in Android. I create a contextual menu bar according to this basic tutorial: tutorial contextual menu bar

And I have now the following in my Activity:

mCallback = new Callback(){

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch(item.getItemId()){
        case 1:
            Toast.makeText(getBaseContext(), "Selected Action1 " + postId, Toast.LENGTH_SHORT).show();
            //mode.finish();    // Automatically exists the action mode, when the user selects this action

            break;
        case 2:
            Toast.makeText(getBaseContext(), "Selected Action2 "  + postId, Toast.LENGTH_SHORT).show();
            //mode.finish();    // Automatically exists the action mode, when the user selects this action
            break;
        case 3:
            Toast.makeText(getBaseContext(), "Selected Action3 " + postId, Toast.LENGTH_SHORT).show();
            //mode.finish();    // Automatically exists the action mode, when the user selects this action
            break;

        }
        return false;

    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        mode.setTitle("Actions for Post");
        getMenuInflater().inflate(R.menu.context_menu_posts, menu);

        menu.add(1, 1, 1, "Option 1");
        menu.add(1, 2, 2, "Option 2");
        menu.add(1, 3, 3, "Option 3");



        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        mMode = null;

    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

};

But now I want it to "show" when the user clicks the menu button. Before I had this code in a LongclickListener:

if(mMode!=null)
        return false;
    else
        mMode = startActionMode(mCallback);

This worked great for a control in the Activity but is there a way to do this for a menu click? I tried putting the code for the startActionMode in the @Overriden menu methods but I can't get it to open upon click on the menu button.

Thanks in advance!

Sorry for stupid post, I must be more tired than I thought.

Wasn't thinking that it is just to Override the menubutton and add the code there, since I'm not using that before.

This Post solved it for me: Intercept menuclick

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM