Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
PLUS
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.