Wiring Up Widgets - Doing it the hard way?


In this section we are told to create member variables and listeners for the [True] and [False] buttons. Why don’t we use the Button’s android:onClick attribute instead? It’s so much easier to do that then create methods in the QuizActivity class.

android:text=”@string/true_button" />


android:text="@string/false_button" />


I guess it would work. But you need to change the names to “leftButton” and “rightButton”. You dont know which button will be the right or wrong beforehand.

Then maybe connect the “onClick” to “string.xml”, put a reference in R.java.
and in the activity class we make a method that compaires the value from R.java with the actual value of the right answer.


I was going to ask the exact same question. I think it may be confusing looking at the OP’s question because he said “rightAnswer” and “wrongAnswer” in the XML. What is really meant is “trueButton” and “falseButton”. The methods would be the exact same as they are now and those methods will figure out whether the true or false is the correct answer. So don’t let right/wrong be a red herring to what is the central question here. Why not use the onClick property of the XML to call the needed method rather than dealing with writing out listeners and anonymous inner methods? It is much more readable and less error prone to do it via XML onClick than what the book is asking.

For those with iOS experience this would be analogous to click dragging from the on-screen button to the method in code to create an IBAction. The difference here though is that the XML is REQUIRED while the graphical design within iOS is not (the interface could be built in code). So again it makes even more sense in Android.

I understand if it is being done here to teach the underlying workings of these actions but I don’t know if that is indeed the case. Having gone through their iOS book some years back and I know they do tend to like to do everything in code which may be what is going on here. Regardless, it is good to know it can be done with the XML property and people can decide later how they want to do it. For now based on what I’ve seen, it is much cleaner and less error prone.