0

I'm trying to disable the back button for all screens in my app (Fragments and Activites).

enter image description here

I'm able to successfully disable the back button in my MainActivity by simply removing the super method in .onBackPressed()

@Override
    public void onBackPressed() {
        //Disabled
}

The back button no longer works on this Activity screen.

However, once I have inflated a DialogFragment, the back button seems to work again, and once I click on it, it dismisses the inflated DialogFragment.

I am not sure why it's doing this, but after searching google I came accross this onBackPressedDispatcher

https://developer.android.com/reference/androidx/activity/OnBackPressedDispatcher

I have tried the method in that doc which says to place this block of code inside my inflated DialogFragment

 @Nullable
    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater,
            @Nullable ViewGroup container,
            @Nullable Bundle savedInstanceState
    ) {
        View view = inflater.inflate(R.layout.dialog_fragment, container, false);
        
        OnBackPressedCallback callback = new OnBackPressedCallback(
                false
        ) {
            @Override
            public void handleOnBackPressed() {

            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(
                this,
                callback);

        return view;
    }

However the back button is still working. I am not sure what I'm doing incorrectly.

How can I disable the Android Back Button inside my DialogFragment?

Edit:___________________________________________

Calling dialog.setCancelable() does not work

@NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        final Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.setCancelable(false);
        return dialog;
    }
DIRTY DAVE
  • 2,523
  • 2
  • 20
  • 83
  • 1
    `DialogFragment` has `onCreateDialog` method in which you can call `setCancelable(false)` on that dialog .. That should work i think.. – ADM Dec 12 '22 at 13:59
  • calling ```dialog.setCancelable(false)``` does not work. But calling ```setCancelable(false)``` works!! Could you make a quick answer below so I can mark yours correct? Thanks for your help!! – DIRTY DAVE Dec 12 '22 at 21:15

0 Answers0