将参数从按钮传递给 android:onClick 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12727331/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:35:11  来源:igfitidea点击:

Passing parameter from a button to android:onClick method

androideclipseeclipse-adt

提问by Murphy316

Hi I have something like this (3 buttons) in my activity xml pointing to same method:

嗨,我的活动 xml 中有这样的(3 个按钮)指向相同的方法:

 <Button
        android:id="@+id/Button_1"
        android:onClick="printNo"
        android:text="@string/Button_1" />
 <Button
        android:id="@+id/Button_2"
        android:onClick="printNo"
        android:text="@string/Button_2" />

 <Button
        android:id="@+id/Button_3"
        android:onClick="printNo"
        android:text="@string/Button_3" />

Is there any way I could determine which button was pressed while in the printNo method ?

有什么方法可以确定在 printNo 方法中按下了哪个按钮?

回答by VicVu

public void printNo( View v ) {
    switch (v.getId()) {
    case (R.id.Button_1):
        //stuff
    break;
    case (R.id.Button_2):
        //stuff
    break;
    case (R.id.Button_3):
        //stuff
    break;
}

回答by Aamir Shah

Simply switch over the ID:

只需切换ID:

public void printNo(View v){
    switch (v.getId()){
    case R.id.Button_1:
        break;
    case R.id.Button_2:
        break;
    case R.id.Button_3:
        break;
}

回答by Kamil Lelonek

As @user1106018 said - you can use tagin xml like that:

正如@user1106018 所说 - 您可以tag像这样在 xml 中使用:

<Button android:onClick="f" android:tag="0"/>

Then it is really simple to get this tag in this way:

那么通过这种方式获取这个标签真的很简单:

public void f(View v) {
    String value =  v.getTag(); 
}

回答by user1693775

Working in my end

在我的最后工作

public void printNo(View v) {

switch (v.getId()) {

    case R.id.Button_1:
    break;

    case R.id.Button_2:
    break;

    case R.id.Button_3:
    break;
}

回答by Drake29a

In xml add tag, np with name of button.

在 xml 中添加标签,np 与按钮名称。

public void printNo(View V){
    view.getTag();
    // now you can recognize view with getTag()
}

Other answers seems also good;)

其他答案似乎也不错;)