Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 950
Yazan Allahham Avatar asked Oct 30 '22 20:10

Yazan Allahham


1 Answers

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!

like image 128
cylon Avatar answered Nov 15 '22 07:11

cylon