android BottomSheet how to collapse when clicked outside?

Pradeep Kumar Kushwaha picture Pradeep Kumar Kushwaha · Jul 4, 2016 · Viewed 24.8k times · Source

I have implemented bottomsheet behavior with NestedScrollView. And was wondering if it is possible to hide the bottomsheet view when touched outside.

Answer

Pradeep Kumar Kushwaha picture Pradeep Kumar Kushwaha · Jul 4, 2016

Finally I was able to do this,

Used the following lines of code:

@Override public boolean dispatchTouchEvent(MotionEvent event){
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        if (mBottomSheetBehavior.getState()==BottomSheetBehavior.STATE_EXPANDED) {

            Rect outRect = new Rect();
            bottomSheet.getGlobalVisibleRect(outRect);

            if(!outRect.contains((int)event.getRawX(), (int)event.getRawY()))
                mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
    }

    return super.dispatchTouchEvent(event);
}

Hope it save someone's whole day!