Use "View" to know which button has been pressed

1

I have a question, I can use view to know which button was used, I'm setting up a calculator and to save code I want to use a single method that can be used by all the numeric buttons, but to do that, I first have to know which button was pressed, I know it should be with view

public void bunton(View view){
    String boton=view //quiero saber que boton me presiono
}
    
asked by Montero 13.10.2016 в 04:14
source

3 answers

2

It's what you say. When you create the button, you do it through an ID, when you send it to the -one function- you recover it using the same ID, in this case through the getId () function of each View.

We create the listener:

View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
 public void onClick(View view) {
  pressed(view);
 }
};

We add it to the buttons:

v.findViewById(R.id.boton_sumar).setOnClickListener(onClickListener);
v.findViewById(R.id.boton_restar).setOnClickListener(onClickListener);
//...y el resto de botones.

And in the function:

private void pressed(View view){
 switch(view.getId()){
  case R.id.boton_sumar:
   //Lo que sea para sumar...
   break;
  case R.id.boton_restar:
   //Lo que sea para restar...
   break;
  case R.id.etc:
    break;
 }
}
    
answered by 13.10.2016 / 04:41
source
2

There is something simpler and it is to put in your xml, within the view you want to capture, a parameter that is android:onClick="nombre_funcion" .

<View
     android:id="@+id/num_11"
     android:layout_width="30dp"
     android:layout_height="30dp"
     android:clickable="true"
     android:onClick="activateNum">

And in your activity you only create the following function:

 public void activateNum(View v)
 {
      switch(v.getId)
      {
            case R.id.boton_sumar:
              //Operación suma...
            break;
            case R.id.boton_restar:
              //Operación resta...
            break;
           case R.id.multiplicar:
              //Operación multiplicar...
           break;

      }
 }

It's the simplest thing and where less code you write.

    
answered by 13.10.2016 в 09:31
0

Maybe you could try returning the button:

public string Button(View view)
{
   Strig boton = view;
   return boton;
}
    
answered by 13.10.2016 в 04:39