在BottomSheetBehavior之外单击时拦截BottomSheetBehavior之外的单击处理程序

问题描述 投票:0回答:1

我已经找到了在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外部的按钮并禁用该按钮的单击处理程序。)我该怎么办?

android bottom-sheet
1个回答
0
投票

[在调用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)
}
© www.soinside.com 2019 - 2024. All rights reserved.