How I can use callback in Kotlin?

后端 未结 7 2189
Happy的楠姐
Happy的楠姐 2020-12-13 04:05

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         


        
7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-13 04:30

    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

提交回复
热议问题