Navigate to fragment on FAB click (Navigation Architecture Components)

Ran into this issue today and I found out that there is a simple and elegant solution for it.

val navController = findNavController(R.id.navHostFragment)

fabAdd.setOnClickListener {
   navController.navigate(R.id.yourFragment)
}  

This takes care of the navigation. Then you must control the visibility of your BottomAppBar inside your Activity.


You could have your BottomAppBar in MainActivity and access your FloatingActionButton in your fragment as follows

activity?.fab?.setOnClickListener { 
    /*...*/
    findNavController().navigate(R.id.action_firstFragment_to_secondFragment, mDataBundle)
}

You could hide the BottomAppBar from another activity as follows

(activity as AppCompatActivity).supportActionBar?.hide()

Make sure you .show() the BottomAppBar while returning to previous fragment