[Translation documentation] Android Dialog

Source: Internet
Author: User

Disclaimer: This article is translated from Guide/topics/UI/dialogs.html In the android SDK documentation.

 

A dialog is usually a small window in front of the current activity. When a dialog is displayed, the activity partially covered by the dialog will lose the focus, and all user operations will be handled by the dialog.

Android APIs support the following types of dialog objects:

Alertdialog -- allows you to add 0, 1, 2, or 3 buttons on it, and it can also contain a list of options (such as checkboxes or radio buttons. Correct use of alertdialog allows you to build most dialog interfaces.

Progressdialog -- used to display a progress wheel or a progress bar. Progressdialog is an extended alertdialog, so it naturally allows you to add a button on it.

Datepickerdialog -- allows users to select a time dialog.

Timepickerdialog -- allows users to select a time dialog.

How to display a dialog

A dialog is often created and displayed as a part of an activity. You should create a dialog in the oncreatedialog (INT) callback function of the activity you created. When you use this callback function, the android system automatically manages the status of each dialog and creates a connection between each dialog and the corresponding activity so that the corresponding activity becomes the "owner" of the corresponding dialog ". In this way, each dialog inherits certain attributes from the activity. For example, when a dialog is in the open state, you can press the menu key to display the menu you have defined for this activity.

Note: If you decide to create a dialog outside oncreatedialog (), the android system will not "Paste" it to an activity. If necessary, you can use the setowneractivity (activity) method to "Paste" a dialog to an activity.

When you want to display a dialog, call the showdialog (INT) method and pass it an integer that uniquely identifies the dialog you want to display.

When a dialog is requested for the first time, the android system will call the oncreatedialog (INT) method in your activity. You need to instantiate a dialog in this method body. Oncreatedialog is the same as showdialog, and you need to pass them a dialog ID. After creating a dialog object, let the oncreatedialog method return a reference to a dialog object.

Before the dialog is displayed, Android also calls onpreparedialog (INT, DIALOG ). This method is optional. If you want to change the dialog tree every time you open the dialog, You need to define this method. Android calls onpreparedialog (INT, DIALOG) each time the dialog is not opened, and oncreatedialog (INT) is called only when the dialog is opened for the first time ). If you write

Onpreparedialog (INT, DIALOG), the dialog will display the status of the last time the user opened it. This method also requires you to pass it a dialog ID, and you also need to pass it a reference to the dialog object that you created and returned using the oncreatedialog () method.

The best way to define the oncreatedialog (INT) and onpreparedialog (INT, DIALOG) callback functions is to use the switch statement to detect the passed-in ID real parameters. Each case should detect a unique dialog ID, and then create and define their own dialog objects. For example, assume you need a game program in two different dialogs. One dialog box indicates that the game has been suspended and the other two indicate that the game has ended.

First, define an ID for each dialog:

View plaincopy to clipboardprint?

Static final int dialog_pause_id = 0;

Static final int dialog_gameover_id = 1;

Static final int dialog_pause_id = 0;

Static final int dialog_gameover_id = 1;

Then, define the oncreatedialog (INT) method, which should contain the switch statement used to distinguish different dialog IDs:

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;}

Note: In the above example, there is no code in the case Branch statement, because this section does not describe the processing process for defining the dialog.

Next, it is time to display a dialog. Please call showdialog (INT) and pass it a dialog ID.

Showdialog (dialog_paused_id );

Showdialog (dialog_paused_id );

How to make a dialog disappear

When you want to close a dialog object, you can call the dismiss () method of the dialog object member method to pass it. If necessary, you can call dismisdialog (INT) from the activity that calls dismiss () for you ).

If you are using oncreatedialog (INT) to manage the dialog status, the activity will hold the status information of the dialog object every time your dialog disappears. If you really don't need this dialog object, or you really need to clear this state, you should call removedialog (INT ). This method will erase all internal references related to this object, and if the dialog is displayed, this method will dismiss this dialog.

How to Use the dismiss listener

If you want your application to do something when the dialog disappears, you should bind an on-dismiss listener to your dialog.

First, define the dialoginterface. ondismisslistener interface. This interface has only one method-ondismiss (dialoginterface). After the dialog disappears, the system will call this method. Then, you can pass the object that implements the ondismisslistener interface to setondismisslistener ().

