Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OnBackPressedCallback is being called, but app is not going back

I recently updated my dependencies to include the OnBackPressedCallback change from an interface into an abstract class.

I have set things up according to the new documentation here but I feel like things are not working as they should.

My fragment's OnCreate looks a lot like the documentation:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requireActivity().onBackPressedDispatcher.addCallback(this) {
            backPressed()
    }
}

When I press the back button, the code in backPressed() is run, but nothing more happens.

I have tried calling handleBackPressed() and requireActivity().onBackPressedDispatcher.onBackPressed() and requireActivity().onBackPressed() from inside the callback, but those all cause a StackOverflowError because it seems to run that callback recursively.

There has got to be something really obvious I am missing...

like image 458
Jason Toms Avatar asked Jun 09 '19 16:06

Jason Toms


2 Answers

There has got to be something really obvious I am missing...

You forget to disable your custom callback in you fragment before asking Activity to handle back pressed.

My solutiuon suitable for me:

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

        final OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
               if (/*situation to handle back pressing*/){
                //here handle your backPress in your fragment
                } else {
                   setEnabled(false); //this is important line
                   requireActivity().onBackPressed();
                }
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
    }
like image 54
Анатолий К. Avatar answered Sep 24 '22 14:09

Анатолий К.


When you register an OnBackPressedCallback, you are taking on the responsibility for handling the back button. That means that no other on back pressed behavior is going to occur when you get a callback.

If you're using Navigation, you can use your NavController to pop the back stack:

requireActivity().onBackPressedDispatcher.addCallback(this) {
    backPressed()
    // Now actually go back
    findNavController().popBackStack()
}
like image 33
ianhanniballake Avatar answered Sep 24 '22 14:09

ianhanniballake