Search code examples
androidkotlinandroid-lifecycle

Using androix backButtonPressedCallback


I need to implement a custom onBackButtonPress method for Fragments. example in LogoutFragment, after logout is handled. user cannot go backStack but a message is shown like press again to exist and is exited. I used this solution. But is not working. Then I saw this Android Doc with onBackPressedDispatcher callback method CODE BELOW. I guess this will work. I added dependencies, but how to implement this in a different fragments, with only 1 activity and fragment container. Kotlin version.

    class LogoutFragment : DaggerFragment() {

       override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)           

                val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {

                    ...
                }

               ...
        }
        ...
    }

Solution

    1. onBackPressedDispatcher gives an opportunity to handle back press differently in every fragment. Hence you may have to give this piece of code in every fragment.

    In the fragment:

    var doubleBackToExitPressedOnce = false
    
     override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        requireActivity().onBackPressedDispatcher.addCallback(this, callback)
     }
    
     val callback = object : OnBackPressedCallback(true ) {
        override fun handleOnBackPressed() {
           if (doubleBackToExitPressedOnce)
              requireActivity().finish()
           Toast.makeText(requireContext(), "Press again to go back", 
              Toast.LENGTH_LONG).show()
           doubleBackToExitPressedOnce = true
        }
     }
    
    1. If you want to handle back presses of all fragments in one place, you can do so by manipulating the doBack() method in your reference: How to implement onBackPressed() in Fragments?

    //pseudocode

       fun doBack()
       {
    
         //find the fragment
         val fragment = supportFragmentManager.findFragmentByTag(
         //your fragment tag 
         )
    
         if(fragment is FragmentA)
         {
    
           //do something
         }
         else if(fragment is FragmentB)
         {
    
           //do something else
         }
    
         else
         {
            activity.getSupportFragmentManager().popBackStack(null, 
            FragmentManager.POP_BACK_STACK_INCLUSIVE);
         }
    
       }