Android notes: Android UI learning-dialog box (alertdialog & progressdialog)

Source: Internet
Author: User
Tags switch case

This article simplifies some content in the online article "android Development Guide-User Interface-dialog box" and adds some of your own understandings. The same content is copyrighted by the original author.

Show dialog box

A dialog box is often created and displayed as part of an activity. You shouldProtected dialog activity. oncreatedialog (int id)
The create dialog box in the callback method. When you use this callback function, the android system will effectively set this activity as the owner of each dialog box to automatically manage the status of each dialog box and attach it to the activity. In this way, each dialog box inherits the specific attributes of this activity. For example, when a dialog box is opened, the menu key displays the option menu defined for the activity, and the volume key modifies the audio stream used by the activity.

 
 
  1. Note: If you decide to create a dialog box outside the oncreatedialog () method, it will not be attached to the activity. However, you can use setowneractivity to attach it to an activity.

To display a dialog box, call the showdialog (int id) method and pass an integer that uniquely identifies the dialog box.

When the dialog box is requested for the first time, Android calls oncreatedialog (int id) from your activity. You should initialize the dialog box dialog here. This callback method is passed to the same ID as showdialog (int id. After you create this dialog box, return this object at the end of the activity.

Before the dialog box is displayed, Android also calls the optional callback function onpreparedialog (int id, DIALOG). If youYou can define this method to change any of its attributes when each dialog box is opened.. This methodCalled each time a dialog box is opened, AndOncreatedialog (INT) is called only when the dialog box is opened for the first time..If you do not define onpreparedialog (), this dialog box will remain the same as the previous one.. This method is also passed with the dialog box ID and the dialog box object created in oncreatedialog. (In my personal understanding, when I show a dialog for the first time in this activity, I will first call oncreatedialog to obtain the returned dialog object and link it to the activity to save the reference of the dialog object before displaying the dialog. This way, next time show
The dialog object does not need to be re-created, but the old one is reused)

DefinitionOncreatedialog (INT)AndOnpreparedialog (INT, DIALOG)The best way to use a callback function is to use a switch statement to check the passed ID parameter. Each case should check a unique dialog box ID and then create and define the corresponding dialog box. For example, imagine that a game uses two different dialogs: one to indicate that the game has been suspended and the other to indicate that the game has ended. First, define a constant for each dialog box:

 
 
  1. static final int DIALOG_PAUSED_ID = 0; 
  2. static final int DIALOG_GAMEOVER_ID = 1; 

Then, define the oncreatedialog (INT) callback function for each ID using a switch case:

 
 
  1. protected Dialog onCreateDialog(int id) { 
  2.     Dialog dialog; 
  3.     switch(id) { 
  4.     case DIALOG_PAUSED_ID: 
  5.         // do the work to define the pause Dialog 
  6.         break; 
  7.     case DIALOG_GAMEOVER_ID: 
  8.         // do the work to define the game over Dialog 
  9.         break; 
  10.     default: 
  11.         dialog = null; 
  12.     } 
  13.     return dialog; 

When one of the dialog boxes is displayed, use the dialog box ID to call showdialog (INT ):

 
 
  1. showDialog(DIALOG_PAUSED_ID); 
Delete dialog box dismissing a dialog

When you are about to close the dialog box, you can call dismiss ()To eliminate it. If needed, you can also call the dismissdialog (int id) method from this activity, which will actually call the dismiss () method for this dialog box.

If you want to use oncreatedialog (int id)
Method to manage the status of your dialog box (as discussed in the previous chapter). Each time your dialog box is cleared, the status of this dialog box object will be retained by this activity. If you decide that you no longer need this object or clear the state, you should call removedialog (int id ). This will delete any internal object reference. If this dialog box is displayed, it will be removed.

Use the using dismiss listeners

If you want your application to execute some processes when a dialog box disappears, you should attach an on-dismiss listener to the dialog box.

 
 
  1. @Override 
  2. protected void onPrepareDialog(int id, Dialog dialog) { 
  3.     switch(id){ 
  4.     case PROGRESS_DIALOG: 
  5.         dialog.setOnDismissListener(new DialogInterface.OnDismissListener(){ 
  6.             @Override 
  7.             public void onDismiss(DialogInterface dialog) { 
  8.                 Toast.makeText(getApplicationContext(), 
  9.                         "dismiss listener!", 
  10.                         Toast.LENGTH_SHORT) 
  11.                 .show(); 
  12.             } 
  13.         }); 
  14.     } 

However, note that the dialog box can also be canceled ". This is a special case that indicates that the dialog box is canceled by the user. This will occur when you press the "return" button, or the cancel () call shown in this dialog box (maybe through a "cancel" button on the dialog box ). When a dialog box is canceled, this ondismisslistener will still be notified, but if you want to be notified when the dialog box is canceled (rather than the usual elimination method ), you should register a dialoginterface through setoncancellistener. oncancellistener
.

Currently, personal learning has found that, generally, calling dialog. Cancel () triggers oncancellister. Clicking the negativebutton (cancel/no) of alertdialog will not trigger. For setoncancellistener (), note that there are two setoncancellistener (), but the return values are different:

 
 
  1. // Called by alertdialog. Builder
  2. Public alertdialog. Builder setoncancellistener (dialoginterface. oncancellistener)
  3.  
  4. // Called by Dialog
  5. Public void setoncancellistener (dialoginterface. oncancellistener listener)
Warning dialog box alertdialog usage

To create a warning dialog box, use the alertdialog. Builder subclass. Use alertdialog. Builder (context) to obtain a constructor and use the public methods of this class to define all the attributes of the warning dialog box. After obtaining the constructor, you can use the CREATE (). method to obtain the alert dialog box object. Sometimes I do not call create (), but call show () to display alertdialog after setting.

Add button adding buttons

This is what I want to know at first how to add a button like yes/no, OK/cancel. It turned out to be through setpositivebutton (...) in response to the yes/OK click, setneutralbutton (...) response to the neutral click, setnegativebutton (...) respond to the No/cancel click. Note: Only one button can be set to respond to the click event.

 
 
  1. AlertDialog.Builder builder = new AlertDialog.Builder(this); 
  2. builder.setMessage("Are you sure you want to exit?") 
  3.        .setCancelable(false) 
  4.        .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
  5.            public void onClick(DialogInterface dialog, int id) { 
  6.                 MyActivity.this.finish(); 
  7.            } 
  8.        }) 
  9.        .setNegativeButton("No", new DialogInterface.OnClickListener() { 
  10.            public void onClick(DialogInterface dialog, int id) { 
  11.                 dialog.cancel(); 
  12.            } 
  13.        }); 
  14. AlertDialog alert = builder.create(); 

First, add a message setmessage (charsequence) to this dialog box ). Then, start function chain and set this dialog box to not canceled not cancelable (Therefore, you cannot use the return button to close this dialog box.). For each button, use any set... button () method, such as setpositivebutton (). This method accepts the button name and a dialoginterface. onclicklistener that defines the action taken after the selected button.

