5.6.9. Anonymous Inner Class That Implements OnClickListener

Lines 91–98 (Fig. 5.27) registered guessButtonListener (Fig. 5.33) as the event-handling object for each guess Button. Instance variable guessButtonListener refers to an anonymous inner class object that implements interface OnClickListener to respond to Button events. The method receives the clicked Button as parameter v. We get the Button’s text (line 259) and the parsed country name (line 260), then increment totalGuesses.

If the guess is correct (line 263), we increment correctAnswers. Next, we set the answerTextView’s text to the country name and change its color to the color represented by the constant R.color.correct_answer (green), and we call our utility method disableButtons (Section 5.6.10) to disable all the answer Buttons.

If correctAnswers is FLAGS_IN_QUIZ (line 275), the quiz is over. Lines 278–307 create a new anonymous inner class that extends DialogFragment and will be used to display the quiz results. The DialogFragment’s onCreateDialog method uses an AlertDialog.Builder to configure and create an AlertDialog, then returns it. When the user touches the dialog’s Reset Quiz Button, method resetQuiz is called to start a new game (line 300). To display the DialogFragment, line 310 calls its show method, passing as arguments the FragmentManager returned by getFragmentManager and a String. The second argument can be used with FragmentManager method getFragmentByTag to get a reference to the DialogFragment at a later time—we don’t use this capability in this app.

If correctAnswers is less than FLAGS_IN_QUIZ, then lines 315–323 call the postDelayed method of Handler object handler. The first argument defines an anonymous inner class that implements the Runnable interface—this represents the task to perform (loadNextFlag) some number of milliseconds into the future. The second argument is the delay in milliseconds (2000). If the guess is incorrect, line 328 invokes flagImageView’s startAnimation method to play the shakeAnimation that was loaded in method onCreateView. We also set the text on answerTextView to display "Incorrect!" in red (lines 331–333), then disable the guessButton that corresponds to the incorrect answer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset