Search code examples
androidandroid-toolbarandroid-architecture-navigationandroid-navigation

Android Fragment Navigation Custom Navigation Back Button


I need to navigate a stack of fragments and I am navigating back using the toolbar back button. Can I override the back button pressed to set a custom animation, for example slide out?

Here is the code for the toolbar.

private fun setupToolbar() {
    val appBarConfiguration = AppBarConfiguration(navController.graph, drawer_layout)
    val toolbar = toolbar as Toolbar
    setSupportActionBar(toolbar)
    toolbar.setupWithNavController(navController, appBarConfiguration)
    val ab: ActionBar? = supportActionBar
    ab?.setDisplayShowTitleEnabled(false) // disable the default title element here (for centered title)
    setupSearchQueryListener()
}

Solution

  • In your setup code, one more thing is needed:

        toolbar.setNavigationOnClickListener {
            onBackPressedDispatcher.onBackPressed() 
        }
    

    In your fragments, you could do this:

        protected lateinit var backPressedCallback: OnBackPressedCallback
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
    
            backPressedCallback = requireActivity().onBackPressedDispatcher.addCallback(this) {
                // your code
            }
        }
    

    The above will enable you to intercept back navigation uniformly and execute your code in question (you can even block/unblock it by playing with backPressedCallback.isEnabled flag). The above was tested. Speaking of setting navigation animation, I was only playing with xml defined action based animations:

            <action
                android:id="@+id/toYourDest"
                app:destination="@+id/yourDest"
                app:enterAnim="@anim/your_slide_in_right"
                app:exitAnim="@anim/your_slide_out_left"
                app:popEnterAnim="@anim/your_slide_in_left"
                app:popExitAnim="@anim/your_slide_out_right" />