我已经找到了在BottomSheetBehavior
外部单击时折叠here的解决方案。该链接的代码如下(转换为Kotlin):
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
var returnValue: Boolean = super.dispatchTouchEvent(event)
if (event.action == MotionEvent.ACTION_DOWN) {
if (mBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) {
val outRect = Rect()
val fragment = supportFragmentManager.findFragmentById(R.id.queueChoicePanel)
fragment?.view?.getGlobalVisibleRect(outRect)
if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
mBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
}
}
}
return returnValue
}
但是,缺少的是,当我在外部单击并单击可单击区域时,也会触发该可单击区域的单击处理程序。我想要这样,当BottomSheetBehavior
处于展开状态(即BottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED
)并且单击外部时,我折叠BottomSheetBehavior
并拦截了点击,因此它不会进一步触发BottomSheetBehavior
外部的点击处理程序(例如,单击BottomSheetBehavior
外部的按钮并禁用该按钮的单击处理程序。)我该怎么办?
[在调用super之前先做检查,然后在折叠工作表的情况下添加return true
,它应该消耗touch事件,因此下面的视图不会收到它。
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
if (mBottomSheetBehavior?.state == BottomSheetBehavior.STATE_EXPANDED) {
val outRect = Rect()
val fragment = supportFragmentManager.findFragmentById(R.id.queueChoicePanel)
fragment?.view?.getGlobalVisibleRect(outRect)
if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
mBottomSheetBehavior?.state = BottomSheetBehavior.STATE_COLLAPSED
return true
}
}
}
return super.dispatchTouchEvent(event)
}