Android Development guide Chinese version (12) User Interface-dialogs

Source: Internet
Author: User
Tags case statement switch case
Dialogs

A dialog box is usually a small window before the current activity. The following activities lose focus and the dialog box accepts all user interactions. A dialog box is usually used as a short activity related to a notification or running application.

Android API supports the following dialog box object types:

  • Warning dialog box alertdialog
    This dialog box manages 0, 1, 2, or 3 buttons, and/or a list of options that can contain check boxes and radio buttons. This warning dialog box can form most user interfaces and is a recommended dialog box type.
  • Progress dialog box progressdialog
    Displays a progress wheel or progress bar. Therefore, it is an extension of the warning dialog box, and it also supports buttons.
  • Date selection dialog box datepickerdialog
    A dialog box that allows users to select a date.
  • Time Selection dialog box timepickerdialog
    A dialog box that allows users to select a time.

If you want to customize your own dialog box, you canDialogObject or any subclass dialog box listed above to expand and define a new layout.

Showing a dialog

A dialog box is often created and displayed as part of an activity. You should usually create a dialog box from the oncreatedialog (INT) callback method of the activity. When you use this callback function, the android system will effectively set this activity as the owner of each dialog box, so as to automatically manage the status of each dialog box and link 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 this activity, and the volume key modifies the audio stream used by the activity.

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) 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) from your activity. You should initialize the dialog box dialog here. This callback method is passed to the same ID as showdialog (INT. After you create this dialog box, return this object at the end of the method.

Before the dialog box is displayed, Android also calls the optional callback function onpreparedialog (INT, DIALOG ). if you want to change any of its attributes when each dialog box is opened, you can define this method. This method is called each time a dialog box is opened, while oncreatedialog (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.

The best way to define the oncreatedialog (INT) and onpreparedialog (INT, DIALOG) callback functions 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 an integer for each dialog box:

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

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

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 this example, the case statement has no specific content, because it is beyond the scope of this chapter.

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

showDialog(DIALOG_PAUSED_ID);
Dismissing a dialog

When you want to close the dialog box, you can call dismiss () to delete it. If needed, you can also call the dismissdialog (INT) method from this activity, which will actually call the dismiss () method for this dialog box.

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

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.

First, define the dialoginterface. ondismisslistener interface. This interface has only one method, ondismiss (dialoginterface), which will be called when the dialog box disappears. Then, pass your ondismisslistener to setondismisslistener ().

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.

Creating an alertdialog

A warning dialog box is an extension class of the dialog box. It can build most Dialog Box user interfaces and is a recommended dialog box type. You should use it when you have the following features:

  • A title
  • One text message
  • 1, 2, or 3 buttons
  • A list of Optional options (optional check boxes or single-choice buttons)

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.

The following describes how to use the alertdialog. Builder class to define different warning dialog box attributes. If you use the following code in the oncreatedialog () callback function, you can return the result dialog box object to display it.

Adding buttons

To create a warning dialog box containing parallel buttons as shown in, use 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();

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.

Note: You can only add one of the button types for this warning dialog box. That is, you cannot include multiple "OK" buttons. This limits the number of possible buttons to only three: positive, neutral, and negative ). These names are technically irrelevant to the actual functions of your buttons, but they should help you record what you have done.

Adding a list

To create a warning dialog box with a list of options, you can use the setitems () method as follows:

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, 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.

Adding checkboxes and radio buttons

To create a checkboxes or radio buttons in the dialog box, call the setmultichoiceitems () and setsinglechoiceitems () methods respectively. 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.

To create a warning dialog box containing the list of single options shown in the following edge, use the same code in the preceding example, but replace the setitems () method with setsinglechoiceitems ().

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 a checkeditem integer value, indicating the location of the default option with the minimum selection value of 0. "-1" indicates that no default options are available.

Creating a progressdialog

The progress dialog box progressdialog is an extension of the alertdialog class. It displays a progress animation in the rotation wheel shape for an undefined progress task or a progress bar for a specified progress task. This dialog box also provides buttons, such as a button to cancel the download.

You can simply call progressdialog. Show () to display a progress dialog box. For example, you can easily get the progress dialog box shown below, instead of using the oncreatedialog (INT) callback to manage this dialog box, as shown below:

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",                                      "Loading. Please wait...", true);

The first parameter is the context of the application, the second is the dialog box title (null here), and the third is the information, finally, this parameter indicates whether the progress is uncertain (this is only related to the creation progress bar, which will be described in the next chapter ).

The default type of the Progress dialog box is a rotation wheel. If you want to create an interval progress, you need more code, as described in the following chapter.

Showing a progress bar

Use 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.
    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.

For example, your settings may look like this:

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

The setting is simple. Most of the Creation code is also used to update the progress. You may realize that it is necessary to create another thread to complete the progress report. The progress is returned to the active user interface thread through an object. If you are not familiar with how to use another thread through a handler, see the following example:

In this example, another thread is used to track the process progress (counting to 100 ). This thread sends back a message with a handle handler each time it updates the progress. Main activity and then update progress dialog box.

package com.example.progressdialog;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.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class NotificationTest extends Activity {    static final int PROGRESS_DIALOG = 0;    Button button;    ProgressThread progressThread;    ProgressDialog progressDialog;      /** Called when the activity is first created. */    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);                // Setup the button that starts the progress dialog        button = (Button) findViewById(R.id.progressDialog);        button.setOnClickListener(new OnClickListener(){            public void onClick(View v) {                showDialog(PROGRESS_DIALOG);            }        });     }    protected Dialog onCreateDialog(int id) {        switch(id) {        case PROGRESS_DIALOG:            progressDialog = new ProgressDialog(NotificationTest.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 progress    final 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 the thread          */        public void setState(int state) {            mState = state;        }    }}
Creating a custom Dialog

If you want to customize the dialog box, you can create your own layout and part elements for the dialog box window. After you define the layout, pass the root view object or layout resource ID to the setcontentview (View) method.

For example, create a dialog box as shown in:

    1. Create an XML layout and save it as custom_dialog.xml:
      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"              android:id="@+id/layout_root"              android:orientation="horizontal"              android:layout_width="fill_parent"              android:layout_height="fill_parent"              android:padding="10dp"              >    <ImageView android:id="@+id/image"               android:layout_width="wrap_content"               android:layout_height="fill_parent"               android:layout_marginRight="10dp"               />    <TextView android:id="@+id/text"              android:layout_width="wrap_content"              android:layout_height="fill_parent"              android:textColor="#FFF"              /></LinearLayout>

      This XML defines an imageview and a textview in a linearlayout.

    2. Set the layout above as the content view of the dialog box and define the content for the imageview and textview elements:
      Context mContext = getApplicationContext();Dialog dialog = new Dialog(mContext);dialog.setContentView(R.layout.custom_dialog);dialog.setTitle("Custom Dialog");TextView text = (TextView) dialog.findViewById(R.id.text);text.setText("Hello, this is a custom dialog!");ImageView image = (ImageView) dialog.findViewById(R.id.image);image.setImageResource(R.drawable.android);

      After the dialog box is instantiated, use setcontentview (INT) to set your custom layout as the content view of the dialog box, and use the layout resource ID as the parameter. Now this dialog box has a defined layout. You can use the findviewbyid (INT) method to capture view objects from the layout.

    3. That's it. You can now display this dialog box.

The dialog box created in the base class dialog box must have a title. If you do not call settitle (), the space occupied by the title remains empty, but it is still visible. If you do not want a title at all, you should use the warning dialog box alertdialog to create your custom dialog box. However, the warning dialog box can be easily created using the alertdialog. Builder class. You do not need to access the setcontentview (INT) method used above. Instead, you must use setview ). This method accepts a view object, so you need to expand the Root View of the layout in XML.

To expand the XML layout, use getlayoutinflater () or getsystemservice () to obtain layoutinflater, and then call inflate (INT, viewgroup ), the first parameter is the layout resource ID, and the second parameter is the root view ID. Here, you can use the expanded layout to find the view object and define the content for the imageview and textview elements. Then instantiate alertdialog. builder and call setview to set the expanded layout for the dialog box.

The following is an example of creating a custom Layout in a warning dialog box:

AlertDialog.Builder builder;AlertDialog alertDialog;Context mContext = getApplicationContext();LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);View layout = inflater.inflate(R.layout.custom_dialog,                               (ViewGroup) findViewById(R.id.layout_root));TextView text = (TextView) layout.findViewById(R.id.text);text.setText("Hello, this is a custom dialog!");ImageView image = (ImageView) layout.findViewById(R.id.image);image.setImageResource(R.drawable.android);builder = new AlertDialog.Builder(mContext);builder.setView(layout);alertDialog = builder.create();

Using the warning dialog box in your custom layout allows you to use the built-in features of the warning dialog box, such as management buttons, optional lists, titles, and icons.

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.