1. Check out our companion app, Forums for Android! Download from Google Play

Preferred method for handling OnClick?

Discussion in 'Application Development' started by That Don Guy, Mar 1, 2011.

  1. That Don Guy

    That Don Guy Member
    Thread Starter
    6

    Feb 24, 2011
    7
    1
    6
    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
    38

    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

Loading...