I am new to Java/Android programming and unfortunately I don't fully under stand the logic behind this piece of code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
I have alredy read a whole lot of tutorials about it but unfortunately in no one so far the code gets explained in detail. Maybe because it's so basic that every decent object oriented programmer would understand the reason for the structure right away.
I am wondering why do I need to use new View.OnClickListener()
as a parameter? for the setOnClickListener
method. In other words why doesn't something like
button.setOnClickListener(
public void onClick(View v) {
// Perform action on click
});
this work?
Besides that I am not quite sure why the onClick
method requires the paramterer of View v
.
I would be quite thankful for some help since I am currently rather puzzled.
View.OnClickListener
is an interface which you need to implement when you want to handle click events. In your code, you are doing that by doingnew View.OnClickListener()
. Here you are actually creating an anonymous class that implementsView.OnClickListener
. And any class that implementsView.OnClickListener
must also implement all the methods declared in it (e.g. theonClick
method). Also, inpublic void onClick(View v) {..}
, theView v
denotes the view or the button that was clicked so that you can perform whatever you want with it. For example, get it's id, change it's color etc.