在导航视图中以编程方式将项目添加到菜单组 [英] Add items to menu group programatically in navigation view
问题描述
我试图务实地将菜单项添加到菜单组,但我发现没有办法做到这一点.我正在使用导航视图并添加了下面提到的菜单:
I am trying to add menu items to menu group pragmatically but I found no way to do that. I am using Navigation View and added below mentioned menu:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/nav_lang_currency"
android:title="" />
<item
android:id="@+id/nav_home"
android:title="" />
<group android:id="@+id/nav_refer" />
<item
android:id="@+id/nav_setting"
android:title="" />
<item
android:id="@+id/nav_about_us"
android:title="" />
<item
android:id="@+id/nav_logout"
android:title="" />
</menu>
一切看起来都很好.
我只想在运行时根据业务需求在 nav_refer
组中添加多个菜单项,但我找不到这样做的方法.
I just want to add multiple menu items in nav_refer
group at run-time as per business requirement but I found no way to do that.
我在 SO 上搜索了解决方案,但没有找到办法.
I searched solution on SO but found no way to do that.
请建议我如何在运行时在组中添加多个菜单项.
Kindly suggest me how to add multiple menu items in group at run-time.
推荐答案
要将菜单添加到特定组,请调用此方法 Menu.add(int groupId, int itemId, int order, CharSequence title)>
To add menu to a particular group, call this method Menu.add(int groupId, int itemId, int order, CharSequence title)
Menu menu = navigationView.getMenu();
menu.add(R.id.nav_refer, 123, Menu.NONE, "Title1");
menu.add(R.id.nav_refer, 124, Menu.NONE, "Title2");
menu.add(R.id.nav_refer, 125, Menu.NONE, "Title3");
重要:最初如果您有空组,那么新添加的项目会出现在底部,要解决这个问题,您需要提及组的订单.为所有组添加一个属性 android:orderInCategory="101"
Important : Initially if you have empty group then newly added items will appear in bottom, to solve this you need to mention orders for groups. add a attribute for all your groups android:orderInCategory="101"
这篇关于在导航视图中以编程方式将项目添加到菜单组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!