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

Blog Reader onClickListener?

Im trying to do the extra credit "Clicks Ahoy" on the blog reader segment "Rebuilding from Scratch" and i cant seem to get the ball rolling on how to implement the OnClickListener

1 Answer

Ben Junya
Ben Junya
12,365 Points

Hey Laura,

I know the feeling of just starting out. It's quite daunting, and especially all the code that drops in with onClickListener. Here's a quick guide for you:

// declare your button object (if it isn't already declared). For the findViewById - find the ID of the button in the layout file
Button myButton = (Button) findViewById(R.id.button2);

// declare and set your onClickListener to myButton
myButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
  // Your code goes here! This happens when the user clicks on the button!
}
});

I hope this helps you out. I know the code is a bit daunting for the OnClickListener, but look closely and observe -

myButton.setOnClickListener( new View.OnClickListener()) {...

This single line of code declares your brand new onClickListener, and sets it to that button you declared.

A good rule of thumb to remember is whenever you use a "findViewById()" method, you use an ID that must correspond with an object in your layout.xml file. All beginner stuff, but solid basic skills make solid programmers.

Good luck! Hope this helps!

Ben