Add a list adding a list
 
 
  1. final CharSequence[] items = {"Red", "Green", "Blue"}; 
  2.   
  3. AlertDialog.Builder builder = new AlertDialog.Builder(this); 
  4. builder.setTitle("Pick a color"); 
  5. builder.setItems(items, new DialogInterface.OnClickListener() { 
  6.     public void onClick(DialogInterface dialog, int item) { 
  7.         Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); 
  8.     } 
  9. }); 
  10. AlertDialog alert = builder.create(); 

First, use the settitle (charsequence) method to add a title to the dialog box. Then, you can use setitems () to add an Option List that accepts a set of displayed items and a dialoginterface. onclicklistener to define the actions taken after the selected button.

Add check box and radio button

To create a checkboxes or radio buttons in the dialog box, you can call setmultichoiceitems () and setsinglechoiceitems () respectively ()
Method. If you create these optional lists in the oncreatedialog () callback function, Android will help you manage the list status. As long as this activity is activated, the dialog box will remember the previously selected items, but if the user exits this activity, the user will lose the selection.

Note: To save the selection when the user leaves or suspends the activity, you must use the activity lifecycle to properly save and restore the settings. To save the option permanently, you need to use data storage technology even if the active process is completely terminated.

 
 
  1. final CharSequence[] items = {"Red", "Green", "Blue"}; 
  2.   
  3. AlertDialog.Builder builder = new AlertDialog.Builder(this); 
  4. builder.setTitle("Pick a color"); 
  5. builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { 
  6.     public void onClick(DialogInterface dialog, int item) { 
  7.         Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show(); 
  8.     } 
  9. }); 
  10. AlertDialog alert = builder.create(); 

