user2742371
user2742371

Reputation:

The different OnClickListener implementation ways

What is the difference between:

public class MainActivity extends Activity {

    public void onCreate (Bundle savedInstanceState) {
        button1 = (Button) findViewById(R.id.btn1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Click code
            }
        )};
    }
}

And:

public class MainActivity extends Activity implements OnClickListener {

    public void onCreate (Bundle savedInstanceState) {
        button1 = (Button) findViewById(R.id.btn1);
        button1.setOnClickListener(this);
    }

    public void onClick(View arg0) {
        switch(arg0.getId()) {
        case R.id.button1:
            // Click code
            break;
        }
    }
}

They have both the exact same functionality and results.

Upvotes: 2

Views: 1263

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82533

The first method uses an anonymous inner class that implements the interface method. By using this approach, you receive events only for that particular View.

In the second method, you entire Activity class implements the OnClickListener interface. You can set the OnClickListener of every View to this, and receive all the click events in one method, where you can then filter them and act upon them.

The first method translates to:

Button.OnClickListener anonymous_listener = new Button.OnClickListener() { ... };
button.setOnClickListener(anonymous_listener);

Which is to say that it dynamically creates and stores a new OnClickListener instance when you use it.

In the second method, your entire class uses one single instance of the OnClickListener, that is passed to all the Views you want to listen for clicks on.

Upvotes: 3

Related Questions