Putting It All Together

Now that we have explained each piece of code that goes into a prompt dialog, we'll present it in one place so you can use it to test the dialog (see Listing 5-27). We have excluded the PromptListener class because it appears separately in Listing 5-26.

Listing 5-27. Code to Test the Prompt Dialog public class Alerts {

public static String prompt(String message, Context ctx) {

//load some kind of a view

LayoutInflater li = LayoutInflater.from(ctx);

View view = li.inflate(R.layout.promptdialog, null);

//get a builder and set the view

AlertDialog.Builder builder = new AlertDialog.Builder(ctx);

builder.setTitle("Prompt");

builder.setView(view);

//add buttons and listener

PromptListener pl = new PromptListener(view,ctx); builder.setPositiveButton("OK", pl); builder.setNegativeButton("Cancel", pl);

//get the dialog

AlertDialog ad = builder.create();

return pl.getPromptReply();

You can invoke the code in Listing 5-27 by creating a menu item in the test harness described at the beginning of this chapter and responding to that menu item using this code:

String reply = Alerts.showPrompt("Your text goes here", this);

The result should look like the screen shown in Figure 5-5.

Sample Dialogs Application

Sample Dialogs Application

Debug Scratch Pad alert:2131165190 prompt:2131165191

Debug Scratch Pad alert:2131165190 prompt:2131165191

Figure 5-5. A simple prompt dialog

After writing all this code, however, you will notice that the prompt dialog always returns null even if the user enters text into it. As it turns out, in the following code ad.show() //dialog.show return pl.getPromptReply(); // listener.getpromptReply()

the show() method will invoke the dialog asynchronously. This means the getPromptReply() method gets called for the prompt value before the user has time to enter text and click the OK button. This fallacy takes us to the heart of the nature of Android dialogs.

0 0

Post a comment