Question

What are the two ways to add Event Listeners to buttons in Android?

I have seen that you can specify the listener within the XML. I personally prefer this way as it usually involves less code. I know some people like to create an anonymous inner class...

I'm relatively new to programming in Android, so this question is purely to expand my knowledge. Be interested to hear what the community has to say on this!

Jack

Was it helpful?

Solution

It depends on your tasks. In one case specify listeners in XML is enough. In other case, for example, when you create buttons dynamically in code, you will need to have defined listener in code or create anonymous inners. Another situation when the listener is used as parameter of method and you won't be able to specify it in XML.

OTHER TIPS

The way I look at it, and I would imagine most would agree, if the button is used for a one time function then putting it in the xml is fine. If you have a button that is used in multiple places then it is better to set the onClick listener in the activity. I have a program that has buttons that do certain things depending on other variables in the program. If I call one function from xml then it won't always call the right one or take the appropriate actions. I hope this makes sense. And Tim is right, this question is on the borderline of not being a "constructive" question for SO but hopefully I answered it in a way for you that makes it more objective. Happy Programming!!!

All i've every used are inner classes because that's what all the tutorials i've seen show. I do know that you can also use "implements OnClickListener" on your class declaration and set all the click listeners in your code as one big case statement. It might look neater, but I don't think it follows the natural train of thought when writing an activity, especially one with a lot of buttons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top