开发者

How to determine which button pressed on android

开发者 https://www.devze.com 2023-01-10 02:33 出处:网络
i need to know, how to recognize, which button is pressed. Like if i h开发者_如何学运维ave two buttons ,say button 1 and button2,and both of them performing the same method, say method(),how to determ

i need to know, how to recognize, which button is pressed. Like if i h开发者_如何学运维ave two buttons ,say button 1 and button2,and both of them performing the same method, say method(),how to determine which button pressed ?

Regards


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.


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();
}


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){

}

}


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();
    }
}


Ok got the solution

if (yesButton.getId() == ((Button) v).getId()){

  // remainingNumber
 }

else if (noButton.getId() == ((Button) v).getId()) 
{
    // it was the second button
}
0

精彩评论

暂无评论...
验证码 换一张
取 消