-2
Hello, my Activity has several buttons. I would like to know if there is as a variable collect the button that the user click on the screen. Thus, the variable would update its value whenever a button was clicked.
I searched the documentation if I could find something to grab the button and store it in a variable, but I couldn’t find it. Therefore, my current code has a Switch for each of the buttons:
button_0.setOnClickListener() {
.
.
.
}
button_1.setOnClickListener() {...}
button_2.setOnClickListener() {...}
button_15.setOnClickListener() {...}
I am repeating the same code several times and it is causing me a lot of work to do maintenance whenever I find a new bug. What I would like to do is a function that would get the button clicked and run the setOnClickListener method().
var clickedButton = getButtonClicked // Existe uma forma de armazenar o botão clicado?
buttonClicked(ClickedButton) // Executa a função genérica abaixo.
fun buttonClicked (Button) {
Button.setOnClickListener() {...}
Your doubt is not very clear. The code that exists inside the listeners is similar, and you want to make it kind of generic, that’s it?
– Leonardo Lima
That’s right, Leonardo, yes. The Code is basically the same, the difference is that each of the buttons (1 to 15) give different values to a group of variables. I made an update of the question to improve understanding.
– Ramon Barros
@Ramonbarros An option is within each
setOnClickListener
you call, for example,setOnClickListener { btn -> buttonClicked(btn) }
or passing another value of your interest– Rafael Tavares