When the game ends, the showGameOverDialog
method (Fig. 6.16) displays a DialogFragment
(using the techniques you learned in Section 5.6.9) containing an AlertDialog
that indicates whether the player won or lost, the number of shots fired and the total time elapsed. The call to method setPositiveButton
(lines 433–444) creates a reset button for starting a new game.
414 // display an AlertDialog when the game ends
415 private void showGameOverDialog(final int messageId)
416 {
417 // DialogFragment to display quiz stats and start new quiz
418 final DialogFragment gameResult =
419 new DialogFragment()
420 {
421 // create an AlertDialog and return it
422 @Override
423 public Dialog onCreateDialog(Bundle bundle)
424 {
425 // create dialog displaying String resource for messageId
426 AlertDialog.Builder builder =
427 new AlertDialog.Builder(getActivity());
428 builder.setTitle(getResources().getString(messageId));
429
430 // display number of shots fired and total time elapsed
431 builder.setMessage(getResources().getString(
432 R.string.results_format, shotsFired, totalElapsedTime));
433 builder.setPositiveButton(R.string.reset_game,
434 new DialogInterface.OnClickListener()
435 {
436 // called when "Reset Game" Button is pressed
437 @Override
438 public void onClick(DialogInterface dialog, int which)
439 {
440 dialogIsDisplayed = false;
441 newGame(); // set up and start a new game
442 }
443 } // end anonymous inner class
444 ); // end call to setPositiveButton
445
446 return builder.create(); // return the AlertDialog
447 } // end method onCreateDialog
448 }; // end DialogFragment anonymous inner class
449
450 // in GUI thread, use FragmentManager to display the DialogFragment
451 activity.runOnUiThread (
452 new Runnable() {
453 public void run()
454 {
455 dialogIsDisplayed = true;
456 gameResult.setCancelable(false); // modal dialog
457 gameResult.show(activity.getFragmentManager(), "results");
458 }
459 } // end Runnable
460 ); // end call to runOnUiThread
461 } // end method showGameOverDialog
462
The onClick
method of the button’s listener indicates that the dialog is no longer displayed and calls newGame
to set up and start a new game. A dialog must be displayed from the GUI thread, so lines 451–460 call Activity
method runOnUiThread to specify a Runnable
that should execute in the GUI thread as soon as possible. The argument is an object of an anonymous inner class that implements Runnable
. The Runnable
’s run
method indicates that the dialog is displayed and then displays it.