'onBackPressed() is not working in Fragment
I want to completely it goes to the home of the phone when i back, but onBackPressed() is not working.
My Page is a fragment btw.
Solution 1:[1]
Use getActivity().onBackPressed(); in your fragment it will execute onBackPressed() of your parent activity
to be more accurate
Activity activity = getActivity();
if (activity != null) {
activity.onBackPressed();}
edit: use requireActivity() for avoiding nullpointer
requireActivity().onBackPressed();
Solution 2:[2]
onBackPressed callback is handled by your parent activity. So you can override callback on parent activity
XyzActivity.java:
@Override
public void onBackPressed() {
handleBackPress();
}
public void handleBackPress() {
Fragment visibleFragment = getSupportFragmentManager().findFragmentById(R.id.fragmentFrameLayout);
if (visibleFragment == null) {
return;
}else if (visibleFragment instanceof PreviewFragment) {
CommonFunctions.showDialogActionable(this, "Confirm", "Are you sure you want to exit?",
"Yes", (dialogInterface, i) -> {
finish();
}, "No", null, "", null, true);
return;
}else
finish();
super.onBackPressed();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Akhilesh |
