如何确定在android上按下了哪个按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3412180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to determine which button pressed on android
提问by Shishir.bobby
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 to determine which button pressed ?
我需要知道,如何识别,按下了哪个按钮。就像我有两个按钮,比如说按钮 1 和按钮 2,并且它们都执行相同的方法,比如说 method(),如何确定按下了哪个按钮?
Regards
问候
回答by Paul Turchenko
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.
这样调试起来会更简单,并确保您不会错过处理任何点击。
回答by adwairi
I have 10 buttons performing the same method updateText()
, I used this code to get the clicked button's text:
我有 10 个按钮执行相同的方法updateText()
,我使用此代码来获取单击按钮的文本:
public void updateText(View v){
Button btn = (Button) findViewById(v.getId());
String text = btn.getText().toString();
}
回答by Bijay Ktheitroadala
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
或者...您可以在按钮的xml代码中放置一个android:onClick="foo",并在带有签名的java上定义一个方法。在方法 foo 中,获取 id 并将其与您需要的进行比较
public void foo(View v){
if (v.getId() == R.id.yourButton){
}
else if (v.getId() == R.id.nextButton){
}
}
回答by Asahi
If by "performing the same method" you mean theirs OnClickListener then you have to reference the parameter being passed to it.
如果“执行相同的方法”是指他们的 OnClickListener,那么您必须引用传递给它的参数。
public void onClick(View v) {
if(v==btnA) {
doA();
} else if(v==btnB) {
doB();
}
}
回答by Shishir.bobby
Ok got the solution
好的得到了解决方案
if (yesButton.getId() == ((Button) v).getId()){
// remainingNumber
}
else if (noButton.getId() == ((Button) v).getId())
{
// it was the second button
}