You can achieve this by clear
ing the Menu
at first then re-add
ing its MenuItem
s.
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?