The second parameter of setsinglechoiceitems () is a checkeditem integer value, indicating the position of the default selection item based on 0. "-1" indicates that no default options are available.

Usage of progress dialog in the Progress dialog box

Progressdialog is an extension of the alertdialog class. It can display a progress animation in the rotation wheel shape for an undefined progress task, or display a progress bar for a task with a specified progress.

You can call progressdialog. Show () to display a progress dialog box. The oncreatedialog (INT) callback management dialog box is optional, as shown below:

 
 
  1. Progressdialog. Show (this, // Context
  2. "", // Title
  3. "Loading. Please wait...", // message
  4. True); // whether the progress is uncertain. This is only related to creating a progress bar.

The default type of the Progress dialog box is a rotating wheel. The running result is as follows:

Because progressdialog is an extension class of alertdialog, progressdialog can also be set as a button, for example, a cancel Download button. However, it should be noted that, with the previous alertdialog. different from builder, progressdialog calls the setbutton, setbutton2, and setbutton3 functions of alertdialog. It is up to us to determine which functions are positive, neutral, or negative.

Show progress bar showing a progress bar

Select the animation progress bar to display the progress:

1. Use the class constructor to initialize the progress dialog box, progressdialog (context ).

2. Use setprogressstyle (INT) to set the progress style to "style_horizontal" and set other attributes, such as messages.

The following figure shows how to create progressdialog:

 
 
  1. ProgressDialog progressDialog = new ProgressDialog(getApplicationContext());  
  2.   
  3. progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  4. progressDialog.setIcon(R.drawable.alert_dialog_icon);  
  5. progressDialog.setMessage("Loading...");  
  6. progressDialog.setCancelable(false);  

3. When you are about to display this dialog box, call show () or return progressdialog from the oncreatedialog (INT) callback.

4. You can call setprogress (INT) to set the current progress percentage or call the incrementprogressby (INT) method to increase the progress value.

The official documentation provides how to track progress in another thread and change the progress value. For more information, see the code in http://androidappdocs.appspot.com/guide/topics/ui/dialogs.html. You can also view the examples in the subsequent article "learning about Android Threads" to see how to use handler,
Message mechanism!

Create custom dialog box creating a custom Dialog

In the create custom dialog box, create a layout XML file. There are two methods to load layout:

1. setcontentview (INT resources ID)

2. Use layoutinflater to load

The official website also prompts us that the dialog class is generally used to create a dialog box, which requires settitle. If this parameter is not set, the space occupied by the title remains empty, but it is still visible. If you do not want the title, use the alertdialog alarm dialog box to create a custom dialog box. However, the warning dialog box can be easily implemented through alertdialog. builder.
Class, you do not need to access the setcontentview (INT) method used above. Instead, you must use setview (View) to load layout to get the view.

Specific code reference http://androidappdocs.appspot.com/guide/topics/ui/dialogs.html

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.