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:
- 1. Define your interface:
interface OnClickListenerInterface {
fun onClick()
}
- 2. Inside the class that will trigger the "onClick" callback i.e. "CircleShape" for your case:
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
})
- 3. Inside the activity where you want to receive the "onClick" callback:
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 😎.
Cheers!
object:OnClickListenerInterfacepart was not known to me. Thanks