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 Build a Simple Android App (2014) Basic Android Programming Making a Button Do Something

Why is showFactButton.setOnClickListener written in the code after View.OnClickListener listener = new?

First you declare what the button should do when you click it but I dont understand why after all that code you write showFactButton.setOnClickListener(listener); Shouldnt you first declare that showfact button is the one you will use, instead of first declaring what the button will do?

1 Answer

Jon Kussmann
Jon Kussmann
Courses Plus Student 7,254 Points

You can first create a View.OnClickListener object that describes what should be done whenever something has been clicked - for example, create a toast message.

If you want to reuse that same listener for multiple buttons (display the same toast message for different buttons), then all you have to do is pass that listener object to the button(s) instead of having to create a new View.OnClickListener for each button.