AlertDialog對話框

在Android程序中 ,我們可能用到,在一個界面中彈出一個dialog 提示一些信息或執行操作。

-一、Dialog:在官方文檔中A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

 一個對話框是一個小窗口,提示用戶做出決定或輸入額外的信息。對話框不填滿屏幕,通常用於模態事件,要求用戶採取行動才能進行。

 DialogFragment:Note: Because the DialogFragment class was originally added with Android 3.0 (API level 11), this document describes how to use the DialogFragment class that's provided with the Support Library. By adding this library to your app, you can use DialogFragment and a variety of other APIs on devices running Android 1.6 or higher. If the minimum version your app supports is API level 11 or higher, then you can use the framework version ofDialogFragment, but be aware that the links in this document are for the support library APIs. When using the support library, be sure that you import android.support.v4.app.DialogFragment class and notandroid.app.DialogFragment.

注意:因爲DialogFragment類最初添加與Android 3.0(API級別11),本文檔描述瞭如何使用DialogFragment類提供的支持庫。通過將這個庫添加到您的應用程序,您可以使用DialogFragment和各種其他api的設備上運行Android 1.6或更高版本。如果最低版本應用程序支持API級別11或更高版本,那麼您可以使用這個框架版本ofDialogFragment,但是請注意,本文檔中的鏈接支持庫的API。當使用支持庫,確保您導入android.support.v4.app。DialogFragment類和notandroid.app.DialogFragment。

二、創建一個dialog的fragment

You can accomplish a wide variety of dialog designs—including custom layouts and those described in theDialogs design guide—by extending DialogFragment and creating a AlertDialog in the onCreateDialog()callback method.

你能完成各種對話框designs-including theDialogs中描述的自定義佈局和設計guide-by擴展DialogFragment和創建一個AlertDialog onCreateDialog()回調方法。

public class FireMissilesDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(R.string.dialog_fire_missiles)
               .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // FIRE ZE MISSILES!
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancelled the dialog
                   }
               });
        // Create the AlertDialog object and return it
        return builder.create();
    }
}


三、alertdialog

組成:AlertDialog類允許您構建各種對話框的設計,往往是你唯一需要的對話框類。如圖2所示,有三個地區的一個警告對話框



①區域1那裏就是定義彈出框的頭部信息,包括標題名或者是一個圖標。

②區域2那裏是AlertDialog對話框的content部分,在這裏我們可以設置一些message信息,或者是定義一組選擇框,還可以定義我們自己的佈局彈出框。

③區域3那裏使我們的Action Buttons部分,這裏我們可以定義我們的操作按鈕

// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
       .setTitle(R.string.dialog_title);

// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();

增加兩個按鈕:添加操作按鈕一樣在上圖中,調用setPositiveButton()和setNegativeButton()方法

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Add the buttons
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // User clicked OK button
           }
       });
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // User cancelled the dialog
           }
       });
// Set other dialog properties
...

// Create the AlertDialog
AlertDialog dialog = builder.create();

在alertdialog中 ,自定義的按鈕都是setxxxButton()方法來完成的

1.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)
這是一個相當於OK、確定操作的按鈕,

2.setNegativeButton (CharSequence text, DialogInterface.OnClickListener listener)
這是一個相當於取消操作的按鈕。

3. setNeutralButton (CharSequence text, DialogInterface.OnClickListener listener)
這個是相當於一個忽略操作的按鈕。

我們每一種action buttons最多隻能出現一個,即彈出對話框最多隻能出現一個PositiveButton。

接下來我們通過一個一個的具體實例來看看我們常用的幾種AlertDialog對話框。

.彈出一個警告框,並有三個按鈕可選擇


