• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Preferred method for handling OnClick?

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

First, put the handling code into the setOnClickListener call:
Code:
<Button android:id="@+id/someButton"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/Click" />

-----

final Button someButton = (Button) findViewById(R.id.someButton);
someButton.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        // handle someButton's click
    }
});
Second, use OnClickListener with parameter "this", and handle the click in a separate onClick call:
Code:
<Button android:id="@+id/someButton"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/Click" />

-----

final Button someButton = (Button) findViewById(R.id.someButton);
someButton.setOnClickListener(this);

@Override
public void onClick(View v)
{
    if (v == someButton)
    {
        // handle someButton's click
    }
}
Third, include android.onClick in the XML:
Code:
<Button android:id="@+id/someButton"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:text="@string/Click"
        android:onClick="someButton_Click" />

-----

public void someButton_Click(View v)
{
    // handle someButton's click
}
Are there any advantages in using one of these ways over the others?

-- Don
 
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...
 
Back
Top Bottom