Android 開發指南 翻譯 User Interface -- Dialogs

User Interface -- Dialogs

A dialog is usually a small window that appears in front of the current Activity. The underlying Activity loses focus and the dialog accepts all user interaction. Dialogs are normally used for notifications that should interupt the user and to perform short tasks that directly relate to the application in progress (such as a progress bar or a login prompt).

對話框是出現在Activity前面的小窗口。其下面的Activity失去焦點,對話框接收所有用戶操作。對話框通常用來通知用戶,要去執行一個任務。

The Dialog class is the base class for creating dialogs. However, you typically should not instantiate a Dialog directly. Instead, you should use one of the following subclasses:

Dialog是對話框的基礎類,然而,你通常不需要實例化Dialog,而是使用下面的子類:

AlertDialog
A dialog that can manage zero, one, two, or three buttons, and/or a list of selectable items that can include checkboxes or radio buttons. The AlertDialog is capable of constructing most dialog user interfaces and is the suggested dialog type. SeeCreating an AlertDialog below.

    AlertDialog可以有零個、一個、兩個或三個按鈕,一組包括複選框、單選框的可選項。AlertDialg是最常用的用戶接口對話框。

ProgressDialog

A dialog that displays a progress wheel or progress bar. Because it's an extension of the AlertDialog, it also supports buttons. See Creating a ProgressDialog below.

    ProgressDialog顯示一個旋轉圖標或進度條。因爲擴展自AlertDialog,所以也支持按鈕。

DatePickerDialog

A dialog that allows the user to select a date. See the Hello DatePicker tutorial.

    允許用戶選擇日期的對話框。

TimePickerDialog

A dialog that allows the user to select a time. See the Hello TimePicker tutorial.

    允許用戶選擇時間的對話框。

If you would like to customize your own dialog, you can extend the base Dialog object or any of the subclasses listed above and define a new layout. See the section on Creating a Custom Dialog below.

如果想自定義對話框,應該擴展Dialog類或任何子類,定義一個新的佈局。

Dialog Design

For design guidelines, read Android Design's Dialogs guide.

Showing a Dialog 顯示對話框

A dialog is always created and displayed as a part of an Activity. You should normally create dialogs from within your Activity's onCreateDialog(int) callback method. When you use this callback, the Android system automatically manages the state of each dialog and hooks them to the Activity, effectively making it the "owner" of each dialog. As such, each dialog inherits certain properties from the Activity. For example, when a dialog is open, the Menu key reveals the options menu defined for the Activity and the volume keys modify the audio stream used by the Activity.

對話框通常作爲Activity的一部分創建和展示。你通常應該從Activity的onCreateDialog(int)回調方法中創建對話框。使用這個回調方法,Android系統自動管理每個對話框的狀態,且連接到Activity,使Activity作爲對話框的擁有者。這樣,每個對話框可以從Activity繼承特定屬性。例如:對話框打開時,Menu鍵會調出Activity定義的可選菜單項,音量鍵可以修改Activity的音量。

Note: If you decide to create a dialog outside of the onCreateDialog() method, it will not be attached to an Activity. You can, however, attach it to an Activity withsetOwnerActivity(Activity).

注意:如果你決定在onCreateDialog()方法之外創建對話框,對話框不會連接到Acitivty。你可以使用setOwnerActivity(Activity)來連接Activity.

When you want to show a dialog, call showDialog(int) and pass it an integer that uniquely identifies the dialog that you want to display.

需要顯示對話框時,調用showDialog(int),傳遞一個對話框的唯一標識整數。

When a dialog is requested for the first time, Android calls onCreateDialog(int) from your Activity, which is where you should instantiate the Dialog. This callback method is passed the same ID that you passed to showDialog(int). After you create the Dialog, return the object at the end of the method.

當對話框第一個請求時,Android調用onCreateDialog(int)來實例化一個對話框。這個回調方法傳遞一個和showDialog(int)相同的ID。創建對話框後,返回該對話框對象。

