1

Basically I have an android popup menu, when any menu item is clicked, it should reshuffle the order of the menu items

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/yellow"
        android:title="Yellow"/>
    <item android:id="@+id/red"
        android:title="Red"/>
    <item android:id="@+id/blue"
        android:title="Blue"/>
    <item android:id="@+id/green"
        android:title="Green"/>
</menu>
hata
  • 11,633
  • 6
  • 46
  • 69
techdan
  • 27
  • 4

1 Answers1

0

You can achieve this by clearing the Menu at first then re-adding its MenuItems.

private final List<Integer> colors = Arrays.asList(
    R.id.yellow, R.id.red, R.id.blue, R.id.green
);

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.yellow || id == R.id.red || id == R.id.blue || id == R.id.green) {
        Collections.shuffle(colors);
        // I'm using viewBinding in this sample code.
        // If you don't use viewBinding,
        // you need to get the Menu instance in an appropriate way.
        // I won't explain about viewBinding in this answer
        // because that is another topic.
        Menu menu = mBinding.toolbar.getMenu();
        menu.clear();
        colors.forEach(color -> {
            String title = "";
            if (color == R.id.yellow) {
                title = "Yellow";
            } else if (color == R.id.red) {
                title = "Red";
            } else if (color == R.id.blue) {
                title = "blue";
            } else if (color == R.id.green) {
                title = "Green";
            }
            menu.add(Menu.NONE, color, Menu.NONE, title);
        });
        return true;
    } else {
        return super.onOptionsItemSelected(item);
    }
}

Note that there is no programmatic (non-build time or dynamic) method to set android:orderInCategory in menu XML. See: How to change the order of MenuItems in menu of NavigationView in code?

hata
  • 11,633
  • 6
  • 46
  • 69