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.
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
OnClickListenerinterface. You can set the OnClickListener of every View tothis, and receive all the click events in one method, where you can then filter them and act upon them.The first method translates to:
Which is to say that it dynamically creates and stores a new
OnClickListenerinstance 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.