Eddy Eddy - 4 months ago 11x
Java Question

Android Development - Why do we have to add 'View' as parameter in onClick method and what it does?

I'm setting up a Event Listener on a Button in Android Studio for changing the text inside the

and came to this point were we define
method. In its parameter list it ask for
Object. Can anyone explain what it does? I can't understand where the object of
class is going to get used.


It is there to let you reuse event handlers like the OnClick method, the View parameter is in your case the Button instance that has fired the method - multiple Buttons can have the same OnClick handler, inside the method you can check which of the Buttons has fired (if there are more than one) and react accordingly.

Actually it is very typical for event-driven programming not only on Android but all contemporary UI programming - iOS, Windows, OS/X, etc.

There is a little bit more to that: the parameter's type is View and not Button because not only Buttons react to OnClick and the common type of UI objects reacting to OnClick is View.

Now not only you can handle the event differently, you have also direct access to the source of the event so that you can work on it - in the example of the Button you can change its caption and you know for sure that you are changing the caption of the very UI object that fired the event.

So it has a lot of sense to do event-driven APIs in this manner.


One of the methods to register an event handler (or ClickListener in Android-world) is assigning the method name to the onClick Attribute directly in the layout - provided of course that the method has the proper signature, that is expect one Parameter of type View and has void return type - you can see an example in the other answer.

The other is to assign an anonymous inner class as a Listener like this:

    new View.OnClickListener() {

      public void onClick(View v) {


You can also have an instance of a class implementing the View.OnClickListener interface, even the `Activity' itself could do it, and then register it as a listener.

In fact all of them work the same - there is an instance of a class implementing View.OnClickListener interface registered in the button instance, the button (or a view for that matter) recognizes a click inside its boundaries and calls a listener passing itself (this) to the listener.

Im my personal opinion the third way is the worst - you can only have one method of a name in the class but many buttons in a layout, so all of them would need to be handled using conditional code.

The first is nice because you can set it visually, yet given that it is all in XML files and you could have multiple layouts for an activity it can be quite a mess to keep it under control in a larger project.

My favorite is thus the second one - it allows you to keep all the logic on one place in the code, for example if you register all you handlers in the onCreate method of an activity.