Tuesday, August 26, 2014

Dialogs

There are three ways to implement a dialog in Android
  • Using the Dialog class (or its extensions)
  • Dialog-themed Activities
  • Toasts
Introducing the Dialog Classes

Dialog d = new Dialog(MyActivity.this);
// Have the new window tint and blur the window it obscures.
Window window = d.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

// Set the title
d.setTitle("Dialog Title");
// Inflate the layout
d.setContentView(R.layout.dialog_view);
// Find the TextView used in the layout
// and set its text value
TextView text = (TextView)d.findViewById(R.id.dialogTextView);
text.setText("This is the text in my dialog");

d.show();

The Alert Dialog Class

It offers a number of options
  • Presenting a message to the user offering them one to three options in the form of buttons
  • Offering a list of options in the form of checkboxes or radio buttons
  • Providing a text entry box for user input
AlertDialog.Builder ad = new AlertDialog.Builder(context);

Configuring an Alert Dialog

Context context = MyActivity.this;
String title = "It is Pitch Black";
String message = "You are likely to be eaten by a grue.";
String button1String = "Go Back";
String button2String = "Move Forward";
AlertDialog.Builder ad = new AlertDialog.Builder(context);

ad.setTitle(title);
ad.setMessage(message);

ad.setPositiveButton("OK",new OnClickListener() 
                                   {
                                        public void onClick(DialogInterface dialog, int whichButton) {
                                              eatenByGrue();
                                          }
});

ad.setNegativeButton("Cancel",
            new onClickListener(){
              public void onClick(DialogInterface dialog, int whichButton)         {
                    // do nothing
              }
});

CharSequence[] items = { “Google”, “Apple”, “Microsoft” };

boolean[] itemsChecked = new boolean [items.length];

ad.setMultiChoiceItems(items, itemsChecked, 
            new onMultiChoiceClickListener()
              public void onClick(DialogInterface dialog, int which, boolean isChecked)         {
                    // do nothing
              }
});

ad.setCancelable(true);

ad.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
eatenByGrue();
}
});

ad.show();  (or) ad.create();


Progress Dialog

This displays the progress dialog. Because this is a modal dialog, it will block the UI until it is dismissed.
Note: There is no OK/CANCEL buttons on this dialog.

public void onClick(View v) {
// ---show the dialog---
final ProgressDialog dialog = ProgressDialog.show(this,
"Doing something", "Please wait...", true);
new Thread(new Runnable() {
public void run() {
try {
// ---simulate doing something lengthy---
Thread.sleep(5000);
// ---dismiss the dialog---
dialog.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}



Progress Dialog (with percentage of processing left)

Note: No show or create method is invoked on progressDialog like on an alertDialogInstance

 ProgressDialog progressDialog;

public void onClick3(View v) {
showDialog(1);        
        progressDialog.setProgress(0);        
        
        new Thread(new Runnable(){
   public void run(){
    for (int i=1; i<=15; i++) {
   try {
    //---simulate doing something lengthy---
       Thread.sleep(1000);
       //---update the dialog---
       progressDialog.incrementProgressBy((int)(100/15));
} catch (InterruptedException e) {
   e.printStackTrace();
}
    }
       progressDialog.dismiss();
}
}).start();
}


@Override
protected Dialog onCreateDialog(int id) { 
switch (id) {
case 1:
            progressDialog = new ProgressDialog(this);
            progressDialog.setIcon(R.drawable.ic_launcher);
            progressDialog.setTitle("Downloading files...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", 
            new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog,
               int whichButton)
               {
                   Toast.makeText(getBaseContext(),
                           "OK clicked!", Toast.LENGTH_SHORT).show();
               }
            });
            progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", 
                new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog,
                   int whichButton)
               {
                   Toast.makeText(getBaseContext(),
                           "Cancel clicked!", Toast.LENGTH_SHORT).show();
               }
            });
            return progressDialog;
}
return null;
}



Specialist Input Dialogs

One of the major uses of dialog boxes is to provide an interface for user input

CharacterPickerDialog
DatePickerDialog
TimePickerDialog
ProgressDialog


Dialog-themed activities

There will still be times when you need more control over the content and life cycle of your dialog box

<activity android:name="MyDialogActivity"
           android:theme="@android:style/Theme.Dialog">
</activity>

public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     //---hides the title bar---
     requestWindowFeature(Window.FEATURE_NO_TITLE);
     setContentView(R.layout.main);
     Log.d(tag, “In the onCreate() event”);
}

Managing and Displaying Dialogs

Android provides the onCreateDialog and onPrepareDialog event handlers within the Activity class to persist and manage dialog-box instances.

The onCreateDialog() method is a callback for creating dialogs that are managed by the activity.
When you call the showDialog() method, this callback will be invoked.
The showDialog() method accepts an integer argument identifying a particular dialog to display

By overriding the onCreateDialog handler you can specify dialogs that will be created on demand when showDialog is used to display a specific dialog.

static final private int TIME_DIALOG = 1;
@Override
    public Dialog onCreateDialog(int id) 
    {
        switch(id) {
            case (TIME_DIALOG) :
            AlertDialog.Builder timeDialog = new                           AlertDialog.Builder(this);
            timeDialog.setTitle("The Current Time Is...");
            timeDialog.setMessage("Now");
            return timeDialog.create();
        }
        return null;
    }

After the initial creation, each time showDialog is called it will trigger the onPrepareDialog handler.

@Override
public void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case (TIME_DIALOG):
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
Date currentTime = new Date(java.lang.System.currentTimeMillis());
String dateString = sdf.format(currentTime);
AlertDialog timeDialog = (AlertDialog) dialog;
timeDialog.setMessage(dateString);
break;
}
}

showDialog(TIME_DIALOG);

No comments:

Post a Comment