I have an options menu created and filled with several menu items. For some reason the order of the menu items when they are added is not as desired.
To guarantee the menu items are shown in the order we want it to be, a sort step is needed after the creation. But I have searched the android dev documents and found no way of doing this (or just I did not find it).
Is there any workaround to achieve this? Please advise.
Thanks!
Some sample code:
public boolean onCreateOptionsMenu(Menu menu) {
menu.add("menuItem1");
menu.add("menuItem2");
// after this I want to sort the items
ArrayList<MenuItem> list = new ArrayList<MenuItem>();
for(int i = 0; i < menu.size(); i ++) {
list.add(menu.getItem(i));
}
Collections.sort(list, new SampleComparator());
// But then I don't know how to add the sorted list of menu items back
}
The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings." See the section about Creating an Options Menu.
We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application.
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.
You can tweak the final display order of menu items using the android:orderInCategory
attribute or the order
parameter of the Menu.add
method. Other than those, I don't believe there's a way to sort menu items. Additionally, I'd wonder what kind of menu would require this — it may be better to use a different UI element.
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