Android AlertDialog 詳解

創建對話框
  一個對話框一般是一個出現在當前Activity之上的一個小窗口. 處於下面的Activity失去焦點, 對話框接受所有的用戶交互. 對話框一般用於提示信息和與當前應用程序直接相關的小功能.
  Android API 支持下列類型的對話框對象:
  警告對話框 AlertDialog:  一個可以有0到3個按鈕, 一個單選框或複選框的列表的對話框. 警告對話框可以創建大多數的交互界面, 是推薦的類型.
  進度對話框 ProgressDialog:  顯示一個進度環或者一個進度條. 由於它是AlertDialog的擴展, 所以它也支持按鈕.
  日期選擇對話框 DatePickerDialog:  讓用戶選擇一個日期.
  時間選擇對話框 TimePickerDialog:  讓用戶選擇一個時間.
  如果你希望自定義你的對話框, 可以擴展Dialog類.
  Showing a Dialog 顯示對話框
   一個對話框總是被創建和顯示爲一個Activity的一部分. 你應該在Activity的onCreateDialog(int)中創建對話框. 當你使用這個回調函數時,Android系統自動管理每個對話框的狀態並將它們和Activity連接, 將Activity變爲對話框的"所有者". 這樣,每個對話框從Activity繼承一些屬性. 例如,當一個對話框打開時, MENU鍵會顯示Activity的菜單, 音量鍵會調整Activity當前使用的音頻流的音量.
  注意: 如果你希望在onCreateDialog()方法之外創建對話框, 它將不會依附在Activity上. 你可以使用setOwnerActivity(Activity)來將它依附在Activity上.
  當你希望顯示一個對話框時, 調用showDialog(int)並將對話框的id傳給它.
  當一個對話框第一次被請求時,Android調用onCreateDialog(int). 這裏是你初始化對話框的地方. 這個回調函數傳入的id和showDialog(int)相同. 創建對話框之後,將返回被創建的對象.
   在對話框被顯示之前,Android還會調用onPrepareDialog(int, Dialog). 如果你希望每次顯示對話框時有動態更改的內容, 那麼就改寫這個函數. 該函數在每次一個對話框打開時都調用. 如果你不定義該函數,則對話框每次打開都是一樣的. 該函數也會傳入對話框的id以及你在onCreateDialog()中創建的Dialog對象.
   最好的定義onCreateDialog(int) 和onPrepareDialog(int, Dialog) 的方法就是使用一個switch語句來檢查傳入的id. 每個case創建相應的對話框. 例如, 一個遊戲使用兩個對話框: 一個來指示遊戲暫停,另一個指示遊戲結束. 首先, 爲它們定義ID:static final int DIALOG_PAUSED_ID = 0;
static final int DIALOG_GAMEOVER_ID = 1; 
然後, 在onCreateDialog(int)中加入一個switch語句:
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;

  注意: 在這個例子中, case語句爲空因爲定義Dialog的程序在後面會有介紹.
  在需要顯示對話框是, 調用showDialog(int), 傳入對話框的id:
  showDialog(DIALOG_PAUSED_ID);Dismissing a Dialog 解除對話框
  當你準備關閉對話框時, 你可以使用dismiss()函數. 如果需要的話, 你也可以從Activity調用dismissDialog(int), 二者效果是一樣的.
   如果你使用onCreateDialog(int)來管理你的對話框的狀態, 那麼每次你的對話框被解除時, 該對話框對象的狀態會被Activity保存. 如果你決定你不再需要這個對象或者需要清除對話框的狀態, 那麼你應該調用 removeDialog(int). 這將把所有該對象的內部引用移除, 如果該對話框在顯示的話將被解除.
  Using dismiss listeners 使用解除監聽器
  如果你希望在對話框解除時運行某些程序, 那麼你應該給對話框附加一個解除監聽器.
  首先定義DialogInterface.OnDismissListener接口. 這個接口只有一個方法, onDismiss(DialogInterface), 該方法將在對話框解除時被調用.
  然後將你的OnDismissListener實現傳給setOnDismissListener().
   然而,注意對話框也可以被"取消". 這是一個特殊的情形, 它意味着對話框被用戶顯式的取消掉. 這將在用戶按下"back"鍵時, 或者對話框顯式的調用cancel()(按下對話框的cancel按鈕)時發生. 當一個對話框被取消時, OnDismissListener將仍然被通知, 但如果你希望在對話框被顯示取消(而不是正常解除)時被通知, 則你應該使用setOnCancelListener()註冊一個DialogInterface.OnCancelListener.
  Creating an 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:
  一個警告對話框是對話框的一個擴展. 它能夠創建大多數對話框用戶界面並且是推薦的對話框類新星. 對於需要下列任何特性的對話框,你都應該使用它:
  一個標題
  一條文字消息
  1個-3個按鈕
  一個可選擇的列表(單選框或者複選框)
   要創建一個AlertDialog, 使用AlertDialog.Builder子類. 使用AlertDialog.Builder(Context)來得到一個Builder, 然後使用該類的公有方法來定義AlertDialog的屬性. 設定好以後, 使用create()方法來獲得AlertDialog對象.
  下面的主題展示瞭如何爲AlertDialog定義不同的屬性, 使用AlertDialog.Builder類. 如果你使用這些示例代碼, 你可以在onCreateDialog()中返回最後的Dialog對象來獲得圖片中對話框的效果.
  Adding buttons 增加按鈕


