Variable grab the ID of a button clicked on Activity

Asked

Viewed 80 times

-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?

  • 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.

  • @Ramonbarros An option is within each setOnClickListener you call, for example, setOnClickListener { btn -> buttonClicked(btn) } or passing another value of your interest

1 answer

0

If I understand your problem correctly, you can declare in the layout:

<Button android:text="Botao 1" onClick="buttonClicked"/>
<Button android:text="Botao 2" onClick="buttonClicked"/>
<Button android:text="Botao 3" onClick="buttonClicked"/>

And in Activity:

fun buttonClicked(view: View) {
  val button = view as Button
  Log.i("Activity", " O botao com texto '" + button.text + "' foi clicado")
}
  • Man, I think that would be it. I am a student of programming and what you said makes sense: But it happened that the following error appeared as soon as I created the function and set onClick in button_0. Could not find method buttonClicked(View) in a Parent or Ancestor Context for android:onClick attribute defined on view class com.google.android.material.button.Materialbutton with id 'button_0'

  • I got it. I already had another buttonClicked function that I didn’t have (view) as a parameter and was conflicting. It worked Leonardo. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.