[英]Change Menu Items Order programmatically Android Java
Basically I have an android popup menu, when any menu item is clicked, it should reshuffle the order of the menu items基本上我有一个 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>
You can achieve this by clear
ing the Menu
at first then re- add
ing its MenuItem
s.您可以通过首先
clear
Menu
然后重新add
其MenuItem
来实现此目的。
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.请注意,在菜单 XML 中没有编程(非构建时间或动态)方法来设置
android:orderInCategory
orderInCategory。 See: How to change the order of MenuItems in menu of NavigationView in code?请参阅:如何在代码中更改 NavigationView 菜单中 MenuItems 的顺序?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.