如何覆盖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
不起作用。
试试这种方式:
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
}
})
好的,我通过覆盖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)
我不认为您的解决方案实际上会解决警告提出的问题。警告声明某些辅助功能使用performClick()
激活按钮。如果你查看View
类,performClick()
函数直接调用onClickListener
,这意味着onTouchListener
中的代码将不会被执行(next.setImageResource(R.drawable.layer_bt_next)
)这些可访问性函数,因为视图永远不会被物理触及,因此你的onTouch
代码赢了'跑。您必须执行以下任一操作之一:
onTouchListener
的视图子类化,并覆盖performClick
以执行代码,或者onClickListener
。您可以在onTouchListener类中实现onClickListener
并从onClick()
(现在有onTouchListener
)手动调用view.performClick()
,然后将可执行代码移动到onClick
覆盖。你还必须在你的观点上设置两个onTouchListener
和onClickListener
。
我不确定这是你看到的同一个问题,但是因为我发现这个页面正在搜索我的问题,我想我会添加我的经验来帮助别人:)
在我的情况下,正在生成警告,因为可空视图可能是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)