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 OnClickListenerInterfa
I was desperately looking for a Kotlin solution similar to what Java interfaces offer until I bumped into the suggestions offered thereabove. Having tried all of them, I was unable to arrive at a working solution that would suit my scenario.
This led to my own implementation which worked perfectly according to my use case, and therefore thought I could share the same here, though it may not be the perfect way of doing it, apologies in advance.
The steps:
interface OnClickListenerInterface {
fun onClick()
}
Create a nullable variable.
var listener: OnClickListenerInterface? = null
Declare a function to initialise the variable above.
fun initOnClickInterface(listener: OnClickListenerInterface){
this.listener = listener
}
At the point where you want to trigger the "onClick" callback:
mCircleShape.setOnClickListener(View.OnClickListener {
if (listener == null) return@OnClickListener
listener?.onClick() // Trigger the call back
})
Make the activity implement the OnClickListenerInterface, then create an object of your CircleShape class.
class Activity : AppCompatActivity(), OnClickListenerInterface {
val mCircleShape = CircleShape()
// ...other stuff
Inside the onCreate function of this activity, initialise your interface using the initOnClickInterface function we created in the CircleShape class.
mCircleShape.initOnClickListenerInterface(this)
Then finish by overriding the onClick method of our interface by adding the code below in the activity.
override fun onClick() {
// Callback received successfully. Do your stuff here
}
The above steps worked for me.
As I said, in case of any issues with my coding, I'm a learner too