Before the dialog is displayed, Android also calls the optional callback method onPrepareDialog(int, Dialog). Define this method if you want to change any properties of the dialog each time it is opened. This method is called every time a dialog is opened, whereas onCreateDialog(int) is only called the very first time a dialog is opened. If you don't defineonPrepareDialog(), then the dialog will remain the same as it was the previous time it was opened. This method is also passed the dialog's ID, along with the Dialog object you created inonCreateDialog().

在顯示對話框之前,Android調用onPrepareDialog(int,Dialog)。如果你想在每次打開對話框時,改變對話框的任何屬相,可以定義該方法。對話框每次打開都調用該方法,然而onCreateDialog(int)只是第一次打開時調用。如果不定義onPrepareDialog(),對話框總是和第一次打開時一樣。這個方法也傳入同樣的對話框標識ID。

The best way to define the onCreateDialog(int) and onPrepareDialog(int, Dialog) callback methods is with a switch statement that checks the id parameter that's passed into the method. Each case should check for a unique dialog ID and then create and define the respective Dialog. For example, imagine a game that uses two different dialogs: one to indicate that the game has paused and another to indicate that the game is over. First, define an integer ID for each dialog:

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

Then, define the onCreateDialog(int) callback with a switch case for each ID:

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, there's no code inside the case statements because the procedure for defining your Dialog is outside the scope of this section. See the section below aboutCreating an AlertDialog, offers code suitable for this example.

When it's time to show one of the dialogs, call showDialog(int) with the ID of a dialog:

showDialog(DIALOG_PAUSED_ID);

Dismissing a Dialog 清除對話框

When you're ready to close your dialog, you can dismiss it by calling dismiss() on the Dialog object. If necessary, you can also call dismissDialog(int) from the Activity, which effectively calls dismiss() on the Dialog for you.

當你準備關閉對話框,你可以調用對話框的dismiss()方法。也可以調用Activity的dismissDialog(int),它會調用對話框的dismiss()方法。

If you are using onCreateDialog(int) to manage the state of your dialogs (as discussed in the previous section), then every time your dialog is dismissed, the state of the Dialog object is retained by the Activity. 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). This will remove any internal references to the object and if the dialog is showing, it will dismiss it.

如果使用onCreateDialog(int)管理對話框的狀態,每次對話框dismiss,對話框的狀態會被Activity保留。如果不再需要這個對話框對象或清除對話框狀態是很重要的,那麼你可以調用removeDialog(int).它將清除對該對象的引用,如果對話框正在顯示,也將dismiss對話框。

Using dismiss listeners 使用dismiss監聽器

If you'd like your application to perform some procedures the moment that a dialog is dismissed, then you should attach an on-dismiss listener to your Dialog.

如果讓應用在對話框消失時,執行一些過程,需要給Dialog加載on-dismiss監聽。

First define the DialogInterface.OnDismissListener interface. This interface has just one method, onDismiss(DialogInterface), which will be called when the dialog is dismissed. Then simply pass your OnDismissListener implementation to setOnDismissListener().

首先定義DialogInterface.OnDismissListener接口,該接口只有一個方法onDismiss(DialogInterface),在對話框消失時調用。然後通過setOnDismissListener()加載你的實現。

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, or if the dialog explicitly calls cancel() (perhaps from a "Cancel" button in the dialog). 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().

然而,對話框可以被取消。這是對話框被用戶明確地取消的一種情況。用戶按“back”鍵關閉對話框或對話框調用cancel()方法。當對話框被取消,onDismissListener會被通知,如果cancel是被通知,可以用setOnCancelListener註冊DialogInterface.OnCancelListener.

Creating an AlertDialog 創建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:

