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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
OnClickListenerfor anyViewin XML. Here’s an example:Using the
onClickattribute, you assign the name of the method that will handle the click. This method must exist in the sameContextas theView, so in the sameActivity. So for example, I would have to implement this method:I believe it has to have a
Viewparameter, just like implementingOnClickListenerwould. 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.