Reputation: 1573
I have DrawerLayout and NavigationView. There are two fragments which are changed when I click on item in navigation drawer and that works well:
<fragment
android:id="@+id/nav_settings"
android:label="@string/menu_settings"
tools:layout="@layout/fragment_settings" />
<fragment
android:id="@+id/nav_themes"
android:label="@string/menu_themes"
tools:layout="@layout/fragment_themes" />
The problem is that I have several other items in the drawer menu that are not Fragments and I can not make them clickable:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group
android:id="@+id/group_1"
android:checkableBehavior="single">
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_keyboard_settings"
android:title="@string/menu_settings" />
<item
android:id="@+id/nav_themes"
android:icon="@drawable/ic_theme"
android:title="@string/menu_themes" />
</group>
<group android:id="@+id/group_2">
<item
android:id="@+id/nav_developer_page"
android:icon="@drawable/ic_developer_page"
android:title="@string/menu_developer_page" />
<item
android:id="@+id/nav_privacy_policy"
android:icon="@drawable/ic_privacy_policy"
android:title="@string/menu_privacy_policy" />
</group>
</menu>
Here is the code:
setSupportActionBar(toolbar)
toggle = object : ActionBarDrawerToggle(this, drawer_layout, toolbar, 0, 0) {
override fun onDrawerClosed(drawerView: View) {
super.onDrawerClosed(drawerView)
syncState()
}
override fun onDrawerOpened(drawerView: View) {
super.onDrawerOpened(drawerView)
syncState()
}
}
toggle.syncState()
drawer_layout.addDrawerListener(toggle)
val navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(setOf(
R.id.nav_settings, R.id.nav_themes, R.id.nav_developer_page), drawer_layout)
nav_view.setupWithNavController(navController)
toggle.syncState()
When I set NavigationItemSelectedListener it breaks navigation for Fragments.
How can I make those two items clickable and call a function?
Upvotes: 1
Views: 1253
Reputation: 525
The solution is to get the menu item from the navigation view and set a click listener:
val signoutMenuItem = binding.nvNavigationDrawerNavigationView.menu.findItem(id.navigation_drawer_menu_sign_out)
signoutMenuItem.setOnMenuItemClickListener {
navigationDrawerMainActivityViewModel.signOut()
true
}
and do not include non-fragment items in AppBarConfiguration
:
appBarConfiguration = AppBarConfiguration(
setOf(
id.drawerFragmentX,
id.drawerFragmentY,
//id.navigation_drawer_menu_sign_out <- Do NOT include
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
This solution is identical to https://stackoverflow.com/a/59451345/5189200.
Xavi
Upvotes: 2