How to determine which button pressed on android

前端 未结 5 697
闹比i
闹比i 2020-12-01 09:38

i need to know, how to recognize, which button is pressed. Like if i have two buttons ,say button 1 and button2,and both of them performing the same method, say method(),how

相关标签:
5条回答
  • 2020-12-01 09:59

    Ok got the solution

    if (yesButton.getId() == ((Button) v).getId()){
    
      // remainingNumber
     }
    
    else if (noButton.getId() == ((Button) v).getId()) 
    {
        // it was the second button
    }
    
    0 讨论(0)
  • 2020-12-01 10:00

    OR... you can just put a android:onClick="foo" in the xml code of the button, and define a method on java with the signature. Inside the method foo, get the id and compare it with the one you need

    public void foo(View v){
    
    if (v.getId() == R.id.yourButton){
    
    }
    
    else if (v.getId() == R.id.nextButton){
    
    }
    
    }
    
    0 讨论(0)
  • 2020-12-01 10:07

    I have 10 buttons performing the same method updateText(), I used this code to get the clicked button's text:

    public void updateText(View v){
        Button btn = (Button) findViewById(v.getId());
        String text = btn.getText().toString();
    }
    
    0 讨论(0)
  • 2020-12-01 10:09

    If by "performing the same method" you mean theirs OnClickListener then you have to reference the parameter being passed to it.

    public void onClick(View v) {
        if(v==btnA) {
           doA();
        } else if(v==btnB) {
           doB();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 10:14

    Most ellegant pattern to follow:

    public void onClick(View v) {
    switch(v.getId())
    {
    case R.id.button_a_id:
    // handle button A click;
    break;
    case R.id.button_b_id:
    // handle button B click;
    break;
    default:
    throw new RuntimeException("Unknow button ID");
    }
    

    This way it's much simplier to debug it and makes sure you don't miss to handle any click.

    0 讨论(0)
提交回复
热议问题