Go Back   Android Forums > Android Development > Application Development
Application Development Dev lounge for our application developers.

Get excited for the Samsung Galaxy S5! Find everything you need and discuss it in our Galaxy S5 Forum!

test: Reply
 
LinkBack Thread Tools
Old March 1st, 2011, 09:52 AM   #1 (permalink)
New Member
Thread Author (OP)
 
Join Date: Feb 2011
Posts: 7
 
Device(s):
Carrier: Not Provided

Thanks: 0
Thanked 1 Time in 1 Post
Default 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

That Don Guy is offline  
Reply With Quote
sponsored links
Old March 2nd, 2011, 02:57 AM   #2 (permalink)
Member
 
Join Date: Dec 2010
Location: Aarhus, Denmark
Posts: 136
 
Device(s): SE Xperia X10
Carrier: Not Provided

Thanks: 2
Thanked 22 Times in 22 Posts
Default

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...
JamTheMan is offline  
Reply With Quote
Reply


Go Back   Android Forums > Android Development > Application Development
Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



All times are GMT -5. The time now is 03:20 PM.
Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2014, vBulletin Solutions, Inc.