2

I am trying to implement a BottomSheet using BottomSheetFragment which collapses when user clicks outside the dialog. I have tried overriding onCancel but to set the state to STATE_COLLAPSED, but it does not work - the BottomSheet disappears when clicked outside. Also have setHideable(false). So, I am expecting the bottomsheet to collapse when the user clicks outside, which is not the case. How can I achieve this?

public class MyBottomSheet extends BottomSheetDialogFragment {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.eazyotp_auto_capture_bottomsheet, container, false);
    }

    @Override
    public void onCancel(@NonNull DialogInterface dialog) {
        super.onCancel(dialog);
        behavior.setState(BottomSheetBehavior.STATE_COLLAPSED); // does not work

    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        behavior = getDialog().getBehavior();
        behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        behavior.setHideable(false);
        behavior.setPeekHeight(70); 
       // following works well - even when user drags the bottomsheet it gets into collapsed state.
        imageView.setOnClickListener(v -> {
        if(behavior.getState() == BottomSheetBehavior.STATE_EXPANDED)
            behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        else
            behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    });

    }
}

Also when I do setCancelable(false), I cant use collapse/expand on the imageView

Sairaj Sawant
  • 1,842
  • 1
  • 12
  • 16
  • So you want to disappear dialog when user click outside? Is [this](https://stackoverflow.com/a/52629439/1318946) your answer? – Pratik Butani Mar 09 '20 at 13:37

1 Answers1

1

add this in activityCreted getDialog().setCanceledOnTouchOutside(true)

Amit pandey
  • 1,149
  • 1
  • 4
  • 15