Satty
Satty

Reputation: 65

BottomsheetDialogFragment is not respecting STATE_HIDDEN

I've a peculiar use case where I need to call show() for a BottomSheetDialogFragment and not want it to show on screen until a condition is met. In order to do this I set the following in onCreateDialog()

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
        val behavior = dialog.behavior
        behavior.isHideable = true
        behavior.state = BottomSheetBehavior.STATE_HIDDEN
        behavior.peekHeight = 0
        return dialog
    }

But I see the screen darkened and the bottom sheet hugging the bottom of the screen with 0 height. I can call dialog.hide() in setOnShowListener to get the artifact to hide but this is obviously is causing a screen flickering. Is there a way to make the dialog get created but stay hidden without any changes to the view?

Upvotes: 1

Views: 319

Answers (1)

Zain
Zain

Reputation: 40878

It's too early to set the BottomSheetBehavior state during dialog creation.

In documentaion:

Sets the state of the bottom sheet. The bottom sheet will transition to that state with animation.

So, it assumes that the bottom sheet is already created.

To solve this, it can be transferred to onStart() callback:

override fun onStart() {
    super.onStart()
    val parentLayout =
        (dialog as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)

    parentLayout?.let { bottomSheet ->

        BottomSheetBehavior.from(bottomSheet).apply {
            state = BottomSheetBehavior.STATE_HIDDEN
        }
    }

    dialog!!.window!!.setDimAmount(0f)
}

Upvotes: 1

Related Questions