Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can use callback in Kotlin?

I have View and one CircleShape , which should show toast in this View. And I use it in main Activity. This is my interface

interface OnClickListenerInterface {   fun onClick() } 

It is CircleShape( it is View in my xml) and listener in my View. I want to implement OnClick in my Activity.

 var listener: OnClickListenerInterface? = null   mCircleShape.setOnClickListener(View.OnClickListener {       if (listener == null) return@OnClickListener       listener!!.onClick()     }) 

I know , that in Kotlin getters and setters generic automatics, but how I can set listener if it private. It is code from my Activity, but It doesn't work

CircleShape.listener  = object :OnClickListenerInterface{       override fun onClick() {         ToastUtils.showSuccessMessage(getContext(),"pressed")       }     } 

How I should to use Callback, onClickListenere in Kotlin?

like image 594
manwhotrycoding Avatar asked Nov 26 '17 19:11

manwhotrycoding


People also ask

How do you execute a callback?

A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.

What is a callback and how do you use it?

A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action. The above example is a synchronous callback, as it is executed immediately.

Where do we use callback?

A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard."


2 Answers

A more simpler solution by using lambda.

Inside CircleShape.kt, declare a lambda function.

var listener: (()->Unit)? = null ... // When you want to invoke the listener listener?.invoke() 

Inside your Activity

mCircleShape.listener = {     // Do something when you observed a call } 
like image 200
Weidian Huang Avatar answered Oct 07 '22 22:10

Weidian Huang


define a function like this:

  fun performWork(param1: String, myCallback: (result: String?) -> Unit) {     // perform some network work      // on network finished     myCallback.invoke("result from network")   } 

use like this:

  performWork("http://..."){ result ->   //use result   } 
like image 25
Dan Alboteanu Avatar answered Oct 07 '22 22:10

Dan Alboteanu