I've been trying to set up a long click listener event, but keep getting the following error:

Type mismatch. 

Required:Boolean

Found:Unit

我对setOnClickListener项赛事没有异议,但由于某种原因,我对setOnLongClickListener项赛事的运气为零.

I'm currently trying to display a simple Toast:

view.setOnLongClickListener{
    Toast.makeText(this, "Long click detected", Toast.LENGTH_SHORT).show();
}

I've seen plenty of examples for Java, but I'm yet to find any examples for Kotlin.

推荐答案

OnLongClickListener.onLongClick签名要求您返回一个布尔值,以通知您是否实际使用了该事件

view.setOnLongClickListener{
     Toast.makeText(this, "Long click detected", Toast.LENGTH_SHORT).show()
     return@setOnLongClickListener true
}

or

view.setOnLongClickListener{
     Toast.makeText(this, "Long click detected", Toast.LENGTH_SHORT).show()
     true
}

Kotlin相关问答推荐

Kotlin—列出具有不同T的列表之间的操作'

将文本与文本字段的内容对齐

编译后的JavaFX应用程序立即以静默方式崩溃

房间数据库操作中的协程取消

在 Kotlin 中实现并输入 Either

同时也是一个字符串的 Kotlin 枚举

如何使用函数类型或 lambdas 作为 Kotlin 上下文接收器的类型?

为什么 KFunction2 在 Kotlin 中不是可表示类型?

使用 Kotlin 协程时 Room dao 类出错

Kotlin 代码是如何编译成原生代码的?

致命错误 LifecycleOwners 必须在 registerForActivityResult 开始之前调用 register

如何在 Kotlin 文件中的 Android Studio 中控制何时将 Imports 替换为通配符

如何使用 Kotlin Coroutines 使 setOnClickListener debounce 1 秒?

kotlin:扩展方法和空接收器

ActivityOptions.makeSceneTransitionAnimation 在具有多个视图的 kotlin 中不起作用

Kotlin:使用Gradle进行增量编译

如何在Kotlin中获得KType?

编译错误:-Xcoroutines has no effect: coroutines are enabled anyway in 1.3 and beyond

Java Integer.MAX_VALUE 与 Kotlin Int.MAX_VALUE

使用 kotlin 每 3 位数添加逗号或点