Adding actions to a already defined onClickListener

Viewed 34

Is there a way to do something like this:

    view.setOnClickListener { Log.e("","Hello") }
    view.setOnClickListener { Log.e("","World") }

While letting both Log to show.

I have buttons on custom views with some universal actions to execute on click which I initialize them in constructor, now I want to setup some additional behaviors based on situations outside of class. And I notice doing things like above will simply overwrite the onClickListener.

What I can think of is to maybe store Array of Unit in the object and let view execute elements of it as on clicked. Then use accessor to append function to the array.

Is there a more simple way to keep existing actions and append new actions at the end?

2 Answers

Why not use a flag and choose the behaviour depending on that flag like this. Using a listener is a recipe for disaster because as it is a listener it is continuously listening ie the code inside will execute whenever that button is pressed and if there are two blocks one will take precedence over the other.

button.setOnClickListener{
when(flag){
"hello" -> Log.e("TAG","Hello")
"world" -> Log.e("TAG","World")
}

}

with this code you can add click listener as much as you want :

class CustomView @JvmOverloads constructor(
    context: Context?,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val clickCallBacks = mutableListOf<((view: View) -> Unit)>()

    fun addClickListener(listener: ((view: View) -> Unit)) {
        clickCallBacks.add(listener)
    }

    override fun setOnClickListener(l: OnClickListener?) {
        super.setOnClickListener {
            //TODO do what you want to do
            l?.onClick(it)
            for (listener in clickCallBacks) {
                listener.invoke(it)
            }
        }
    }
}

in your activity or fragment:

 customView.view.addClickListener{ Log.e("","Hello") }
 customView.view.addClickListener{ Log.e("","World") }
Related