15

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

 <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 ?

Murphy316
  • 766
  • 3
  • 13
  • 29

5 Answers5

35
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;
}
Vic Vuci
  • 6,993
  • 6
  • 55
  • 90
15

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

<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(); 
}
Kamil Lelonek
  • 14,592
  • 14
  • 66
  • 90
14

Simply switch over the 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;
}
Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
Aamir Shah
  • 4,473
  • 8
  • 21
  • 28
6

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;
}
pocmo
  • 660
  • 6
  • 24
user1693775
  • 126
  • 3
1

In xml add tag, np with name of button.

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

Other answers seems also good;)

Drake29a
  • 896
  • 8
  • 23