Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly use setOnLongClickListener() with Kotlin

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.

like image 389
Dylan Hargett Avatar asked Apr 07 '18 22:04

Dylan Hargett


4 Answers

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
}
like image 173
Samuel Eminet Avatar answered Nov 05 '22 13:11

Samuel Eminet


Another way can be this...

view.setOnLongClickListener{
    dispathAnEventOnLongClick("Long click detected!");
}
private fun dispathAnEventOnLongClick(text:CharSequence): Boolean {
    Toast.makeText(applicationContext,text,Toast.LENGTH_SHORT).show();
    return true;
}
like image 38
CATCODER DEV Avatar answered Nov 05 '22 13:11

CATCODER DEV


This one also works for Kotlin. Simply return true

view.setOnLongClickListener {
    Toast.makeText(this,"This is a long click",Toast.LENGTH_SHORT).show(); 
    true
}
like image 2
Bashi Lenny Avatar answered Nov 05 '22 13:11

Bashi Lenny


Inline Functions

You can make an inline function that consume a function and return a boolean. Then use it with any functions that required a boolean as return type.

In a kotlin file:

inline fun consume(function: () -> Unit): Boolean {
    function()
    return true
}

Usage:

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

Now your code will work and returned a true value to satisfied the need for setOnLongClickListener method. You can reuse this function consume with any function that require a true value like onCreateOptionsMenu and onOptionsItemSelected without an explicitly needs to return a true value.

This way uses: Inline Functions. And the solution you checked as a best answer uses : Labeled Return.

like image 1
MohammadL Avatar answered Nov 05 '22 13:11

MohammadL