button back in startDestination with navigation component

You can't, activity has their own toolbars and in your case they have two different NavControllers. So your second activity manage NavUp Button for his fragment and when start Destination fragment comes NavUpButton(Backbutton) disappear because it has no destination left behind. And if you programmatically show NavUp Button on start destination of that (2nd activity) and manage onClick and start first activity that always goes to Start destination of first activity's fragment because it has it's own Nav Controller.

Problem is that Navigation UI not works like that. The better approach is use only one activity with multiple fragments. And use any other approach to solve your problem within the same nav controller.


You can do it by specifying a setFallbackOnNavigateUpListener:

private fun setupToolbar() {
    val navController = findNavController(R.id.nav_host_fragment)

    val appBarConfiguration =
        AppBarConfiguration.Builder()
            .setFallbackOnNavigateUpListener { onNavigateUp() }
            .build()

    dataBinding.toolbar.apply {
        setupWithNavController(navController, appBarConfiguration)
    }
}

And then do whatever you want in the Activity's:

override fun onNavigateUp(): Boolean {
    finish()
    return true
}