Search code examples
androidandroid-layoutandroid-fragmentsandroid-activitykotlin

Navigate to fragment on FAB click (Navigation Architecture Components)


I have no idea how to, using the new navigation architecture component, navigate from my main screen (with a FloatingActionButton attatched to a BottomAppBar) to another screen without the app bar.

When I click the fab I want my next screen (fragment?) to slide in from the right. The problem is where do I put my BottomAppBar? If I put it in my MainActivity then I have the issue of the FloatingActionButton not having a NavController set. I also cannot put my BottomAppBar in my Fragment. I am at a loss.


Solution

  • 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.