-1

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.

Jam
  • 91
  • 12

2 Answers2

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();
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