要創建一個如圖所示的窗口, 使用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();
   首先,使用setMessage(CharSequence)爲對話框增加一條消息。 然後, 開始連續調用方法, 使用setCancelable(boolean)將對話框設爲不可取消(不能使用back鍵來取消)。對每一個按鈕,使用set...Button() 方法,該方法接受按鈕名稱和一個DialogInterface.OnClickListener,該監聽器定義了當用戶選擇該按鈕時應做的動作。
   注意:對每種按鈕類型,只能爲AlertDialog創建一個。也就是說,一個AlertDialog不能有兩個以上的"positive"按鈕。這使 得可能的按鈕數量最多爲三個:肯定、否定、中性。這些名字和實際功能沒有聯繫,但是將幫助你記憶它們各做什麼事情。Adding a list 增加列表


要創建一個具有可選項的AlertDialog,使用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();
首先增加一個標題。然後使用setItems()增加一個可選列表,該列表接受一個選項名稱的列表和一個DialogInterface.OnClickListener, 後者定義了選項對應的響應。
Adding checkboxes and radio buttons 增加單選框和複選框


  要創建一個帶有多選列表或者單選列表的對話框, 使用setMultiChoiceItems()和setSingleChoiceItems()方法。如果你在onCreateDialog()中創建 可選擇列表, Android會自動管理列表的狀態. 只要activity仍然活躍, 那麼對話框就會記住剛纔選中的選項,但當用戶退出activity時,該選擇丟失。
  注意: 要在你的acitivity離開和暫停時保存選擇, 你必須在activity的聲明週期中正確的保存和恢復設置。爲了永久性保存選擇,你必須使用數據存儲技術中的一種。
  要創建一個具有單選列表的AlertDialog,只需將一個例子中的setItems()換成 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();
第二個參數是默認被選中的選項位置,使用“-1”來表示默認情況下不選中任何選項。
Creating a ProgressDialog 創建進度對話框


  一個ProgressDialog(進度對話框)是AlertDialog的擴展。它可以顯示一個進度的動畫——進度環或者進度條。這個對話框也可以提供按鈕,例如取消一個下載等。
  打開一個進度對話框很簡單,只需要調用 ProgressDialog.show()即可。例如,上圖的對話框可以不通過onCreateDialog(int),而直接顯示:
  ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "",
  "Loading. Please wait...", true);
  第一個參數是應用程序上下文。第二個爲對話框的標題(這裏爲空),第三個爲對話框內容, 最後一個爲該進度是否爲不可確定的(這隻跟進度條的創建有關,見下一節)。
  進度對話框的默認樣式爲一個旋轉的環。如果你希望顯示進度值,請看下一節。
  Showing a progress bar 顯示進度條
  使用一個動畫進度條來顯示進度:
  使用 ProgressDialog(Context)構造函數來初始化一個ProgressDialog對象。
  將進度樣式設置爲"STYLE_HORIZONTAL",使用setProgressStyle(int)方法。並且設置其它屬性,例如內容等。
  在需要顯示時調用show()或者從onCreateDialog(int)回調函數中返回該ProgressDialog。
  你可以使用 setProgress(int)或者incrementProgressBy(int)來增加顯示的進度。
  例如,你的設置可能像這樣:ProgressDialog progressDialog;
progressDialog = new ProgressDialog(mContext);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
  設置很簡單。大部分創建進度對話框需要的代碼是在更新它的進程中。你可能需要在一個新的線程中更新它,並使用Handler來將進度報告給Activity。如果你不熟悉使用Handler和另外的線程,請看下列例子,該例子使用了一個新的線程來更新進度。
  Example ProgressDialog with a second thread 例--使用一個線程來顯示進度對話框
   這個例子使用一個線程來跟蹤一個進程的進度(其實爲從1數到100)。每當進度更新時,該線程通過Handler給主activity發送一個消息。主 Activity更新ProgressDialog.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 創建自定義對話框


如果你想自定義一個對話框,你可以使用佈局元素來創造你的對話框的佈局。定義好佈局後,將根View對象或者佈局資源ID傳給setContentView(View).
例如,創建如圖所示的對話框:
創建一個xml佈局custom_dialog.xml: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"
              >
    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"
              >
                   android:layout_width="wrap_content"
               android:layout_height="fill_parent"
               android:layout_marginRight="10dp"
               />
                  android:layout_width="wrap_content"
              android:layout_height="fill_parent"
              android:textColor="#FFF"
              />

該xml定義了一個LinearLayout中的一個ImageView 和一個TextView。
將以上佈局設爲對話框的content view,並且定義ImageView 和 TextView的內容:
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);
  在初始化Dialog之後,使用setContentView(int),將佈局資源id傳給它。現在Dialog有一個定義好的佈局,你可以使用findViewById(int)來找到該元素的id並修改它的內容。
  使用前面所講的方法顯示對話框。
   一個使用Dialog類建立的對話框必須有一個標題。如果你不調用setTitle(),那麼標題區域會保留空白。如果你不希望有一個標題,那麼你應該 使用AlertDialog類來創建自定義對話框。然而,由於一個AlertDialog使用AlertDialog.Builder類來建立最方便,所 以你沒有方法使用setContentView(int),而是隻能使用setView(View)。該方法接受一個View對象,所以你需要從xml中 展開你的根View。
  要展開一個xml佈局,使用 getLayoutInflater() (或 getSystemService())取得LayoutInflater,然後調用inflate(int, ViewGroup),第一個參數爲佈局id,而第二個參數爲根view的id。現在,你可以使用展開後的佈局來找到View對象並定義 ImageView和TextView元素的內容。然後實例化AlertDialog.Builder並使用setView(View)來爲對話框設置展 開後的佈局。例如:
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();
使用AlertDialog來自定義對話框,可以利用其內置特性例如按鈕、選擇列表、標題、圖標等。

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