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 Basic Android Programming Making a Button Do Something

Why create the onclick listener outside of the mShowFactButton?

So I am taking to refreshed version of Fun Facts, I try to code along or just a head of Ben Deitch so that I can see what I did versus what he is doing.

I noticed his on click listener looked like:

... 

View.OnClickListener listener = new View OnClickListner() {
  @Override
  public void OnClick(View v) {
  }
}

mShowFactButton.setOnClickListener(listener);

...

where as I did the listner built in to the buttons set onclick listener like so

...
mShowFactButton.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {

  }
});
...

Is there any reason to do one way over the other? They both seem to work fine.

I realize Ben's way could be tapped into from multiple events. Just curious as to if there was other reasons.

1 Answer

Hi John,

I believe Ben wrote it his way to help people who are new to Android development understand what's happening.

Your code and his will function identically in this context, but his more clearly separates the ideas that we have an OnClickListener, and that we are assigning the listener to mShowFactButton.

Gavin Ralston
Gavin Ralston
28,770 Points

Right on. This is probably the same reason he doesn't use lambdas for event handling at this point also.

If the listener is going to be that tightly related to the button, there's no reason to have a reference to the listener floating around, nor a method to handle that one specific task. But it sure would be confusing to someone who stepped into development in general to parse that code in their head, or even reading out loud.

Seth Kroger
Seth Kroger
56,413 Points

Actually, you can't use lambdas for event handling because Android doesn't support them yet. It currently uses Java 7, but hasn't yet updated to Java 8. I understand there's a 3rd party Gradle plugin that can support simple lambda syntax for Android but it doesn't cover everything lambdas are capable of.

Gavin Ralston
Gavin Ralston
28,770 Points

Good point. It's so easy to count on lambdas since they've been a part of C# for the better part of a decade now. :)