Is it possible to set event listener in XML?
android, event-listener, layout, xml
Solution
Most people set their listeners in code. It's sometimes easier to do it in code because you often times will need to add or remove listeners based on some action or state.
However, Android also gives you the option of setting a `OnClickListener` for any `View` in XML. Here's an example:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onActionClick"
android:text="Action" />
Using the `onClick` attribute, you assign the name of the method that will handle the click. This method must exist in the same `Context` as the `View`, so in the same `Activity`. So for example, I would have to implement this method:
public void onActionClick(View v) {
// Do stuff for my "Action" button...
}
I believe it has to have a `View` parameter, just like implementing `OnClickListener` would. I also believe it must be public.
So as far as which way is "best"? That's up to you. Both routes are viable. It's worth noting though that this is only useful for click listeners and not other types of listeners.
Problem
When I using XML to design layout, I am using `findViewById()` in java code to load views and set listeners to them. Is this correct what I am doing? May be it is possible to set listeners in XML or something?