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!
Go to app > res > right-click > New > Android Resource Directory and give Directory name and Resource type as menu. Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it as popup_menu.
A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.
If you've developed for Android 3.0 and higher, the system calls onCreateOptionsMenu() when starting the activity, in order to show items to the app bar.
The Android System Settings menu allows you to control most aspects of your device—everything from establishing a new Wi-Fi or Bluetooth connection, to installing a third-party onscreen keyboard, to adjusting system sounds and screen brightness.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With