[Android] OnBackPressedCallBack() does not work in the dialog fragment.

Asked 2 years ago, Updated 2 years ago, 28 views

After displaying the dialog fragment window, enter various data and click Back I'm trying to save the data by sending it to an activity To test whether onBackPressedCallback works well, I'm going to send a toast message first There's no response.

I heard that using onBackPress() should take good care of the life cycle, so I'm going to use onBackPressedCallback() and OnBackPressedDispatcher() these days, but it doesn't work.ㅜ<

May I know what it is for?

public class WritingCommentDialogFragment extends DialogFragment implements CommentModel.EditInputListener {
    OnBackPressedCallback callback;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_writing_comment_dialog, container, false);
        bindViews(view);
        addCommentItem();
        Toast.makeText(getContext(), "onCreateView()", Toast.LENGTH_SHORT).show();
        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);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callback.remove();
    }

    @Override
    public void onResume() {
        super.onResume();
        setDialogSize();
    }
}
routineAdapter.setOnAddRoutineClickListener(new RoutineAdapter.OnRoutineAddClickListener() {
            @Override
            public void OnAddRoutineClick() {
                WorkoutListDialogFragment routineDialog = new WorkoutListDialogFragment();
                routineDialog.show(getSupportFragmentManager(), "RoutineListDialog");
            }
        });

android java

2022-09-20 17:41

1 Answers

In the case of DialogFragment, it occurs above window of Activity, so the backup key event is intercepted at the top. It's not an Android bug, it's normal. If you want to pass the result value in DialogFragment, it would be better to create a separate listener and use methods such as onDismiss() or onCancel().

This is a note link. https://issuetracker.google.com/issues/149173280


2022-09-20 17:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.