以编程方式更改菜单项顺序 Android Java

Change Menu Items Order programmatically Android Java

基本上我有一个 android 弹出菜单,当任何菜单项被点击时,它应该重新调整菜单项的顺序

<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>

您可以通过 clearing the Menu at first then re-addMenuItem 来实现。

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);
    }
}

请注意,菜单 XML 中没有设置 android:orderInCategory 的编程(非构建时间或动态)方法。参见: