Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort menu items in the an android app's options menu?

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
}                
like image 291
Linghui Avatar asked Feb 09 '12 02:02

Linghui


People also ask

What is android option menu?

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.

Where do you define the items for a menu in an android application?

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.

How do I open the pop up menu on android?

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.


1 Answers

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.

like image 180
Roman Nurik Avatar answered Oct 03 '22 22:10

Roman Nurik