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?
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?
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 anyView
in XML. Here's an example:Using the
onClick
attribute, you assign the name of the method that will handle the click. This method must exist in the sameContext
as theView
, so in the sameActivity
. So for example, I would have to implement this method:I believe it has to have a
View
parameter, just like implementingOnClickListener
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.
You may specify
android:onClick
attribute when describe yourView
in XML. The value of this attribute is the name of the method which will be called at yourView
'sonClick
event. Then you should define this method as public in your code and you could pass thereView
object which will determine whatView
from those that you described at xml with the sameandroid:onClick
attributes has gotten touch event from user.There is an onClick attribute that you can use inside your xml.
you can set an
onClick
but I think thats about it