Class EraseImageDialogFragment
(Fig. 7.40) extends DialogFragment
to create an AlertDialog
that confirms whether the user really wants to erase the entire image. The class is similar to class ColorDialogFragment
and LineWidthDialogFragment
, so we discuss only method onCreateDialog
(lines 16–41) here. The method creates an AlertDialog
with Erase Image and Cancel button. Lines 27–35 configure the Erase Image button as the positive button—when the user touches this, line 32 in the button’s listener calls the DoodleView
’s clear
method to erase the image. Line 38 configures Cancel as the negative button—when the user touches this, the dialog is dismissed. Line 40 returns the AlertDialog
.
1 // EraseImageDialogFragment.java
2 // Allows user to erase image
3 package com.deitel.doodlz;
4
5 import android.app.Activity;
6 import android.app.AlertDialog;
7 import android.app.Dialog;
8 import android.app.DialogFragment;
9 import android.content.DialogInterface;
10 import android.os.Bundle;
11
12 //class for the Select Color dialog
13 public class EraseImageDialogFragment extends DialogFragment
14 {
15 // create an AlertDialog and return it
16 @Override
17 public Dialog onCreateDialog(Bundle bundle)
18 {
19 AlertDialog.Builder builder =
20 new AlertDialog.Builder(getActivity());
21
22 // set the AlertDialog's message
23 builder.setMessage(R.string.message_erase);
24 builder.setCancelable(false);
25
26 // add Erase Button
27 builder.setPositiveButton(R.string.button_erase,
28 new DialogInterface.OnClickListener()
29 {
30 public void onClick(DialogInterface dialog, int id)
31 {
32 getDoodleFragment().getDoodleView().clear(); // clear image
33 }
34 }
35 ); // end call to setPositiveButton
36
37 // add Cancel Button
38 builder.setNegativeButton(R.string.button_cancel, null);
39
40 return builder.create(); // return dialog
41 } // end method onCreateDialog
42
43 // gets a reference to the DoodleFragment
44 private DoodleFragment getDoodleFragment()
45 {
46 return (DoodleFragment) getFragmentManager().findFragmentById(
47 R.id.doodleFragment);
48 }
49
50 // tell DoodleFragment that dialog is now displayed
51 @Override
52 public void onAttach(Activity activity)
53 {
54 super.onAttach(activity);
55 DoodleFragment fragment = getDoodleFragment();
56
57 if (fragment != null )
58 fragment.setDialogOnScreen(true );
59 }
60
61 // tell DoodleFragment that dialog is no longer displayed
62 @Override
63 public void onDetach()
64 {
65 super.onDetach();
66 DoodleFragment fragment = getDoodleFragment();
67
68 if (fragment != null )
69 fragment.setDialogOnScreen(false);
70 }
71 } // end class EraseImageDialogFragment