Reputation: 8030
I would like to ask you some information about the managing events in android programming.
In java, when an event occurs, an Event object instance is created and it is passed to the method of the listener class whom implements it; in android I have noticed that all the methods of the listeners class require, as parameter, a View instance, then the first question is the following: when an event occurs, in android, isn't an Event object instance created?
The second doubt I ran into came reading the following http://developer.android.com/training/basics/firstapp/starting-activity.html , here with the attribute android:onClick I can specify the method I want to be executed when an click event occurs, then the problem is the following: why should I speficy a method? Shouldn't I indicate that class whom implements a listener and has inside that particular method that manages that particular event?
Upvotes: 2
Views: 145
Reputation: 83527
Swing creates Event objects to send to the methods in its listeners. It is very consistent about following this pattern. Android is not so consistent. It sends onClick()
a View
, but it sends onKey
a View
, int
, and KeyEvent
. This shows that Swing's approach of wrapping everything in an Event object is not the only way to process events.
android:onClick
is a shortcut to assign a callback method for an onClick event. It assumes will look for that method in the context class of the view which was clicked. Usually this is a subclass of Activity. Certainly, the API designers could have required a class name instead and assumed a certain method name (say, onClick()
) within that class. However, that not have been much better than using setOnClickListener()
.
Upvotes: 1
Reputation: 3636
Android use a system of callbacks to manage these sort of events (click, touch, etc.)
For example, when you click on a button btnMyButton
, the framework will check if there is a OnClickListener
attached to it, and if so execute its onClick()
method.
Listeners methods usually take a View
argument so you can use the same instance for several Views
, and adapt the behavior depending on the affected view (usually using View.getId()
)
the android:onClick
is just an XML shortcut which can be handy for tiny apps.
For bigger application, I believe it is clearer and less error prone to use View.setOnClickListener()
instead.
Upvotes: 1