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 trialErick Shaffer
203 PointsWhat is the benefit of using an onClickListener rather than android:onClick="onButtonClick" in the xml??
Just wondering what the benefit of making an onClickListener is rather than using the attribute onClick in the xml.
For example, in the xml
android:onClick="onButtonClick"
in Java class
public void onButtonClick(View v){ //button code goes here }
1 Answer
Seth Kroger
56,413 Pointsandroid:onClick does have some cons: It uses reflection so it is slower performance-wise and bypasses the usual compiler checks for type correctness. You can give it a method that different signature or a method that doesn't exist and it will compile just fine. It won't be until you tap the item in question when it crashes. The lack of any clear connection in the Java code between the method and the view can make it difficult to see what's going on. It's also the only listener you can set in XML which makes it inconsistent style-wise when using the others like OnLongClickListener, etc.