1

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()
}
6
  • You can do so by overriding onBackPressed in your hosting activity then using an interface as a listener if i understand what you're asking correctly Commented May 12, 2020 at 8:51
  • Hmm. seems like the onBackPressed is only activated when I press the "physical" back button on my phone? Commented May 12, 2020 at 8:56
  • you can create a custom toolbar, register a clickListener with your custom toolbar back button then trigger the interface in your onclick event or just trigger the interface in your current toolbar's back button event. make sense? Commented May 12, 2020 at 9:04
  • Is it possible to use the default toolbar and in some way access the back button anyway? Commented May 12, 2020 at 10:43
  • Try overriding onSupportNavigateUp Commented May 12, 2020 at 11:12

1 Answer 1

2

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" />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.