AndroidManifest.xml
<application
...
android:enableOnBackInvokedCallback="true"
Main Activity
On main activity declare:
// callback on back key pressed
OnBackPressedCallback myBackPressedCallback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
FragmentManager fm = getSupportFragmentManager();
// Pop fragment back stack if possible
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
return;
}
// Log.e("dedetok", "handleOnBackPressed()"); //debug
AlertDialog.Builder myAliertDialog = new AlertDialog.Builder(
MainActivity.this);
myAliertDialog.setTitle(R.string.dialog_title).
setMessage(R.string.dialog_message).
setIcon(android.R.drawable.ic_dialog_alert).
setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// finish() will execute onDestroy()
finish();
}
}).
setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// do nothing
}
}).
show();
}
};
onCreate() in main activity
...
// onbackkeypress
// onBackPressed() deprecated -> OnBackPressedCallback & getOnBackPressedDispatcher()
// dispatcher
OnBackPressedDispatcher myOnbackPressedDispatcher = getOnBackPressedDispatcher();
// add callback to dispatcher
myOnbackPressedDispatcher.addCallback(this, myBackPressedCallback);
...
Fragment
To replace fragment in main activity
Fragment helpFragment = new FragmentHelp();
requireActivity()
.getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, helpFragment)
.addToBackStack("help")
.commit();
addToBackStack("help") is the way android system implement on back pressed
If you have button back on your fragment e.g helpFragment, you need to emulate OnBackPressedDispatcher
requireActivity()
.getOnBackPressedDispatcher()
.onBackPressed();
Activity B
onCreate in activity B
// Inside Activity B's onCreate
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
// This runs when the physical back button OR
// the programmatic onBackPressed() is called.
finish();
}
});
// Inside your Button's onClick (Assuming it's in the Activity)
buttonExit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// This triggers the callback above
getOnBackPressedDispatcher().onBackPressed();
}
});