I'm having a difficult time trying how to figure out how to create a callback in Kotlin using lambdas. I have a custom TextInputEditText and I want to implement a function that the activity can call when text changes.
Here is my custom EditText:
class EditTextEx : TextInputEditText, TextWatcher {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// Call the callback onTextAvailable with the EditText's text (s.toString)
}
override fun afterTextChanged(p0: Editable?) {
}
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
}
In my activity I want to have a callback that gets called when the onTextChanged event gets called. The callback in the custom control sends only the text back to the client. So in my activity, I want something like this:
editText.onTextAvailable(text -> do something )
It's actually quite easy to do, look:
Now you can call
Try something like this:
Hope it helps
In addition to the solution by @EpicPandaForce, there are a couple other solutions. If you want to stick with using a class as you've shown in your example, then you can do this:
Then in your activity create a function:
And then setup your callback as follows:
This solution allows you to re-use the same onTextChange function for other controls that want to use it as well.
If you prefer to use an interface to define the callback, do this:
Then in your activity, create the callback as follows:
And then setup your callback for your edittext controls as follows: