When trying to use the back button of a dialog fragment
I'm curious as to the difference between using onBackPressed() (or onBackPressedCallBack) and onCancel().
I tried to define the data forwarding event of the back key using onBackPressedCallback() and OnBackPressedDispatcher() in the dialog fragment, but it didn't work.
In the end, I passed the data using onCancel().
Why doesn't the back key with onBackPressed() work?
UPDATED
public class WritingCommentDialogFragment extends DialogFragment {
OnBackPressedCallback callback;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return view;
}
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.setCanceledOnTouchOutside(false);
return dialog;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
callback = new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
Toast.makeText(getContext(), "TEST", Toast.LENGTH_SHORT).show();
}
};
requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);
}
}