Marco Ramirez Castro
Marco Ramirez Castro

Reputation: 346

Kotlin: Check which button was clicked

I have 3 buttons that call the same method, within the method I'd like to be able to retrieve either the button's text or ID.

Is there something like this?

 fun getButtonID(view: View) {

        var buttonTxt = this.getText
        Log.d("DEV", "${buttonTxt}")

    }

Upvotes: 0

Views: 3019

Answers (1)

cactustictacs
cactustictacs

Reputation: 19524

onClickListeners pass the clicked View to their callback, so you can do this kind of thing to identify it:

fun handleButtonClick(view: View) {
    with (view as Button) {
        Log.d("TAG", "$text, $id")
    }
}

and then set your buttons up like

button1.setOnClickListener { view ->
    handleButtonClick(view)
}

That's one way to cast the View to Button - by doing it in the handler method you only do it in one place. And since your onClick lambda is only calling the method and passing the parameter straight in (no need to cast it as well), it means you can simplify it to a function reference, since your function takes the same arguments the lambda did (i.e. just a View):

button1.setOnClickListener(::handleButtonClick)

and while we're at it

listOf(button1, button2, button3).forEach {
    it.setOnClickListener(::handleButtonClick)
}

Upvotes: 3

Related Questions