Yazan Allahham
Yazan Allahham

Reputation: 174

How to change the order of MenuItems in menu of NavigationView in code?

I have a menu in NavigationView that have 7 menu items, some of these menu items should be invisible based on user settings and the remaining visible items should be displayed in different order. the items are already defined in the XML menu layout.

I've googled a lot but nothing related to already defined menu items. most of the solutions was suggesting to create the menu items in code and set the order while creating it.

here is my menu items XML layout:

<group android:checkableBehavior="single">
    <item
        android:id="@+id/Home_menuitem"
        android:title="Home" />
    <item
        android:id="@+id/Register_menuitem"
        android:title="Register" />
    <item
        android:id="@+id/Login_menuitem"
        android:title="Login" />
    <item
        android:id="@+id/language_menuitem"
        android:title="Language" />
    <item
        android:id="@+id/ContactUs_menuitem"
        android:title="Contact Us" />
    <item
        android:id="@+id/Likes_menuitem"
        android:title="Likes" />
    <item
        android:id="@+id/Subscription_menuitem"
        android:title="Subscription" />
    <item
        android:id="@+id/Logout_menuitem"
        android:title="Logout" />
</group>

say I want to change the order in Code (NOT in XML) to make "Likes_menuitem" to be displayed above "Home_menuitem"

Upvotes: 5

Views: 4926

Answers (3)

Daniel
Daniel

Reputation: 2605

If you add items programmatically just change the order of adding items. Even if you change the position of menu inflating it will affect the result order.

menu.add(Menu.NONE, 898, Menu.NONE, "Item title") // <- Will be 1st
inflater.inflate(R.menu.menu_progress_avatar, menu) // <- Will be 2nd

Upvotes: 0

D.J
D.J

Reputation: 1559

You can do this by visible menuitem to true or false.

Upvotes: -1

cylon
cylon

Reputation: 733

I didn't try it but you probably can follow these steps.

  1. Get a reference to the menu first

    navigationView.getMenu()

  2. Add or remove specific items to (from) it with different order to achieve your order.

    add(int groupId, int itemId, int order, CharSequence title)

    removeItem(int id)

More information in the docs!

Upvotes: 3

Related Questions