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.
Asked
Active
Viewed 1,589 times
-1

Jam
- 91
- 12
-
Hi @Jam , please try this link for the `Fragment` **backPress** functionlity (https://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press) – Ravindra Kushwaha Oct 04 '19 at 05:32
-
Fragment does not have `onBackPressed` callback. – Vladyslav Matviienko Oct 04 '19 at 05:35
2 Answers
3
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();

trinadh thatakula
- 807
- 5
- 18
1
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();
}

Akhilesh
- 25
- 5