Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...