jjz
jjz

Reputation: 2057

Which is better in implementing click listener?

Which is a good practice in implementing click listener and why? Or is there a better way other than the two? Thanks.

First :

    sampleButton.setOnClickListener(new View.OnClickListener(){
        public void onClick(View v){
            // do something
        }

    });

Second : implement OnClickListener then override onClick method?

Upvotes: 1

Views: 208

Answers (3)

Graham Borland
Graham Borland

Reputation: 60691

The third option is to set the listener directly in your XML layout:

android:onClick="myClickHandler"

and then implement it in your Activity:

public void myClickHandler(View v){
        // do something
    }

Upvotes: 3

Kurru
Kurru

Reputation: 14331

You're technically doing the 2nd thing with the 1st one. The 1st case uses whats called an anonymous class which implements OnClickListener, but since is anonymous, doesn't have a class name and isn't editable from external classes. Explicitably implementing OnClickListener is useful if you expect to use the same onClick functionality in multiple different locations, or if the click code is long

Upvotes: 1

Yashwanth Kumar
Yashwanth Kumar

Reputation: 29131

The first approach is used when you want to perform the action only for a particular case, if many click events require the same action then use the second one.

Upvotes: 1

Related Questions