I am adding footer-view in navigation drawer using following code -
Dear this worked for me the item R.id.nav_logout i needed finish activity and not instance a fragment:
private lateinit var appBarConfiguration: AppBarConfiguration
var drawerLayout: DrawerLayout? = null
var navView: NavigationView? = null
var navController: NavController? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_customer_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
val fab: FloatingActionButton = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
drawerLayout = findViewById(R.id.drawer_layout)
navView = findViewById(R.id.nav_view)
navController = findNavController(R.id.nav_host_fragment)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(setOf(
R.id.nav_home, R.id.nav_service_requests), drawerLayout)
setupActionBarWithNavController(navController!!, appBarConfiguration)
navView!!.setupWithNavController(navController!!)
navView!!.setNavigationItemSelectedListener(this)
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
override fun onNavigationItemSelected(menuItem: MenuItem): Boolean {
menuItem.isChecked = true
drawerLayout!!.closeDrawers()
when (menuItem.itemId) {
R.id.nav_logout -> {
Prefs.putBoolean("flagLogin", false)
val intent = Intent(this@CustomerMainActivity, LoginActivity::class.java)
startActivity(intent)
finish()
return true
}
}
if( navController!!.currentDestination!!.id != menuItem.itemId)
navController!!.navigate(menuItem.itemId)
return true
}
You attach setNavigationItemSelectedListener
with NavigationView
which will override during default configuration of setupWithNavController
. So attach your listener after configuring default settings. Check below code.
nv_top.setupWithNavController(navController)
drawer_menu_body.setNavigationItemSelectedListener(this)
Update: To work with default navigation you have to handle like below:
override fun onNavigationItemSelected(menu: MenuItem): Boolean {
val handled = NavigationUI.onNavDestinationSelected(menu, navController)
if (!handled) {
// handle other navigation other than default
}
drawer_layout.closeDrawer(GravityCompat.START)
return handled
}