Then, it is worth noting that the dialog can be canceled ). This is a special case where the dialog is displayed and canceled by the user. When the user presses the return key or closes the dialog or the application programmer shows that Cannel () is called (which may be called in the processing method that the "cancel" button in the dialog is pressed ), this will happen. When a dialog is in the canceled state, ondismisslistener will receive notifications from Android, but if you want android to be canceled (and not dismissed normally) in this dialog ), you must use the setoncancellistener () method to register
Dialoginterface. oncancellistener.

How to create an alertdialog

Alertdialog is an extension class of the dialog class. It can build many dialog user interfaces. Android also recommends that application programmers use alertdialog to build the dialog user interface. You can use it to build a dialog with any of the following attributes:

A title

A text message

One, two, or three buttons

A list of selectable items (with optional checkboxes or radio buttons)

To create an alertdialog, you need to use the alertdialog. Builder subclass. Use alertdialog. Builder (context) to obtain a builder, and then use the public method of the class to define all the attributes of alertdialog. After you have completed builder operations, call the CREATE () method to retrieve the alertdialog object.

The following describes how to use the alertdialog. Builder class to define various attributes of alertdialog. If you use any of the following code in the oncreatedialog () callback function, you can return the target dialog object with certain attributes you want to display.

Add button

If you want to build a dialog with a button, you need to call the set... button () method.

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) {                MyActivity.this.finish();           }       })       .setNegativeButton("No", new DialogInterface.OnClickListener() {           public void onClick(DialogInterface dialog, int id) {                dialog.cancel();           }       });AlertDialog alert = builder.create();

Call setmessage (charsequence) to add a prompt message to the dialog. Then, start method-chaining and call the setcancelable (Boolean) function to set this dialog to uncancable (you cannot press the return key to close this dialog ). Use set... add a button using the button () method. For example, you can use the string that is received on the button and the dialoginterface that is processed by the user by pressing the button. the setpositivebutton () method of the onclicklistener parameters adds a button for the dialog.

Note: you cannot add two "positive" buttons at the same time on a dialog. You can add up to three buttons on a single dialog: positive, neutral, and negative buttons.

Add list:

Use setitems () to add a list for alertdialog.

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();

 

First, call settitle (charsequence) to add a title for the dialog. Then, call setitems () to add a list for the dialog, which receives a set of items for display, and dialoginterface. onclicklistener processes different user choices.

Add checkboxes and radio buttons

To create a dialog with multiple-choice items (checkboxes) or single-choice items (radio buttons), you must use setmultichoiceitems () and setsinglechoiceitems () methods respectively. If you create these optional lists in oncreatedialog, Android will manage the list status for you. As long as the activity is active, the dialog will remember the previously selected items, but when the user leaves the current activity,
Selection will be lost.

Note: In order to save selection when the user leaves or suspends the activity, you must Sava and restore at appropriate times throughout the lifecycle of the activity.

The setting. If you want to permanently Save the selections, you need to use the data storage technology to save these setting.

To create an alertdialog with single-choice items, you can use the code segment that creates the alertdialog with lists. However, you must use setsinglechoiceitems () instead of setitems ().

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) {        Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();    }});AlertDialog alert = builder.create();

 

The second parameter of setsinglechoiceitems () is an integer indicating which list (zero-based) is selected by default. "-1" indicates that no item should be selected by default.

 

Create progressdialog

A processdialog is an extended alertdialog class. A dialog instantiated processdialog can display a progress bar and provide buttons, such as a button to cancel the download.

You only need to call progressdialog. Show () to open a progress dialog.

Progressdialog dialog = progressdialog. Show (myactivity. This ,"",

"Loading. Please wait...", true );

The first parameter is the context of the application, the second parameter is the title of the dialog (left blank), and the third parameter is the string displayed on the dialog, the last parameter identifies whether the SS is indeterminate (this is only related to the creation of the progress bar, which will be discussed in the following section ).

By default, the Progress dialog box displays the progress as a ring. If you want to create a progress bar that displays the download process, read the content.

Display progress bar

To display a progress bar with dynamic progress information, you need:

1. Call the ssdialog (context) constructor to initialize progressdialog.

2. Call setprogressstyle (INT) to set the style of the progress bar to style_horizontal. Of course, you can also set other attributes for this dialog, such as displaying a message on it.

3. When you are ready to display a dialog, you can call the show () method or return progressdialog from the oncreatedialog (INT) callback method.

