Kotlin OnTouchListener被调用,但它不会覆盖performClick

问题描述 投票:7回答:4

如何覆盖Kotlin中的performClick以避免警告?

next.setOnTouchListener(View.OnTouchListener { view, motionEvent ->
        when (motionEvent.action){
            MotionEvent.ACTION_DOWN -> {
                val icon: Drawable = ContextCompat.getDrawable(activity.applicationContext, R.drawable.layer_bt_next)
                icon.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
                next.setImageDrawable(icon)
            }
            MotionEvent.ACTION_UP -> {
                //view.performClick()
                next.setImageResource(R.drawable.layer_bt_next)
            }
        }
        return@OnTouchListener true
    })

view.performClick不起作用。

android kotlin ontouchlistener
4个回答
13
投票

试试这种方式:

 next.setOnTouchListener(object : View.OnTouchListener {
        override fun onTouch(v: View?, event: MotionEvent?): Boolean {
            when (event?.action) {
                MotionEvent.ACTION_DOWN -> //Do Something
            }

            return v?.onTouchEvent(event) ?: true
        }
    })

4
投票

好的,我通过覆盖OnTouch监听器解决了我自己的问题。

override fun onTouch(view: View, motionEvent: MotionEvent): Boolean {
    when (view) {
        next -> {
            Log.d("next", "yeyy")
            when (motionEvent.action){
                MotionEvent.ACTION_DOWN -> {
                    val icon: Drawable = ContextCompat.getDrawable(activity.applicationContext, R.drawable.layer_bt_next)
                    icon.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
                    next.setImageDrawable(icon)
                }
                MotionEvent.ACTION_UP -> {
                    view.performClick()
                    next.setImageResource(R.drawable.layer_bt_next)
                }
            }
        }
        previous -> {
            //ingredients here XD
        }
    }
    return true
}

通过这种方式,我可以调用单个onTouch并将其实现为多个按钮,也可以使用onClick by:

view.performClick()

别忘了实施:

View.OnTouchListener

并设置监听器:

next.setOnTouchListener(this)
previous.setOnTouchListener(this)

4
投票

我不认为您的解决方案实际上会解决警告提出的问题。警告声明某些辅助功能使用performClick()激活按钮。如果你查看View类,performClick()函数直接调用onClickListener,这意味着onTouchListener中的代码将不会被执行(next.setImageResource(R.drawable.layer_bt_next))这些可访问性函数,因为视图永远不会被物理触及,因此你的onTouch代码赢了'跑。您必须执行以下任一操作之一:

  1. 将您正在设置onTouchListener的视图子类化,并覆盖performClick以执行代码,或者
  2. 在执行代码的视图上设置onClickListener

您可以在onTouchListener类中实现onClickListener并从onClick()(现在有onTouchListener)手动调用view.performClick(),然后将可执行代码移动到onClick覆盖。你还必须在你的观点上设置两个onTouchListeneronClickListener


1
投票

我不确定这是你看到的同一个问题,但是因为我发现这个页面正在搜索我的问题,我想我会添加我的经验来帮助别人:)

在我的情况下,正在生成警告,因为可空视图可能是Void类型。调用以下内容:

nullableView?.setOnTouchListener(this)

产生了错误:

Custom view Void has setOnTouchListener called on it but does not override performClick

在这种情况下,在设置监听器之前执行空检查并转换为View,因为View将覆盖performClick

if (nullableView != null) (nullableView as View).setOnTouchListener(this)
© www.soinside.com 2019 - 2024. All rights reserved.