Passing parameter from a button to android:onClick method

Murphy316 picture Murphy316 · Oct 4, 2012 · Viewed 24.2k times · Source

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 ?

Answer

VicVu picture VicVu · Oct 4, 2012
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;
}