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?
First of all you need to remove this code:
Because listener is always null at first and your code just always returns.
var listener: OnClickListenerInterface? = null
is already public (this is a default access level in Kotlin). So you can just set it in your activity, when needed. Uselistener?.onClick()
call to trigger it from your CircleShape.A more simpler solution by using lambda.
Inside CircleShape.kt, declare a lambda function.
Inside your Activity
On CircleShape.kt.
On your Activity
If you're gonna use lambda expression, you can use a Function Type. Here how it looks like on CirclesShapt.kt
So in activity looks like.
define a function like this:
then use like:
to use Kotlin callbacks , I use them in my api calls for success or failure use
Have you tried to use a lambda expression? For example in your case:
Or if you want to make it more kotlin style: