Most used way is, anonymous declaration
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// handle click
}
});
Also you can create View.OnClickListener object and set it to button later, but you still need to override onClick method for example
View.OnClickListener listener = new View.OnClickListener(){
@Override
public void onClick(View v) {
// handle click
}
}
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(listener);
When your activity implements OnClickListener interface you must override onClick(View v) method on activity level. Then you can assing this activity as listener to button, because it already implements interface and overrides the onClick() method
public class MyActivity extends Activity implements View.OnClickListener{
@Override
public void onClick(View v) {
// handle click
}
@Override
public void onCreate(Bundle b) {
Button send = (Button) findViewById(R.id.buttonSend);
send.setOnClickListener(this);
}
}
(imho) 4-th approach used when multiple buttons have same handler, and you can declare one method in activity class and assign this method to multiple buttons in xml layout, also you can create one method for one button, but in this case I prefer to declare handlers inside activity class.