Android Open Menu from a button

2019-04-08 05:14发布

问题:

Is there a way for a button to call a submenu?

I currently have a menu where if they select one of the options it opens a submenu, however I want to be able to start the submenu from the Button widget instead of the Menu object.

Thanks!

回答1:

I am not necessarily recommending this, but I was able to call the submenu programatically. First, in the override of onCreateOptionsMenu I stored the menu parameter to a private Menu variable in the activity. Then, I was able to simply do the following from the onClick():

MyActivity.this.openOptionsMenu(); // activity's onCreateOptionsMenu gets called
optionsMenu.performIdentifierAction(R.id.miSubMenu1, 0);

In a particular instance this saved me a lot of time since the submenu was built months before the request to have an additional button go directly to the submenu.



回答2:

You can use the openOptionsMenu() on the activity to programmatically open the activity from the button, but you can't do the same for a submenu.



回答3:

I'm not sure if thats possible. One option would be to use a dialog as the sub menu, so that you can open it from either location.