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

Linghui picture Linghui · Feb 9, 2012 · Viewed 10.4k times · Source

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
}                

Answer

Roman Nurik picture Roman Nurik · Feb 9, 2012

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.