Search code examples
androidandroid-menuandroid-navigationview

Android - Can't add item to top of navigation view menu


According to the documentation, to add an item to a Menu programmatically you use this.

By doing Menu.add(Menu.NONE, Menu.NONE, 0, "item"); I should be able to add an item to the very top of the menu of my navigation view, but despite this, the newly created item would still be added to the bottom. What could be the problem here?


Solution

  •    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            menu.add(Menu.NONE, Menu.NONE, 1000, "Item First");
            menu.add(Menu.NONE, Menu.NONE, 500, "Item Second");
            menu.add(Menu.NONE, Menu.NONE, 200, "Item Third");
    
            return true;
        }
    // 200 is lowest 500 in middle  and finally 1000 so the order is like below 
    

    enter image description here

    Should work for you!

    Note : If you use both xml and code like below

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            menu.add(Menu.NONE, Menu.NONE, 0, "1000"); //<---- It's 0
            menu.add(Menu.NONE, Menu.NONE, 500, "500");
            menu.add(Menu.NONE, Menu.NONE, 200, "200");
            return true;
        }
    

    and xml :

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
        <item
            android:id="@+id/action_settings"
                                          // <----------not Given
            android:title="5000"
            app:showAsAction="never" />
    
        <item
            android:id="@+id/main_item"
            android:orderInCategory="100"
            android:title="200"/>
    
        <item
            android:id="@+id/teams_item"
            android:orderInCategory="800"
            android:title="800"/>
    </menu>
    

    and if you forget to add orderInCategory to an item like in the 5000 one Then those items go in top giving priority to xml (check the example)

    enter image description here