Download presentation
Presentation is loading. Please wait.
Published byDean Cutts Modified over 9 years ago
1
Copyright© Jeffrey Jongko, Ateneo de Manila University Dialogs, Custom Dialogs, Toasts
2
Overview Dialog concepts Built-in Dialogs Custom Dialogs Toasts
3
Copyright© Jeffrey Jongko, Ateneo de Manila University Dialogs Concepts
4
Dialogs A dialog is a modal input type You must finish with the dialog before proceeding with anything else Android provides Activity instances with a way to automatically manage dialogs and their life-cycle
5
showDialog() Dialogs are triggered using the showDialog(int id) method The Dialog ID is an arbitrary integer used to identify a specific dialog usually stored as a constant E.g. DATE_DIALOG_ID
6
Dialog ID Each dialog that shows from an Activity must have a unique dialog id This id will be used in onCreateDialog(int id) and onPrepareDialog(int id) methods These will be used in switch() statements to handle specific dialogs
7
onCreateDialog() When a dialog is created for the first time onCreateDialog(int id) is called This method returns the specific Dialog instance that will displayed Once a dialog has been created, the instance is kept by the Activity Any changes done to the dialog’s state is preserved
8
Example For every dialog type and entry should appear here Note the use of constants protected Dialog onCreateDialog(int id) { Dialog dialog; switch(id) { case DIALOG_PAUSED_ID: // do the work to define the pause Dialog break; case DIALOG_GAMEOVER_ID: // do the work to define the game over Dialog break; default: dialog = null; } return dialog; }
9
onPrepareDialog() Once a dialog is created the instance is kept by the Activity until it is dismissed (see later) However, there are times you will want to reset the state of the existing dialog onPrepareDialog(int id, Dialog d) is called every time a dialog is activated You can then typecast and adjust the Dialog supplied accordingly each time it is opened
10
Example If you need to reset the state of an existing dialog, place an entry here for the dialogs that need it protected void onPrepareDialog(int id, Dialog d) { switch(id) { case DIALOG_PAUSED_ID: // adjust pause Dialog break; case DIALOG_GAMEOVER_ID: // adjust the game over Dialog break; } }
11
Copyright© Jeffrey Jongko, Ateneo de Manila University Built-in Dialogs
12
Built-in Dialogs DatePickerDialog TimePickerDialog AlertDialog ProgressDialog
13
DatePickerDialog Standard widget for selecting a date, use the DatePicker widget (usable from the GraphicalEditor), which allows the user to select the month, day, and year, in a familiar interface.DatePicker A Dialog-based version is also available, DatePickerDialog
14
DatePickerDialog DatePickerDialog follows the same basic principles of dialogs Define an ID representing this dialog Use showDialog(id) Instantiate the dialog in onCreateDialog(id) In addition define its close behaviour Prep the dialog in onPrepareDialog(id, dialog)
15
OnDateSetListener You need to define the close behaviour of a DatePickerDialog This is the DatePickerDialog.OnDateSetListener Defines one method public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
16
Example private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDisplay(); } }; protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; }
17
Calendar objects Java’s basic date/time handling class is the Calendar object Allows for the setting and retrieving information about date/time using simple constants Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH);
18
Calendar A detailed description of Calendar’s methods and constants can be found here file:///C:/android-sdk- windows/docs/reference/java/util/Calendar.html file:///C:/android-sdk- windows/docs/reference/java/util/Calendar.html
19
TimePickerDialog TimePicker is similar to the DatePicker except it is used to handle hour/minute, time of day TimePickerDialog is the dialog version of the TimePicker Just like with the DatePickerDialog you can use a Calendar object to hold data received from this dialog
20
OnTimeSetListener private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int hourOfDay, int minute) { mHour = hourOfDay; mMinute = minute; updateDisplay(); } }; protected Dialog onCreateDialog(int id) { switch (id) { case TIME_DIALOG_ID: return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false); } return null; }
21
Copyright© Jeffrey Jongko, Ateneo de Manila University AlertDialog
22
AlertDialog An AlertDialog is an extension of the Dialog class. It is capable of constructing most dialog user interfaces and is the suggested dialog type. You should use it for dialogs that use any of the following features:AlertDialogDialog A title A text message One, two, or three buttons A list of selectable items (with optional checkboxes or radio buttons)
23
AlertDialog.Builder AlertDialogs are created using the AlertDialog.Builder class Using the builder you may supply the required information Title, button names, etc. The final Dialog instance is built using the create() method
24
Example 1 AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to exit?").setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // positive action exit() } }).setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // negative action dialog.cancel(); } }); AlertDialog alert = builder.create();
25
Example 2 final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); } }); AlertDialog alert = builder.create();
26
Example 3 final CharSequence[] items = {"Red", "Green", "Blue"}; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Pick a color"); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { // do something } }); AlertDialog alert = builder.create(); To use checkboxes, use setMultiChoiceItems() instead
27
Notes: Note the getApplicationContext() calls in defining DialogInterface.OnClickListener Retrieves the Activity instance Can’t use this since it will refer to the DialogInterface.OnClickListener instance Lists of strings do not need to be hard-coded, they can also be placed in the values
28
ProgressDialog A ProgressDialog is an extension of the AlertDialog class that can display a progress animation in the form of a spinning wheel, for a task with progress that's undefined, or a progress bar, for a task that has a defined progressionProgressDialogAlertDialog Used in conjunction with Threads This will be discussed in later topics
29
Copyright© Jeffrey Jongko, Ateneo de Manila University Custom Dialogs
30
CustomDialogs Generally AlertDialog is all you will need for most Dialog requirements If you can get away with AlertDialog use it If AlertDialog does not provide what you need, it is possible to define your own Dialog layout The process is similar to defining an Activity layout
31
Making your own Dialog If you want a customized design for a dialog, you can create your own layout for the dialog window with layout and widget elements. After you've defined your layout, pass the root View object or layout resource ID to setContentView(View).setContentView(View) Use a LayoutInflator similar to a MenuInflator to create a ViewGroup from a layout XML Use the ViewGroup’s findViewById(id) to edit individual widgets
32
dismiss() / dismissDialog() When you're ready to close your dialog, you can dismiss it by calling dismiss() on the Dialog object.dismiss() Alternatively, you can also call dismissDialog(int) from the Activity, which effectively calls dismiss() on the Dialog for you. dismissDialog(int)dismiss()
33
OnDismissListener Sometimes you want to do something as a result of dismissing a dialog First define the DialogInterface.OnDismissListener interface.DialogInterface.OnDismissListener This interface has just one method,onDismiss(DialogInterface), which will be called when the dialog is dismissed.onDismiss(DialogInterface) pass your OnDismissListener implementation to setOnDismissListener() of the dialog when you create itsetOnDismissListener()
34
Cancelling a Dialog However, note that dialogs can also be "cancelled." This is a special case that indicates the dialog was explicitly cancelled by the user. This will occur if the user presses the "back" button to close the dialog if the dialog explicitly calls cancel() (perhaps from a "Cancel" button in the dialog).cancel()
35
OnCancelListener When a dialog is cancelled, the OnDismissListener will still be notified, but if you'd like to be informed that the dialog was explicitly cancelled (and not dismissed normally), then you should register an DialogInterface.OnCancelListener with setOnCancelListener()DialogInterface.OnCancelListener setOnCancelListener()
36
removeDialog() If you are using onCreateDialog(int) to manage the state of your dialogs, then every time your dialog is dismissed, the state of the Dialog object is retained by the Activity.onCreateDialog(int) If you decide that you will no longer need this object or it's important that the state is cleared, then you should call removeDialog(int)removeDialog(int)
37
More Info More details on custom dialogs can be found here file:///C:/android-sdk- windows/docs/guide/topics/ui/dialogs.html
38
Copyright© Jeffrey Jongko, Ateneo de Manila University Toasts
39
Toasts A Toast what is used to represent a “pop-up” message Toasts cannot be interacted with They just display the message embedded in them for a specified amount of time then disappear Cancel and other button do not do anything
40
Creating a Toast To instantiate a Toast object use one of the makeText() methods.ToastmakeText() This method takes three parameters: the application Context (usually the Activity), the text message, and the duration for the toast.Context It returns a properly initialized Toast object.
41
Toasts Toasts are usually used to display simple messages E.g. Validation errors Toasts have two possible fixed durations Toast.LENGTH_LONG Toast.LENGTH_SHORT Messages should be short enough to read in this time frame
42
Example Once a Toast instance is created you may make it appear using show() The context parameter is the enclosing Activity Toast toast = Toast.makeText(this, “Hello”, Toast.LENGTH_SHORT); toast.show();
43
Positioning Toasts A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. setGravity(int, int, int) This accepts three parameters: a Gravity constant (anchor), an x-position offset, and a y-position offset from the upper left.Gravity toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
44
Custom Toasts Custom toasts can be created The process is similar to creating a custom dialog file:///C:/android-sdk- windows/docs/guide/topics/ui/notifi ers/toasts.html file:///C:/android-sdk- windows/docs/guide/topics/ui/notifi ers/toasts.html
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.