Search code examples
javaandroidkotlinnavigation-drawerbottomnavigationview

Bottom Navigation with Drawer Layout | onBackPressed in Fragment


I have an interesting and confusing question.

I have a Drawer Layout that opens from the Bottom Navigation like in the photo

Screens:
enter image description here

In order for Drawer Layout to open from the Bottom Navigation, I used this code:

    bottomNavigationView.setOnItemSelectedListener { item ->
            when (item.itemId) {
                R.id.itemDrawer -> {
                    drawerLayout.openDrawer(GravityCompat.END)
                    return@setOnItemSelectedListener false
                }
                R.id.homeFragment -> navController.navigate(R.id.homeFragment)
                R.id.booksFragment -> navController.navigate(R.id.booksFragment)
                R.id.grammarFragment -> navController.navigate(R.id.grammarFragment)
                R.id.translatorFragment -> navController.navigate(R.id.translatorFragment)
            }
            true
        }

This is what my problem is

When I override listener for Bottom Navigation, in my opinion, the onBackPressed behaviour gets confused default.

I mean that when I click on Home, then another element, then Home again, and so on several times, and I stay on the Home Fragment and click on onBackPressed, then instead of leaving the app, I go back to the fragment where I was before

I think this is not normal for the user

What should I do?

I thought to somehow override onBackPressed for Home Fragment but I don't understand how to do it


Solution

  • You can use onBackPressedDispatcher in your HomeFragment

    private lateinit var onBackPressedCallback: OnBackPressedCallback
    

    and instantiate the implementation and add the callback to activity in onResume()

    override fun onResume() {
        super.onResume()
        onBackPressedCallback = object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    activity?.moveTaskToBack(true)
                    exitProcess(ZERO)
                }
            }
        
        activity?.onBackPressedDispatcher?.addCallback(onBackPressedCallback)
    }
    

    Due to this callback added on activity, then the callback should be removed on leaving HomeFragment

    override fun onPause() {
        onBackPressedCallback.remove()
        super.onPause()
    }