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 Adding the onClick() Method

sahil shokeen
sahil shokeen
1,579 Points

onclick confusion!!!

View.OnClickListner() and View.setOnClickListner(new View.OnClickListner) how they work and when they are invoked??

2 Answers

Jon Kussmann
PLUS
Jon Kussmann
Courses Plus Student 7,254 Points

Often times in an Android application, you want your application to behave a certain way when a user clicks on something, like a button.

To define what happens when that button is clicked on, you "set" the onClickListener to that view (the view being the button in this case). When you instantiate the listener, you must override the "onClick" method. What happens is the application is "waiting" for the user to click that button and when it does, it will run the code within the "onClick" method.

sahil shokeen
sahil shokeen
1,579 Points

but why there is a parameter in view.setOnClickListner?

Jon Kussmann
Jon Kussmann
Courses Plus Student 7,254 Points

Calling View.setOnClickListener assigns a new listener to that object, so you need to tell it which listener you want. You do this by adding it as a parameter.

You can in theory have a few different listeners, so you need to specify which one you want.

sahil shokeen
sahil shokeen
1,579 Points

can u please explain in detail about these methods how they internally work please!!!