I'm trying to disable the back button for all screens in my app (Fragments and Activites).
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;
}