天天看點

彈出對話-------- 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

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

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

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

});

首先增加一個标題。然後使用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"}; 

builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {

第二個參數是預設被選中的選項位置,使用“-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:layout_width="wrap_content"

               android:layout_height="fill_parent"

               android:layout_marginRight="10dp"

               />

                  android:layout_width="wrap_content"

              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; 

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

ImageView image = (ImageView) layout.findViewById(R.id.image);

builder = new AlertDialog.Builder(mContext);

builder.setView(layout);

alertDialog = builder.create();

使用AlertDialog來自定義對話框,可以利用其内置特性例如按鈕、選擇清單、标題、圖示等。

繼續閱讀