来自模态 BottomSheetFragment 的 BottomSheetCallback

mar*_*tom 5 android kotlin bottom-sheet

如果我使用 Modal BottomSheetFragment 如何添加 BottomSheetBehavior ?

var bottomSheetBehaviorCallback = 
    object : BottomSheetBehavior.BottomSheetCallback() {

        override fun onSlide(bottomSheet: View, slideOffset: Float) {
            Log.d(Constants.LOG_INFO, "on slide")
        }

        override fun onStateChanged(bottomSheet: View, newState: Int) {
            Log.d(Constants.LOG_INFO, "onStateChanged")
        }
    }

val detailView = StationDetailFragment.newInstance(selectedStationID, "")
detailView.show(fragmentManager, "detailView")
Run Code Online (Sandbox Code Playgroud)

此时视图尚未创建

我更改了代码并添加了覆盖 setupDialog 。但我仍然没有得到回调工作

override fun setupDialog(dialog: Dialog?, style: Int) {

    val contentView = View.inflate(context, R.layout.fragment_station_detail, null)
    dialog!!.setContentView(contentView)

    val layoutParams = (contentView.parent as View).layoutParams as CoordinatorLayout.LayoutParams

    val behavior = layoutParams.behavior

    if (behavior != null && behavior is BottomSheetBehavior<*>) {
      behavior.setBottomSheetCallback(mBottomSheetBehaviorCallback)
    }
}
Run Code Online (Sandbox Code Playgroud)

mar*_*tom 5

谢谢你们!对我来说最好的解决方案是将我的 BottomSheet 作为持久底部表添加到 Activity_main.xml

以下解释帮助我在 Android 上使用 Bottom Sheet

最后我用kotlin找到了Modal Bottomsheet的解决方案

  override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {


    val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog

    dialog.setOnShowListener { dialog ->
        val d = dialog as BottomSheetDialog

        val bottomSheet = d.findViewById<View>(android.support.design.R.id.design_bottom_sheet) as FrameLayout?
        bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet!!)
        bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
    }

    return dialog

}
Run Code Online (Sandbox Code Playgroud)

我的问题是我尝试使用我的协调器布局。但对于 Modal BottomSheet 你必须使用 android.support.design.R.id.design_bottom_sheet