Android事件冲突解决--悬浮窗拖拽问题,setOnTouchListener和setOnClickListener冲突

最近项目中要做一个音乐播放悬浮按钮的功能,最终实现效果如下:

悬浮窗布局文件就不放了,就是水平LinearLayout里面放几个ImageView。

做的过程当中遇到一个问题,就是悬浮窗是可以任意拖拽的,悬浮窗里面的按钮是可以点击的,比如暂停,下一曲,关闭悬浮窗等。

按常规思路,先给整个悬浮窗setOnTouchListener,然后再给你里面的按钮setOnClickListener,点击运行,结果发现,点击事件是可以响应,拖拽也没问题,但是当手指放在ImageView上拖拽时,onTouchListener事件无法响应。

此时第一感觉就是setOnTouchListener和setOnClickListener冲突了,需要解决一下冲突。无奈自己对Android事件分发消费机制一直都是一知半解的,一般都是出了问题需要解决,第一时间先百度,没有解决方案就只能去研究Android事件分发消费机制了,但是研究完也都是懵懵懂懂的,今天就决定把这个难点彻底消化掉。

主要研究了这篇文章Android事件分发消费机制,然后对照着写了个demo,一一去验证,加深了自己的理解,最后终于解决了我的问题。

先说下解决思路,自定义LinearLayout,当手指处于滑动时,直接拦截事件,交给自己的onTouchEvent处理即可,核心代码如下:

/**
 * @author:Jason
 * @date:2021/8/24 19:49
 * @email:[email protected]
 * @description:可拖拽的LinearLayout,解决子View设置OnClickListener之后无法拖拽的问题
 */
class DraggerbleLinearLayout : LinearLayout {
    constructor(context: Context, attr: AttributeSet) : this(context, attr, 0)
    constructor(context: Context, attr: AttributeSet, defStyleAttr: Int) : this(context, attr, defStyleAttr, 0)
    constructor(context: Context, attr: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attr, defStyleAttr, defStyleRes)

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        when (ev?.action) {
            MotionEvent.ACTION_MOVE -> {
                return true
            }
        }
        return super.onInterceptTouchEvent(ev)
    }
}

很简单,就是在onInterceptTouchEvent里面拦截move事件即可,这里你也可以重写onTouchEvent,在里面实现拖拽功能,但是这样就固定死了,所以我选择在外面setOnTouchListener,需要拖拽功能时才去实现

    /**
     * 创建悬浮窗
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun showWindow() {
        //获取WindowManager
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        val outMetrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(outMetrics)
        var layoutParam = WindowManager.LayoutParams().apply {
            /**
             * 设置type 这里进行了兼容
             */
            type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
            } else {
                WindowManager.LayoutParams.TYPE_PHONE
            }
            format = PixelFormat.RGBA_8888
            flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            //位置大小设置
            width = WRAP_CONTENT
            height = WRAP_CONTENT
            gravity = Gravity.LEFT or Gravity.TOP
            //设置剧中屏幕显示
            x = outMetrics.widthPixels / 2 - width / 2
            y = outMetrics.heightPixels / 2 - height / 2
        }
        //在这里设置触摸监听,以实现拖拽功能
        floatRootView?.setOnTouchListener(ItemViewTouchListener(layoutParam, windowManager))
        // 将悬浮窗控件添加到WindowManager
        windowManager.addView(floatRootView, layoutParam)
        isAdded = true
    }

主要是这行代码

//在这里设置触摸监听,以实现拖拽功能
floatRootView?.setOnTouchListener(ItemViewTouchListener(layoutParam, windowManager))

ItemViewTouchListener.kt文件内容

/**
 * @author:Jason
 * @date: 2021/8/23 19:27
 * @email:[email protected]
 * @description:
 */
class ItemViewTouchListener(val layoutParams: WindowManager.LayoutParams, val windowManager: WindowManager) : View.OnTouchListener {
    private var lastX = 0.0f
    private var lastY = 0.0f
    override fun onTouch(view: View, event: MotionEvent): Boolean {
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                //这里接收不到Down事件,不要在这里写逻辑
            }
            MotionEvent.ACTION_MOVE -> {
                //重写LinearLayout的OnInterceptTouchEvent之后,这里的Down事件会接收不到,所以初始位置需要在Move事件里赋值
                if (lastX == 0.0f || lastY == 0.0f) {
                    lastX = event.rawX
                    lastY = event.rawY
                }
                val nowX: Float = event.rawX
                val nowY: Float = event.rawY
                val movedX: Float = nowX - lastX
                val movedY: Float = nowY - lastY

                layoutParams.apply {
                    x += movedX.toInt()
                    y += movedY.toInt()
                }
                //更新悬浮球控件位置
                windowManager?.updateViewLayout(view, layoutParams)
                lastX = nowX
                lastY = nowY
            }
            MotionEvent.ACTION_UP -> {
                lastX = 0.0f
                lastY = 0.0f
            }
        }
        return true
    }
}

这里有一点需要注意的是,重写了LinearLayout的onInterceptTouchEvent后会导致setOnTouchListener里面的ACTION_DOWN事件接收不到,所以不要在down事件里面写逻辑。然后onTouch一定要返回true,表示要消费事件,否则当拖拽非ImageView区域时会拖不动。

好了,花了一整天,就解决了这个小问题。

猜你喜欢

转载自blog.csdn.net/u013936727/article/details/119898153