Arfmann
Arfmann

Reputation: 734

Android Studio Kotlin - Disable user gestures in BottomSheetDialogFragment

I need to disable user from dragging bottom sheet, but I have no idea on how to do that.

This is my fragment:

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class MyFragment : BottomSheetDialogFragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val main = inflater.inflate(R.layout.fragment_layout, container, false)

       return main
    }

    companion object {
        fun newInstance(): MyFragment = newInstance()
    }
}

This is how I show it:

val test = MyFragment()
test.show(supportFragmentManager, "test")

Upvotes: 0

Views: 406

Answers (1)

Kishan Maurya
Kishan Maurya

Reputation: 3394

You need to override onCreateDialog() and put below code

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog

        dialog.setOnShowListener {
            val bottomSheet = (it as BottomSheetDialog).findViewById<View>(com.google.android.material.R.id.design_bottom_sheet) as FrameLayout?
            val behavior = BottomSheetBehavior.from(bottomSheet!!)
            behavior.state = BottomSheetBehavior.STATE_EXPANDED

            behavior.setBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
                override fun onStateChanged(bottomSheet: View, newState: Int) {
                    if (newState == BottomSheetBehavior.STATE_DRAGGING) {
                        behavior.state = BottomSheetBehavior.STATE_EXPANDED
                    }
                }

                override fun onSlide(bottomSheet: View, slideOffset: Float) {}
            })
        }

        // Do something with your dialog like setContentView() or whatever
        return dialog
    }

or check this link How to disable BottomSheetDialogFragment dragging

Upvotes: 1

Related Questions