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 trialRadu Stanciu
Courses Plus Student 3,274 PointsWhy is this wrong? isn't the purpose of refactoring using the same code in multiple places?
i made a method which includes all the common code in both onclicks.
maybe i didn't understand how refactoring works
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
public static final String TAG = MainActivity.class.getSimpleName();
public Button mButton1;
public Button mButton2;
/*
* Some code has been omitted for brevity
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton1 = (Button)findViewById(R.id.button1);
mButton2 = (Button)findViewById(R.id.button2);
mButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
trackButtonPress();
}
});
mButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
trackButtonPress();
}
});
}
public void trackButtonPress()
{
Toast.makeText(MainActivity.this, "A button was pressed", Toast.LENGTH_LONG).show();
Log.i(TAG, "A button was pressed");
}
}
3 Answers
Richard Ling
8,522 PointsHi, I couldn't see anything wrong with your code, and when I plugged it into the Code Challenge it said it was correct? Where did it say it was wrong?
Radu Stanciu
Courses Plus Student 3,274 PointsI just copied and pasted that code again in the challenge to show you the error and now it works...
Weird. I was probaly missing something...
Sorry for the bother.
Thanks for the help!
Michael Perry
8,101 PointsI was stuck on this problem and I created a method that returned the entire OnClick Listener. I tested the code on my emulator and it worked but it wouldn't work for the Code challenge. I am curious to know if I'm wrong, or if this answer and mine are right or if one is more right than the other.
... mButton2.setOnClickListener(trackButtonPress()); }
public OnClickListener trackButtonPress(){
OnClickListener listener = new OnClickListener(){
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "A button was pressed", Toast.LENGTH_LONG).show();
Log.i(TAG, "A button was pressed");
}
};
return listener;
}
}