[Android] Touch event distribution logic combing and pit avoidance logic (the upper layer set the event monitoring of setOnTouchListener but it didn't work)

background

In the project, I found that activityone of DrawerLayoutthe objects in the topmost layer has set the following code:

 /**
         *  超级白板的整体点击事件
         *  保证topBar在合适的时机出现
         */
        binding.layoutMainDrawer.setOnTouchListener {
    
     _, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
    
    
                val isVisible = binding.layoutTopBar.visibility == View.VISIBLE
                binding.layoutTopBar.visibility = if (isVisible) View.GONE else View.VISIBLE
                if (!isVisible) {
    
    
                    handler.removeCallbacks(hideTopBarRunnable)
                    handler.postDelayed(hideTopBarRunnable, 5000)
                }
            }
            false
        }

TopBarThe function of this code is to display a custom UI component when clicked .

However, it is found that clicking on the super whiteboard (you can understand it as a drawing board component) part of the above code does not trigger. What's going on here?

PS: 超级白板组件是在DrawerLayout内一个自定义的ViewGroup(约束布局)的一部分UI组件

analyze

Firstly, sort out and learn the distribution mechanism of Touch events.
The focus is on the following distribution and processing methods
dispatchTouchEventand dispatchTouchEventmethods andonInterceptTouchEvent
insert image description here

insert image description here
Reference 1 Reference 2

solve

Then according to the analysis idea:
the touch event on the top layer is consumed at the bottom (that is, returns true). Then you have to choose whether to distribute when distributing.
Then I rewrote the distribution logic in the parent layout containing the super whiteboard:

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    
    

        val isBlankBoardShowing = binding.mainBlankSuperboard.visibility == View.VISIBLE
        // 如果是没有权限管理就不用分发到超级白板这里
        if(!ClassRoomManager.me().sharable && !isBlankBoardShowing){
    
    
            return false
        }
        return super.dispatchTouchEvent(ev)
    }

Reference 3

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44002043/article/details/131417528