Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get MenuItem position in the listener using the new NavigationView

The topic says it all. How should I go about retrieving the item position on the onClick listener using NavigationView? Also, why is there no getHeader method? Lastly I am doing everything programmatically, but the header is still clickable. Any thoughts?

Thanks!

like image 393
Fhl Avatar asked Aug 07 '15 07:08

Fhl


1 Answers

You can just take its order if you specify the "android:orderInCategory" attribute for menu items:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:orderInCategory="0"
        android:title="@string/news" />
    <item
        android:orderInCategory="1"
        android:title="@string/search" />
</menu>
val navigationView = findViewById<NavigationView>(R.id.navigation)

navigationView.setNavigationItemSelectedListener { menuItem ->
    val menuItemOrder = menuItem.order

    true
}

Or, use this in case you don't want to specify orders by hand:

val navigationView = findViewById<NavigationView>(R.id.navigation)

navigationView.setNavigationItemSelectedListener { menuItem ->
    val menuItemIndex = bottomNavigation.menu.children.indexOf(menuItem)

    true
}
like image 69
Igor Kharakhordin Avatar answered Sep 29 '22 13:09

Igor Kharakhordin