4. you can call and pass an integer of the current total completion percentage to setprogress (INT), or call and pass an integer that you want to add to the current completed percentage to incrementprogressby (INT ).

For example, you may create progressdialog like this.

ProgressDialog progressDialog;progressDialog = new ProgressDialog(mContext);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("Loading...");progressDialog.setCancelable(false);

Most of the Code for creating progress dialog will create a thread for updating this progress dialog at the same time. To complete the task of updating progress dialog, You need to enable another thread in your application, and then use the handler object to pass the progress information to the UI thread of the activity. If you are not familiar with the newly added thread with handler, please refer to the following example of a new thread to update progress dialog.

Progressdialog that contains the new startup thread

This example uses a newly started thread to track the progress (in fact, it only accumulates the number to 100, the newly started thread uses handler to send a message to the main activity, and then the main acitalog updates progressdialog.

package org.vhow.android.ui.dialogs;import android.app.Activity;import android.app.Dialog;import android.app.ProgressDialog;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class Dialogs extends Activity{static final int PROGRESS_DIALOG = 0;Button button;ProgressThread progressThread;ProgressDialog progressDialog;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);// setup the button that starts the progress dialogbutton = (Button) findViewById(R.id.progressDialog);button.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){showDialog(PROGRESS_DIALOG);}});}@Overrideprotected Dialog onCreateDialog(int id){switch (id){case PROGRESS_DIALOG:progressDialog = new ProgressDialog(Dialogs.this);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("Loading...");progressThread = new ProgressThread(handler);progressThread.start();return progressDialog;default:return null;}}// Define the Handler that receives messages from the thread and update the// progressfinal Handler handler = new Handler(){public void handleMessage(Message msg){int total = msg.getData().getInt("total");progressDialog.setProgress(total);if (total >= 100){dismissDialog(PROGRESS_DIALOG);progressThread.setState(ProgressThread.STATE_DONE);}}};/*** Nested class that performs progress calculations(counting)*/private class ProgressThread extends Thread{Handler mHandler;final static int STATE_DONE = 0;final static int STATE_RUNNING = 1;int mState;int total;ProgressThread(Handler h){mHandler = h;}public void run(){mState = STATE_RUNNING;total = 0;while (mState == STATE_RUNNING){try{Thread.sleep(100);}catch (InterruptedException e){Log.e("ERROR", "Thread Interrupted");}Message msg = mHandler.obtainMessage();Bundle b = new Bundle();b.putInt("total", total);msg.setData(b);mHandler.sendMessage(msg);total++;}}/*** sets the current state for the thread, used to stop teh thread*/public void setState(int state){mState = state;}}}package org.vhow.android.ui.dialogs;import android.app.Activity;import android.app.Dialog;import android.app.ProgressDialog;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class Dialogs extends Activity{static final int PROGRESS_DIALOG = 0;Button button;ProgressThread progressThread;ProgressDialog progressDialog;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);// setup the button that starts the progress dialogbutton = (Button) findViewById(R.id.progressDialog);button.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v){showDialog(PROGRESS_DIALOG);}});}@Overrideprotected Dialog onCreateDialog(int id){switch (id){case PROGRESS_DIALOG:progressDialog = new ProgressDialog(Dialogs.this);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("Loading...");progressThread = new ProgressThread(handler);progressThread.start();return progressDialog;default:return null;}}// Define the Handler that receives messages from the thread and update the// progressfinal Handler handler = new Handler(){public void handleMessage(Message msg){int total = msg.getData().getInt("total");progressDialog.setProgress(total);if (total >= 100){dismissDialog(PROGRESS_DIALOG);progressThread.setState(ProgressThread.STATE_DONE);}}};/*** Nested class that performs progress calculations(counting)*/private class ProgressThread extends Thread{Handler mHandler;final static int STATE_DONE = 0;final static int STATE_RUNNING = 1;int mState;int total;ProgressThread(Handler h){mHandler = h;}public void run(){mState = STATE_RUNNING;total = 0;while (mState == STATE_RUNNING){try{Thread.sleep(100);}catch (InterruptedException e){Log.e("ERROR", "Thread Interrupted");}Message msg = mHandler.obtainMessage();Bundle b = new Bundle();b.putInt("total", total);msg.setData(b);mHandler.sendMessage(msg);total++;}}/*** sets the current state for the thread, used to stop teh thread*/public void setState(int state){mState = state;}}

 

 

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.