Xamarin Android:如何通过代码动态创建Navigation View菜单项分组及ID
Got it, let's break down how to replicate your static XML NavigationView groups programmatically—so you'll end up with the exact same empty groups (grpTest1 and grpTest2) but created at runtime instead of in XML.
1. First, Declare Your Group IDs
Just like how @+id in XML creates a unique ID, you need to define these IDs in a resource file so your code can reference them. Create or edit res/values/ids.xml and add:
<?xml version="1.0" encoding="utf-8"?> <resources> <item name="grpTest1" type="id"/> <item name="grpTest2" type="id"/> </resources>
2. Code to Create Groups in Your Activity/Fragment
Now use the Android Menu API to add the groups directly to your NavigationView's menu. Here's how to do it in Java and Kotlin:
Java Example
// Grab your NavigationView from the layout NavigationView navigationView = findViewById(R.id.your_navigation_view_id); Menu navMenu = navigationView.getMenu(); // Create first group (matches <group android:id="@+id/grpTest1"></group>) MenuGroup grpTest1 = (MenuGroup) navMenu.addGroup( Menu.NONE, // No parent group (we're creating top-level groups) R.id.grpTest1, // The unique ID we defined earlier Menu.NONE, // Order (use this to control where the group appears) "" // Group title (empty since your XML has no title) ); // Create second group (matches <group android:id="@+id/grpTest2"></group>) MenuGroup grpTest2 = (MenuGroup) navMenu.addGroup( Menu.NONE, R.id.grpTest2, Menu.NONE, "" ); // Optional: Add menu items to a group later // For example, add an item to grpTest1: navMenu.add( grpTest1.getId(), // Link this item to grpTest1 Menu.NONE, // Unique item ID (define in ids.xml if needed) Menu.NONE, // Position within the group "Sample Item" // Item text );
Kotlin Example
val navigationView = findViewById<NavigationView>(R.id.your_navigation_view_id) val navMenu = navigationView.menu val grpTest1 = navMenu.addGroup(Menu.NONE, R.id.grpTest1, Menu.NONE, "") as MenuGroup val grpTest2 = navMenu.addGroup(Menu.NONE, R.id.grpTest2, Menu.NONE, "") as MenuGroup // Optional: Add an item to the group navMenu.add(grpTest1.id, Menu.NONE, Menu.NONE, "Sample Item")
Quick Notes
- The
addGroup()method returns aMenuGroupobject, which you can use later to tweak properties like visibility or enabled state. - The
orderparameter (third argument) lets you control where groups appear relative to other menu items/groups. If you need specific positioning, adjust this value.
This setup will behave exactly like your original static XML—you'll have two empty groups with the same IDs, ready to be populated with items dynamically if needed.
内容的提问来源于stack exchange,提问作者Pravin Patil

