OnBackPressedCallback not trigger after screen rotation

Viewed 540

i have follow (https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher)

@Override
public void onAttach(@NonNull final Context context)
{
    super.onAttach(context);
    final OnBackPressedCallback _fragmentOnBackPressedCallback = new OnBackPressedCallback(true)
    {
        @Override
        public void handleOnBackPressed()
        {
            sendData();
        }
    };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, _fragmentOnBackPressedCallback);
}

in my activity in onCreate i do

final OnBackPressedCallback callback = new OnBackPressedCallback(true)
        {
            @Override
            public void handleOnBackPressed()
            {
                if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
                    getSupportFragmentManager().popBackStack();
                else
                    navigateUpInMenu();
            }
        };
        getOnBackPressedDispatcher().addCallback(this, callback);
}

It work great, but when i rotate the phone the sendData method is not called. Do i miss something ? I'm using androidx.activity:activity:1.1.0

2 Answers

I think you should have OnBackPressedCallback registered as long as View or viewLifecycleOwner of Fragment is alive.

viewLifeCycleOwner lives between onCreateView and onDestroyView so you don't need to unregister callback either to prevent any potential memory leak due to lifecycle of Fragment.

I use

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner, callback)

}

    val callback = object : OnBackPressedCallback(false) {

        override fun handleOnBackPressed() {
             sendData()
       }
   }

With a callBack property you can also enable or disable based on some conditions or lifecycle events.

override fun onResume() {
    super.onResume()
    callback.isEnabled = true
}

override fun onPause() {
    super.onPause()
    callback.isEnabled = false
}

According to official documentation

onAttach(Activity) called once the fragment is associated with its activity.

A good thing to do is to move the onBackPressedDispatcher in the onViewCreated

Related