Passing parameter from a button to android:onClick method

25,727

Solution 1

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

Solution 2

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

Solution 3

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

Solution 4

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;
}
Share:
25,727
Murphy316
Author by

Murphy316

Updated on October 16, 2020

Comments

  • Murphy316
    Murphy316 over 3 years

    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 ?