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
I had the same issue, and got it resolved with help from some hints above. The problem for me was that I was registering onBackPressedDispatcher both from my Fragments and from my MainActivity.
Before the recent updates to Android, I was using onBackPressed() in my MainActivity to hide a drawer before exiting the app, and onBackPressedDispatcher in my Fragments to ask the user for confirmation before navigating back. This approach worked fine. Now, onBackPressed() in Activities is deprecated and onBackPressedDispatcher is recommended to be used instead. This also worked fine, until you rotate the display and suddenly the Fragment back press gets ignored and the MainActivity back press code gets executed instead. I don't know if it's a bug or not, but I will avoid using it.
I've fixed the issue by moving the onBackPressedDispatcher code from my MainActivity into the first "Main" Fragment. This way, back presses are only controlled by Fragments, which in my case means that only one element at a time is responsible for controlling the back press behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With