Выполните следующие действия
1. Свяжите свой NavigationView
с NavigationUI
NavigationUI.setupWithNavController(nav_view, hostFragment.navController)
2. Bind ActionBar
С NavController
NavigationUI.setupActionBarWithNavController(this@NavActivity, hostFragment.navController)
3. Bind ActionBar
и DrawerLayout
С NavController
NavigationUI.setupActionBarWithNavController(this@NavActivity, hostFragment.navController, drawer_layout)
4. переопределить onSupportNavigateUp()
в вашей активности
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(drawer_layout, hostFragment.navController)
|| super.onSupportNavigateUp()
}
Пример:
class NavActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
lateinit var hostFragment: NavHostFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nav)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val toggle = ActionBarDrawerToggle(
this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
nav_view.setNavigationItemSelectedListener(this)
hostFragment = supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
NavigationUI.setupWithNavController(nav_view, hostFragment.navController)
NavigationUI.setupActionBarWithNavController(this@NavActivity, hostFragment.navController)
NavigationUI.setupActionBarWithNavController(this@NavActivity, hostFragment.navController, drawer_layout)
}
override fun onBackPressed() {
if (drawer_layout.isDrawerOpen(GravityCompat.START)) {
drawer_layout.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(drawer_layout, hostFragment.navController) || super.onSupportNavigateUp()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.nav, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
when (item.itemId) {
R.id.action_settings -> return true
else -> return super.onOptionsItemSelected(item)
}
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
}
выход
Фрагмент дома:
Фрагмент второй:
Фрагмент дерева: