• Android Video Tutorials

Android - 警報對話方塊



對話方塊是一個小型視窗,提示使用者做出決定或輸入更多資訊。

有時,在您的應用程式中,如果您想詢問使用者是否對使用者採取的任何特定操作做出是或否的決定,同時停留在同一活動中而無需更改螢幕,則可以使用警報對話方塊。

為了建立警報對話方塊,您需要建立一個 AlertDialogBuilder 物件,它是 AlertDialog 的內部類。其語法如下所示

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

現在,您必須使用 AlertDialogBuilder 類物件設定肯定(是)或否定(否)按鈕。其語法如下

alertDialogBuilder.setPositiveButton(CharSequence text, 
   DialogInterface.OnClickListener listener)
alertDialogBuilder.setNegativeButton(CharSequence text, 
   DialogInterface.OnClickListener listener)

除此之外,您可以使用構建器類提供的其他函式來自定義警報對話方塊。這些列在下面

序號 方法型別和描述
1

setIcon(Drawable icon)

此方法設定警報對話方塊框的圖示。

2

setCancelable(boolean cancelable)

此方法設定對話方塊是否可以取消的屬性

3

setMessage(CharSequence message)

此方法設定要在警報對話方塊中顯示的訊息

4

setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener)

此方法設定要在對話方塊中顯示為內容的專案列表。所選選項將由偵聽器通知

5

setOnCancelListener(DialogInterface.OnCancelListener onCancelListener)

此方法設定如果對話方塊被取消將呼叫的回撥。

6

setTitle(CharSequence title)

此方法設定要在對話方塊中顯示的標題

建立和設定對話方塊構建器後,您將透過呼叫構建器類的 create() 方法來建立警報對話方塊。其語法如下

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

這將建立警報對話方塊,並將其顯示在螢幕上。

對話方塊片段

在進入示例之前,我們需要了解對話方塊片段。對話方塊片段是一個可以在對話方塊框中顯示片段的片段

public class DialogFragment extends DialogFragment {
   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
      // Use the Builder class for convenient dialog construction
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();
         }
      })
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            finish();
         });
         // Create the AlertDialog object and return it
         return builder.create();
      }
   }
}

列表對話方塊

它用於在對話方塊框中顯示專案列表。例如,使用者需要選擇專案列表,或者需要從多個專案列表中點選一個專案。在這種情況下,我們可以使用列表對話方塊。

public Dialog onCreateDialog(Bundle savedInstanceState) {
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   builder.setTitle(Pick a Color)
   
   .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
         // The 'which' argument contains the index position
         // of the selected item
      }
   });
   return builder.create();
}

單選列表對話方塊

它用於向對話方塊框新增單選列表。我們可以根據使用者的選擇進行選中或取消選中。

public Dialog onCreateDialog(Bundle savedInstanceState) {
   mSelectedItems = new ArrayList();
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   
   builder.setTitle("This is list choice dialog box");
   .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();
}

示例

以下示例演示了在 Android 中使用 AlertDialog 的方法。

要試驗此示例,您需要在模擬器或實際裝置上執行它。

步驟 描述
1 您將使用 Android Studio 建立一個 Android 應用程式,並將其命名為 My Application,位於 com.example.sairamkrishna.myapplication 包下。
2 修改 src/MainActivity.java 檔案以新增警報對話方塊程式碼以啟動對話方塊。
3 修改佈局 XML 檔案 res/layout/activity_main.xml,如果需要,新增任何 GUI 元件。
4 無需更改預設字串常量。Android Studio 會處理 values/string.xml 中的預設字串。
5 執行應用程式,選擇正在執行的 Android 裝置,將應用程式安裝到該裝置上,並驗證結果。

這是修改後的 src/MainActivity.java 程式碼

package com.example.sairamkrishna.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   public void open(View view){
      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
      alertDialogBuilder.setMessage("Are you sure,
         You wanted to make decision");
      alertDialogBuilder.setPositiveButton("yes", 
         new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(MainActivity.this,"You clicked yes 
               button",Toast.LENGTH_LONG).show();
         }
      });

      alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
         Override
         public void onClick(DialogInterface dialog, int which) {
            finish();
         }
      });

      AlertDialog alertDialog = alertDialogBuilder.create();
      alertDialog.show();
   }
}

這是修改後的 res/layout/activity_main.xml 程式碼

在下面的程式碼中,abc 表示 tutorialspoint.com 的徽標
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" 
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" 
   tools:context=".MainActivity">
   
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert Dialog"
      android:id="@+id/textView"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />
      
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorialspoint"
      android:id="@+id/textView2"
      android:textColor="#ff3eff0f"
      android:textSize="35dp"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />
      
   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_alignLeft="@+id/textView"
      android:layout_alignStart="@+id/textView" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert dialog"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="42dp"
      android:onClick="open"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />
      
</RelativeLayout>

這是 Strings.xml 的程式碼

<resources>
    <string name="app_name">My Application</string>
</resources>

這是 AndroidManifest.xml 的預設程式碼

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >
      
      <activity
         android:name="com.example.sairamkrishna.myapplication.MainActivity"
         android:label="@string/app_name" >
         
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
         
      </activity>
      
   </application>
</manifest>

讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您的專案之一的活動檔案,然後單擊工具欄中的執行 Eclipse Run Icon 圖示。在啟動應用程式之前,Android Studio 將顯示以下視窗,供您選擇要在其中執行 Android 應用程式的選項。

Anroid Camera Tutorial

選擇一個選項,然後單擊它。例如,如果您單擊“是”按鈕,則結果如下所示

Anroid Camera Tutorial

如果您單擊“否”按鈕,它將呼叫 finish() 並關閉您的應用程式。

廣告