Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Do I need to Create OnClickListener Instance Every-time?

For example if I have multiple Button on my app, Do I need to create OnClickListener instance for every single button?

2 Answers

Kunal Bhuwalka
Kunal Bhuwalka
32,978 Points

You can use OnItemClickListener if the buttons are inside a listView.

Seth Kroger
Seth Kroger
56,413 Points

It depends. It's certainly possible to have all buttons use the same OnClickListener, you just need to distinguish between different buttons to find out which one is clicked. But this works best if the buttons' functions are similar to each other (like they do the same thing to different data objects). If they are fairly different, it's often best to use different OnClickListener functions to separate out the code instead of having one huge function will all the UI logic.