Preferred method for handling OnClick?


Last Updated:

  1. That Don Guy

    That Don Guy Member

    I have noticed three different ways of handling a Button click:

    First, put the handling code into the setOnClickListener call:
    Code (Text):
    1.  
    2. <Button android:id="@+id/someButton"
    3.         android:layout_height="wrap_content"
    4.         android:layout_width="wrap_content"
    5.         android:text="@string/Click" />
    6.  
    7. -----
    8.  
    9. final Button someButton = (Button) findViewById(R.id.someButton);
    10. someButton.setOnClickListener(new View.OnClickListener() {
    11.     public void onClick(View v) {
    12.         // handle someButton's click
    13.     }
    14. });
    Second, use OnClickListener with parameter "this", and handle the click in a separate onClick call:
    Code (Text):
    1.  
    2. <Button android:id="@+id/someButton"
    3.         android:layout_height="wrap_content"
    4.         android:layout_width="wrap_content"
    5.         android:text="@string/Click" />
    6.  
    7. -----
    8.  
    9. final Button someButton = (Button) findViewById(R.id.someButton);
    10. someButton.setOnClickListener(this);
    11.  
    12. @Override
    13. public void onClick(View v)
    14. {
    15.     if (v == someButton)
    16.     {
    17.         // handle someButton's click
    18.     }
    19. }
    Third, include android.onClick in the XML:
    Code (Text):
    1.  
    2. <Button android:id="@+id/someButton"
    3.         android:layout_height="wrap_content"
    4.         android:layout_width="wrap_content"
    5.         android:text="@string/Click"
    6.         android:onClick="someButton_Click" />
    7.  
    8. -----
    9.  
    10. public void someButton_Click(View v)
    11. {
    12.     // handle someButton's click
    13. }
    Are there any advantages in using one of these ways over the others?

    -- Don

    Advertisement
  2. JamTheMan

    JamTheMan Well-Known Member

    I, for one, always use a generic onClick handler defined in the xml and then with a switch case for all the buttons in a single activity.
    Not for any specific performance reasons, I just find it easier to maintain, and it creates fewer lines of code...

Share This Page