Search code examples
androidandroid-fragmentsandroid-bottomsheetdialogbottomsheetdialogfragment

How can a BottomSheetDialogFragment communicate with its host fragment?


I have a button in my fragment which opens a BottomSheetDialogFragment. I want to notify the host fragment if the user selected an item on the BottomSheetDialogFragment. In order to achieve this, I have made an interface in my BottomSheetDialogFragment. However, that interface only communicates with the host activity, not the fragment. How can I send the information from the dialog to the fragment?

This is my interface:

public interface BottomSheetListener {
        void onButtonClicked(int index);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            mListener = (BottomSheetListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement BottomSheetListener");
        }
    }

Solution

  • getParentFragment will return the parent fragment, if the current fragment is attached to a fragment else it will return null if it is attached directly to an Activity

    @Override
        public void onAttach(@NonNull Context context) {
            super.onAttach(context);
            try {
                mListener = (BottomSheetListener) getParentFragment();
            } catch (ClassCastException e) {
                throw new ClassCastException(context.toString() + " must implement BottomSheetListener");
            }
        }