How to properly use setOnLongClickListener() with Kotlin

Dylan Hargett picture Dylan Hargett · Apr 8, 2018 · Viewed 21.9k times · Source

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

Type mismatch. 

Required:Boolean

Found:Unit

I've had no issues with the setOnClickListener event, but for some reason I'm having zero luck with the setOnLongClickListener event.

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.

Answer

Samuel Eminet picture Samuel Eminet · Apr 8, 2018

OnLongClickListener.onLongClick signature required that you return a boolean to notify if you actually consumed the event

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
}