Linghui
Linghui

Reputation: 151

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
}                

Upvotes: 5

Views: 11512

Answers (2)

ductran
ductran

Reputation: 10203

You should sort items when you add like this:

     menu.add (int groupId, int itemId, int order, CharSequence title)

See reference

Upvotes: 2

Roman Nurik
Roman Nurik

Reputation: 29745

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.

Upvotes: 9

Related Questions