Reputation: 21
In the following code, I'm confused as to how do you know its onClick
method of OnClickListener
its overriding ?
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
Upvotes: 0
Views: 139
Reputation: 885
One thing to note is that lambda expression like this is only possible when the lambda takes one function. To see what this is just to pay attention when creating your lambda.
We see here that when we create the onClick its expected parameter is View.OnClickListener. So an OnClick with a receiver of View.
So we can give it that.
As we can see it was expecting one interface wich has one function, OnClickListener.
We can simplify this due to the fact that we are only expecting one interface function on our receiver "view" so it is implicit.
As stated before, we can only have a lambda like this with a single function, so if we look into our onClickListener we can see a single interface which has a single method so the lambda is implicit:
Upvotes: 1
Reputation: 3128
OnClickListener
only have the onClick method. Therefore Kotlin will use a lambda expression to simplify it. The normal code to the OnClickListener
is as given below.
setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
But if you have more than one method, this won't be the case. For example setOnQueryTextListener
on a SearchView you need to override the two functions separetely.
setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onQueryTextChange(newText: String?): Boolean {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
})
You can find more about Lambda functions from this doc
Upvotes: 1