AlertDialog繼承了Dialog類,它有能力構造大多數用戶接口對話框。可以使用如下屬性:

  • A title 標題
  • A text message 文本信息
  • One, two, or three buttons 1,2,3個按鈕
  • A list of selectable items (with optional checkboxes or radio buttons)可選項列表

To create an AlertDialog, use the AlertDialog.Builder subclass. Get a Builder with AlertDialog.Builder(Context) and then use the class's public methods to define all of the AlertDialog properties. After you're done with the Builder, retrieve the AlertDialog object with create().

創建一個AlertDialog,可以使用AlertDialog.Builder子類。通過AlertDialog.Bulder(Context)獲得一個Builder,然後使用該類的公共犯非法來定義AlertDialog的屬性。定義好後,使用Builder.create()獲得AlertDialog。

The following topics show how to define various properties of the AlertDialog using the AlertDialog.Builder class. If you use any of the following sample code inside your onCreateDialog()callback method, you can return the resulting Dialog object to display the dialog.

下列各節顯示瞭如何使用AlertDialog.Buider類定義AlertDialog的屬性。如果在onCreateDialog()中使用下面的代碼,你可以返回結果Dialog對象來顯示。

Adding buttons 添加按鈕

To create an AlertDialog with side-by-side buttons like the one shown in the screenshot to the right, use the set...Button() methods:

使用set...Button()方法:

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 for the dialog with setMessage(CharSequence). Then, begin method-chaining and set the dialog to be not cancelable (so the user cannot close the dialog with the back button) with setCancelable(boolean). For each button, use one of the set...Button() methods, such as setPositiveButton(), that accepts the name for the button and aDialogInterface.OnClickListener that defines the action to take when the user selects the button.

首先,使用setMessage(CharSequence)增加信息。然後,使用方法鏈setCancelable(boolean)設置對話框不可取消,使用set...Button()方法,如setPositiveButton()接收按鈕的名字和DialogInterface.OnClickListener方法。

Note: You can only add one of each button type to the AlertDialog. That is, you cannot have more than one "positive" button. This limits the number of possible buttons to three: positive, neutral, and negative. These names are technically irrelevant to the actual functionality of your buttons, but should help you keep track of which one does what.

注意:每種按鈕只能在AlertDialog中添加一個。就是說,你不能有多於一個的"positive"按鈕。有三種可能的按鈕:positive(正),neutral(中立),negative(負)。這些名字和實際功能是不相干的。

Adding a list 添加列表

To create an AlertDialog with a list of selectable items like the one shown to the right, use the setItems() method:

使用setItems()方法產生可選擇的列表。

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, add a title to the dialog with setTitle(CharSequence). Then, add a list of selectable items with setItems(), which accepts the array of items to display and aDialogInterface.OnClickListener that defines the action to take when the user selects an item.

Adding checkboxes and radio buttons 添加多選或單選按鈕

To create a list of multiple-choice items (checkboxes) or single-choice items (radio buttons) inside the dialog, use the setMultiChoiceItems() andsetSingleChoiceItems() methods, respectively. If you create one of these selectable lists in the onCreateDialog() callback method, Android manages the state of the list for you. As long as the Activity is active, the dialog remembers the items that were previously selected, but when the user exits the Activity, the selection is lost.


Note: To save the selection when the user leaves or pauses the Activity, you must properly save and restore the setting throughout the activity lifecycle. To permanently save the selections, even when the Activity process is completely shutdown, you need to save the settings with one of theData Storage techniques.

To create an AlertDialog with a list of single-choice items like the one shown to the right, use the same code from the previous example, but replace thesetItems() 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 in the setSingleChoiceItems() method is an integer value for the checkedItem, which indicates the zero-based list position of the default selected item. Use "-1" to indicate that no item should be selected by default.

Creating a ProgressDialog 創建進度對話框

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 progression. The dialog can also provide buttons, such as one to cancel a download.

Opening a progress dialog can be as simple as calling ProgressDialog.show(). For example, the progress dialog shown to the right can be easily achieved without managing the dialog through the onCreateDialog(int) callback, as shown here:


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