button.setOnClickListener(new OnClickListener()

        {             @Override             public void onClick(View v)             {                 //    通過AlertDialog.Builder這個類來實例化我們的一個AlertDialog的對象                 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);                 //    設置Title的圖標                 builder.setIcon(R.drawable.ic_launcher);                 //    設置Title的內容                 builder.setTitle("彈出警告框");                 //    設置Content來顯示一個信息                 builder.setMessage("確定刪除嗎?");                 //    設置一個PositiveButton                 builder.setPositiveButton("確定", new DialogInterface.OnClickListener()                 {                     @Override                     public void onClick(DialogInterface dialog, int which)                     {                         Toast.makeText(MainActivity.this, "positive: " + which, Toast.LENGTH_SHORT).show();                     }                 });                 //    設置一個NegativeButton                 builder.setNegativeButton("取消", new DialogInterface.OnClickListener()                 {                     @Override                     public void onClick(DialogInterface dialog, int which)                     {                         Toast.makeText(MainActivity.this, "negative: " + which, Toast.LENGTH_SHORT).show();                     }                 });                 //    設置一個NeutralButton                 builder.setNeutralButton("忽略", new DialogInterface.OnClickListener()                 {                     @Override                     public void onClick(DialogInterface dialog, int which)                     {                         Toast.makeText(MainActivity.this, "neutral: " + which, Toast.LENGTH_SHORT).show();                     }                 });                 //    顯示出該對話框                 builder.show();             }         });


四、下拉列表彈出框:


button2.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View arg0)
            {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setIcon(R.drawable.ic_launcher);
                builder.setTitle("選擇一個城市");
                //    指定下拉列表的顯示數據
                final String[] cities = {"廣州", "上海", "北京", "香港", "澳門"};
                //    設置一個下拉的列表選擇項
                builder.setItems(cities, new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        Toast.makeText(MainActivity.this, "選擇的城市爲:" + cities[which], Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
            }
        });


Because the list appears in the dialog's content area, the dialog cannot show both a message and a list and you should set a title for the dialog with setTitle(). To specify the items for the list, call setItems(), passing an array. Alternatively, you can specify a list using setAdapter(). This allows you to back the list with dynamic data (such as from a database) using a ListAdapter.

If you choose to back your list with a ListAdapter, always use a Loader so that the content loads asynchronously. This is described further in Building Layouts with an Adapter and the Loaders guide.

Note: By default, touching a list item dismisses the dialog, unless you're using one of the following persistent choice lists.

五、

Adding a persistent multiple-choice or single-choice list

官方解釋:To add a list of multiple-choice items (checkboxes) or single-choice items (radio buttons), use thesetMultiChoiceItems() or setSingleChoiceItems()methods, respectively.
For example, here's how you can create a multiple-choice list like the one shown in figure 4 that saves the selected items in an ArrayList:



public Dialog onCreateDialog(Bundle savedInstanceState) {
    mSelectedItems = new ArrayList();  // Where we track the selected items
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Set the dialog title
    builder.setTitle(R.string.pick_toppings)
    // Specify the list array, the items to be selected by default (null for none),
    // and the listener through which to receive callbacks when items are selected
           .setMultiChoiceItems(R.array.toppings, null,
                      new DialogInterface.OnMultiChoiceClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int which,
                       boolean isChecked) {
                   if (isChecked) {
                       // If the user checked the item, add it to the selected items
                       mSelectedItems.add(which);
                   } else if (mSelectedItems.contains(which)) {
                       // Else, if the item is already in the array, remove it 
                       mSelectedItems.remove(Integer.valueOf(which));
                   }
               }
           })
    // Set the action buttons
           .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   // User clicked OK, so save the mSelectedItems results somewhere
                   // or return them to the component that opened the dialog
                   ...
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   ...
               }
           });

    return builder.create();
}
note:Although both a traditional list and a list with radio buttons provide a "single choice" action, you should usesetSingleChoiceItems() if you want to persist the user's choice. That is, if opening the dialog again later should indicate what the user's current choice is, then you create a list with radio buttons.


六、.自定義彈出對話框

If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.

By default, the custom layout fills the dialog window, but you can still use AlertDialog.Builder methods to add buttons and a title.


dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    
    <EditText 
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="username"/>
    
    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/username"
        android:hint="password"
        android:inputType="textPassword"/>


</RelativeLayout>

button5.setOnClickListener(new OnClickListener()

        {             @Override             public void onClick(View v)             {                 AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);                 builder.setIcon(R.drawable.ic_launcher);                 builder.setTitle("請輸入用戶名和密碼");                 //    通過LayoutInflater來加載一個xml的佈局文件作爲一個View對象                 View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog, null);                 //    設置我們自己定義的佈局文件作爲彈出框的Content                 builder.setView(view);                                  final EditText username = (EditText)view.findViewById(R.id.username);                 final EditText password = (EditText)view.findViewById(R.id.password);                                  builder.setPositiveButton("確定", new DialogInterface.OnClickListener()                 {                     @Override                     public void onClick(DialogInterface dialog, int which)                     {                         String a = username.getText().toString().trim();                         String b = password.getText().toString().trim();                         //    將輸入的用戶名和密碼打印出來                         Toast.makeText(MainActivity.this, "用戶名: " + a + ", 密碼: " + b, Toast.LENGTH_SHORT).show();                     }                  });                 builder.setNegativeButton("取消", new DialogInterface.OnClickListener()                 {                     @Override                     public void onClick(DialogInterface dialog, int which)                     {                                              }                 });                 builder.show();             }         });


我們看到,通過自定義彈出框,我們首先需要寫一個xml的佈局文件,然後在裏面定義我們的佈局,我們不需要在佈局文件裏定義Button按鈕,可以通過 AlertDialog.Builder 來設置 action buttons。

通過 View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.dialog, null); 我們可以將我們的佈局文件加載進來,得到一個View對象,然後通過 AlertDialog.Builder 的setView方法來設置我們的自定義彈出框.


Prompt  User Input  Dialog

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_label" />
    <EditText
        android:id="@+id/editTextResult"
        android:layout_width="match_parent"
        android:inputType="text"
        android:layout_height="wrap_content" >
    </EditText>
</LinearLayout>

prompts.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tv_label"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    <EditText
        android:id="@+id/userInput"
        android:layout_width="match_parent"
        android:inputType="text"
        android:layout_height="wrap_content" >
        <requestFocus />
    </EditText>
</LinearLayout>

MainActivity.class.

public class MainActivity extends Activity {


private Button button;
private EditText editTextMainScreen;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

// components from main.xml
button = (Button) findViewById(R.id.button);
editTextMainScreen = (EditText) findViewById(R.id.editTextResult);

button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {


// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(context);

View promptView = layoutInflater.inflate(R.layout.prompts, null);

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);

// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);

final EditText input = (EditText) promptView.findViewById(R.id.userInput);

// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
editTextMainScreen.setText(input.getText());
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});


// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();


alertD.show();


}
});
}
}



官方文檔:http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog


android用戶界面之PopupWindow教程實例彙總:

http://www.apkbus.com/forum.php?mod=viewthread&tid=50999&extra=page%3D1&page=1


發佈了21 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章