The first parameter is the application Context, the second is a title for the dialog (left empty), the third is the message, and the last parameter is whether the progress is indeterminate (this is only relevant when creating a progress bar, which is discussed in the next section).


The default style of a progress dialog is the spinning wheel. If you want to create a progress bar that shows the loading progress with granularity, some more code is required, as discussed in the next section.


Showing a progress bar

To show the progression with an animated progress bar:

  1. Initialize the ProgressDialog with the class constructor, ProgressDialog(Context).
  2. Set the progress style to "STYLE_HORIZONTAL" with setProgressStyle(int) and set any other properties, such as the message.
  3. When you're ready to show the dialog, call show() or return the ProgressDialog from the onCreateDialog(int) callback.
  4. You can increment the amount of progress displayed in the bar by calling either setProgress(int) with a value for the total percentage completed so far or incrementProgressBy(int) with an incremental value to add to the total percentage completed so far.

For example, your setup might look like this:

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

The setup is simple. Most of the code needed to create a progress dialog is actually involved in the process that updates it. You might find that it's necessary to create a second thread in your application for this work and then report the progress back to the Activity's UI thread with a Handler object. If you're not familiar with using additional threads with a Handler, see the example Activity below that uses a second thread to increment a progress dialog managed by the Activity.

Creating a Custom 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).

如果你想客戶化對話框,你可以創建你自己的layout和控件。然後通過setContentView(View)傳遞根view或layout資源ID。

For example, to create the dialog shown to the right:

  1. Create an XML layout saved 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 inside a LinearLayout.

  2. Set the above layout as the dialog's content view 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 you instantiate the Dialog, set your custom layout as the dialog's content view with setContentView(int), passing it the layout resource ID. Now that the Dialog has a defined layout, you can capture View objects from the layout with findViewById(int) and modify their content.


  3. That's it. You can now show the dialog as described in Showing A Dialog.

A dialog made with the base Dialog class must have a title. If you don't call setTitle(), then the space used for the title remains empty, but still visible. If you don't want a title at all, then you should create your custom dialog using the AlertDialog class. However, because an AlertDialog is created easiest with the AlertDialog.Builder class, you do not have access to the setContentView(int) method used above. Instead, you must use setView(View). This method accepts a View object, so you need to inflate the layout's root View object from XML.

一個繼承自Dialog的對話框必須有一個標題。如果你不調用setTitle(),標題爲空,但仍然可見。如果根本不想顯示標題,你需要使用AlertDialog創建自己的客戶化對話框.然而,因爲AlertDialog可以使用AlertDialgo.Builder方便的建立,沒有setContentView(int)方法。你必須使用setView(View)來代替。這個方法接收View對象,所以你需要從xml構造根view。

To inflate the XML layout, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then call inflate(int, ViewGroup), where the first parameter is the layout resource ID and the second is the ID of the root View. At this point, you can use the inflated layout to find View objects in the layout and define the content for the ImageView and TextView elements. Then instantiate the AlertDialog.Builder and set the inflated layout for the dialog with setView(View).

構造XML佈局,通過getLayoutInflater()獲取LayoutInflater,然後調用inflate(int,ViewGroup),第一個參數是佈局資源ID,第二個參數是根View的ID。你可以查找View對象,來定義ImageView和TextView的內容。然後實例化AlertDialog.Builder對象,使用setView(View)指定infalted的視圖。

Here's an example, creating a custom layout in an AlertDialog:

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 an AlertDialog for your custom layout lets you take advantage of built-in AlertDialog features like managed buttons, selectable lists, a title, an icon and so on.

使用AlertDialog來客戶化對話框,可以利用AlertDialog的內建特性,如:按鈕、可選的列表、標題和圖標等。

For more information, refer to the reference documentation for the Dialog and AlertDialog.Builder classes.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章