對話方塊

試用 Compose
Jetpack Compose 是 Android 推薦的 UI 工具包。瞭解如何在 Compose 中新增元件。

對話方塊是提示使用者輸入的小視窗 或輸入其他資訊對話方塊沒有填滿畫面, 通常用於強制使用者等互動再採取行動的事件 就能繼續操作

,瞭解如何調查及移除這項存取權。
顯示基本對話方塊的圖片
圖 1.基本對話方塊。

Dialog 類別是對話方塊的基礎類別,但不會將 Dialog 例項化 請改用下列其中一個子類別:

AlertDialog
對話方塊可顯示標題、最多 3 個按鈕,以及可選取的清單 也可以建立自訂版面配置
DatePickerDialogTimePickerDialog
這個對話方塊含有預先定義的 UI,可讓使用者選取日期或 讓應用程式從可以最快做出回應的位置 回應使用者要求
,瞭解如何調查及移除這項存取權。

這些類別會定義對話方塊的樣式和結構。您也需要 換 DialogFragment 做為對話方塊的容器DialogFragment 類別提供 建立對話方塊和管理外觀所需的所有控制項 而不是呼叫 Dialog 物件的方法

使用 DialogFragment 管理對話方塊,讓對話方塊正確顯示 處理生命週期事件,例如使用者輕觸「返回」按鈕或旋轉 。DialogFragment 類別也可讓您重複使用 做為大型使用者介面中的可嵌入元件 傳統 Fragment:例如 就好比您想讓對話方塊 UI 在大、小尺寸上不同顯示時一樣 螢幕。

本文件的後續章節將說明如何使用 DialogFragmentAlertDialog 物件。如要建立日期或時間挑選器,請參閱 在廣告活動廣告中加入挑選器 app

建立對話方塊片段

您可以完成多種對話方塊設計,包括 資源配置以及 質感設計 對話方塊:擴充 DialogFragment 並建立 AlertDialogonCreateDialog() 回呼方法。

例如,以下是在 Pod 中管理的基本 AlertDialog DialogFragment:

Kotlin

class StartGameDialogFragment : DialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        return activity?.let {
            // Use the Builder class for convenient dialog construction.
            val builder = AlertDialog.Builder(it)
            builder.setMessage("Start game")
                .setPositiveButton("Start") { dialog, id ->
                    // START THE GAME!
                }
                .setNegativeButton("Cancel") { dialog, id ->
                    // User cancelled the dialog.
                }
            // Create the AlertDialog object and return it.
            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }
}

class OldXmlActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_old_xml)

        StartGameDialogFragment().show(supportFragmentManager, "GAME_DIALOG")
    }
}

Java

public class StartGameDialogFragment 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_start_game)
               .setPositiveButton(R.string.start, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // START THE GAME!
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // User cancels the dialog.
                   }
               });
        // Create the AlertDialog object and return it.
        return builder.create();
    }
}
// ...

StartGameDialogFragment().show(supportFragmentManager, "GAME_DIALOG");

建立這個類別的例項並呼叫 show() 該物件上的對話方塊,如下圖所示。

顯示含有兩個動作按鈕的基本對話方塊的圖片
圖 2. 顯示訊息和兩個訊息的對話方塊 動作按鈕。

下一節將詳細說明如何使用 AlertDialog.Builder 用於建立對話方塊的 API。

視對話方塊的複雜程度而定,您可以實作 DialogFragment 中的其他回呼方法,包括所有 基本的片段生命週期方法

建立快訊對話方塊

AlertDialog 類別可讓您建構各種對話方塊 這通常是您需要的唯一對話方塊類別。如下所示 快訊對話方塊有三個區域:

  • 標題:此為選用項目,只有在內容區域為 並嵌入至詳細訊息、清單或自訂版面配置中。如果需要 一個簡單的訊息或問題,不需要標題。
  • 內容區域:可顯示訊息、清單或其他自訂訊息 版面配置。
  • 動作按鈕:單一容器最多可有三個動作按鈕 對話方塊

AlertDialog.Builder 類別提供的 API 可讓您建立 包含這類內容的 AlertDialog,包括 版面配置。

如要建構 AlertDialog,請按照下列步驟操作:

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setMessage("I am the message")
    .setTitle("I am the title")

val dialog: AlertDialog = builder.create()
dialog.show()

Java

// 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.
AlertDialog dialog = builder.create();

上一個程式碼片段會產生這個對話方塊:

顯示含有標題、內容區域和兩個動作按鈕的對話方塊的圖片。
圖 3. 基本快訊的版面配置 對話方塊

新增按鈕

如要新增動作按鈕 (如圖 2 所示),請將按鈕呼叫 setPositiveButton()setNegativeButton() 方法:

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setMessage("I am the message")
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

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 taps OK button.
           }
       });
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
               // User cancels the dialog.
           }
       });
// Set other dialog properties.
...

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

set...Button() 方法需要有標題的 按鈕, 字串資源—以及 換 DialogInterface.OnClickListener 定義使用者輕觸按鈕時要採取的動作。

您可以新增以下三個動作按鈕:

  • 正面:使用這個選項即可接受並繼續動作 ( 「確定」動作)。
  • 負面:用於取消動作。
  • 無意見:如果使用者不想繼續使用 但不一定您想要取消。它位於 正面和負面按鈕例如,動作可能是「提醒我」 。」

您只能在 AlertDialog 中為每個按鈕類型新增一種。適用對象 每個品牌只能有一個「正面」按鈕。

先前的程式碼片段會顯示快訊對話方塊,如下所示:

這張圖片顯示快訊對話方塊,其中含有標題、訊息和兩個動作按鈕。
圖 4. 含有標題的快訊對話方塊 訊息和兩個動作按鈕

新增清單

AlertDialog 提供三種清單。 API:

  • 傳統單選清單。
  • 持續的單選清單 (圓形按鈕)。
  • 持續的複選清單 (核取方塊)。

如要建立單選清單 (如圖 5 所示),請使用 setItems() 方法:


Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }
    .setItems(arrayOf("Item One", "Item Two", "Item Three")) { dialog, which ->
        // Do something on item tapped.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.pick_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();
}

這個程式碼片段會產生對話方塊,如下所示:

顯示含有標題和清單的對話方塊的圖片。
圖 5. 含有標題和清單的對話方塊。

該清單會顯示在對話方塊的內容區域中,因此對話方塊無法顯示 訊息和清單為對話方塊設定標題 setTitle()。 若要指定清單的項目,請呼叫 setItems(),並傳遞 陣列。此外,您可以使用 setAdapter()。 這樣您就能使用動態資料傳回清單,例如來自 使用編碼器 - 資料庫 ListAdapter

如果使用 ListAdapter 傳回清單,請一律使用 Loader 讓內容以非同步方式載入詳細說明請參閱 建立版面配置 包含轉接器載入器

新增持續的複選清單或單選清單

如何新增複選項目清單 (核取方塊) 或單選項目 (圓形按鈕),請使用 setMultiChoiceItems()setSingleChoiceItems() 方法。

以下舉例說明如何建立複選清單 如圖 6 所示,將所選項目儲存在 ArrayList:

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }
    .setMultiChoiceItems(
        arrayOf("Item One", "Item Two", "Item Three"), null) { dialog, which, isChecked ->
        // Do something.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    selectedItems = 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 checks the item, add it to the selected
                       // items.
                       selectedItems.add(which);
                   } else if (selectedItems.contains(which)) {
                       // If the item is already in the array, remove it.
                       selectedItems.remove(which);
                   }
               }
           })
    // Set the action buttons
           .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   // User taps OK, so save the selectedItems results
                   // somewhere or return them to the component that opens the
                   // dialog.
                   ...
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   ...
               }
           });

    return builder.create();
}
顯示含有複選項目清單的對話方塊圖片。
圖 6. 包含複選項目的清單。

單選警示對話方塊的取得方式如下:

Kotlin

val builder: AlertDialog.Builder = AlertDialog.Builder(context)
builder
    .setTitle("I am the title")
    .setPositiveButton("Positive") { dialog, which ->
        // Do something.
    }
    .setNegativeButton("Negative") { dialog, which ->
        // Do something else.
    }
    .setSingleChoiceItems(
        arrayOf("Item One", "Item Two", "Item Three"), 0
    ) { dialog, which ->
        // Do something.
    }

val dialog: AlertDialog = builder.create()
dialog.show()

Java

        String[] choices = {"Item One", "Item Two", "Item Three"};
        
        AlertDialog.Builder builder = AlertDialog.Builder(context);
        builder
                .setTitle("I am the title")
                .setPositiveButton("Positive", (dialog, which) -> {

                })
                .setNegativeButton("Negative", (dialog, which) -> {

                })
                .setSingleChoiceItems(choices, 0, (dialog, which) -> {

                });

        AlertDialog dialog = builder.create();
        dialog.show();

這會產生以下範例:

顯示含有單選項目清單的對話方塊的圖片。
圖 7.單選項目清單。

建立自訂版面配置

如果您希望在對話方塊中使用自訂版面配置,請建立版面配置並新增至 致電給AlertDialog setView() 在您的 AlertDialog.Builder 物件上。

顯示自訂對話方塊版面配置的圖片。
圖 8. 自訂對話方塊版面配置。

根據預設,自訂版面配置會填滿對話方塊視窗,但您仍然可以 使用 AlertDialog.Builder 方法新增按鈕和標題。

例如,以下自訂對話方塊的版面配置檔案 版面配置:

res/layout/dialog_signin.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:src="@drawable/header_logo"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:scaleType="center"
        android:background="#FFFFBB33"
        android:contentDescription="@string/app_name" />
    <EditText
        android:id="@+id/username"
        android:inputType="textEmailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="4dp"
        android:hint="@string/username" />
    <EditText
        android:id="@+id/password"
        android:inputType="textPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:fontFamily="sans-serif"
        android:hint="@string/password"/>
</LinearLayout>
敬上

如要加載 DialogFragment 中的版面配置,請取得 LayoutInflater 同時 getLayoutInflater() 並撥號 inflate()。 第一個參數是版面配置資源 ID,第二個參數是 版面配置的上層檢視畫面。接著,您可以撥打 setView() 將版面配置放在對話方塊中如以下範例所示。

Kotlin

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return activity?.let {
        val builder = AlertDialog.Builder(it)
        // Get the layout inflater.
        val inflater = requireActivity().layoutInflater;

        // Inflate and set the layout for the dialog.
        // Pass null as the parent view because it's going in the dialog
        // layout.
        builder.setView(inflater.inflate(R.layout.dialog_signin, null))
                // Add action buttons.
                .setPositiveButton(R.string.signin,
                        DialogInterface.OnClickListener { dialog, id ->
                            // Sign in the user.
                        })
                .setNegativeButton(R.string.cancel,
                        DialogInterface.OnClickListener { dialog, id ->
                            getDialog().cancel()
                        })
        builder.create()
    } ?: throw IllegalStateException("Activity cannot be null")
}

Java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater.
    LayoutInflater inflater = requireActivity().getLayoutInflater();

    // Inflate and set the layout for the dialog.
    // Pass null as the parent view because it's going in the dialog layout.
    builder.setView(inflater.inflate(R.layout.dialog_signin, null))
    // Add action buttons
           .setPositiveButton(R.string.signin, new DialogInterface.OnClickListener() {
               @Override
               public void onClick(DialogInterface dialog, int id) {
                   // Sign in the user.
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   LoginDialogFragment.this.getDialog().cancel();
               }
           });
    return builder.create();
}

如要使用自訂對話方塊,可以改為顯示 Activity 即 而非使用 Dialog API。建立活動並 將主題設為 Theme.Holo.Dialog<activity> 資訊清單元素:

<activity android:theme="@android:style/Theme.Holo.Dialog" >

活動現在會在對話方塊 (而非全螢幕) 中顯示。

將事件傳回對話方塊的主機

使用者輕觸對話方塊的動作按鈕,或選取項目時 DialogFragment 可能會執行必要的 但通常您希望在活動中傳送事件 開啟對話方塊的片段。為此,請使用方法定義介面 為每個點擊事件類型啟用預算然後在主機中實作該介面 接收對話方塊的動作事件。

舉例來說,以下 DialogFragment 定義了介面 透過這個方法將事件傳回主機活動:

Kotlin

class NoticeDialogFragment : DialogFragment() {
    // Use this instance of the interface to deliver action events.
    internal lateinit var listener: NoticeDialogListener

    // The activity that creates an instance of this dialog fragment must
    // implement this interface to receive event callbacks. Each method passes
    // the DialogFragment in case the host needs to query it.
    interface NoticeDialogListener {
        fun onDialogPositiveClick(dialog: DialogFragment)
        fun onDialogNegativeClick(dialog: DialogFragment)
    }

    // Override the Fragment.onAttach() method to instantiate the
    // NoticeDialogListener.
    override fun onAttach(context: Context) {
        super.onAttach(context)
        // Verify that the host activity implements the callback interface.
        try {
            // Instantiate the NoticeDialogListener so you can send events to
            // the host.
            listener = context as NoticeDialogListener
        } catch (e: ClassCastException) {
            // The activity doesn't implement the interface. Throw exception.
            throw ClassCastException((context.toString() +
                    " must implement NoticeDialogListener"))
        }
    }
}

Java

public class NoticeDialogFragment extends DialogFragment {

    // The activity that creates an instance of this dialog fragment must
    // implement this interface to receive event callbacks. Each method passes
    // the DialogFragment in case the host needs to query it.
    public interface NoticeDialogListener {
        public void onDialogPositiveClick(DialogFragment dialog);
        public void onDialogNegativeClick(DialogFragment dialog);
    }

    // Use this instance of the interface to deliver action events.
    NoticeDialogListener listener;

    // Override the Fragment.onAttach() method to instantiate the
    // NoticeDialogListener.
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        // Verify that the host activity implements the callback interface.
        try {
            // Instantiate the NoticeDialogListener so you can send events to
            // the host.
            listener = (NoticeDialogListener) context;
        } catch (ClassCastException e) {
            // The activity doesn't implement the interface. Throw exception.
            throw new ClassCastException(activity.toString()
                    + " must implement NoticeDialogListener");
        }
    }
    ...
}

代管對話方塊的活動會建立含有 對話方塊片段的建構函式,並透過 實作 NoticeDialogListener 介面:

Kotlin

class MainActivity : FragmentActivity(),
        NoticeDialogFragment.NoticeDialogListener {

    fun showNoticeDialog() {
        // Create an instance of the dialog fragment and show it.
        val dialog = NoticeDialogFragment()
        dialog.show(supportFragmentManager, "NoticeDialogFragment")
    }

    // The dialog fragment receives a reference to this Activity through the
    // Fragment.onAttach() callback, which it uses to call the following
    // methods defined by the NoticeDialogFragment.NoticeDialogListener
    // interface.
    override fun onDialogPositiveClick(dialog: DialogFragment) {
        // User taps the dialog's positive button.
    }

    override fun onDialogNegativeClick(dialog: DialogFragment) {
        // User taps the dialog's negative button.
    }
}

Java

public class MainActivity extends FragmentActivity
                          implements NoticeDialogFragment.NoticeDialogListener{
    ...
    public void showNoticeDialog() {
        // Create an instance of the dialog fragment and show it.
        DialogFragment dialog = new NoticeDialogFragment();
        dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
    }

    // The dialog fragment receives a reference to this Activity through the
    // Fragment.onAttach() callback, which it uses to call the following
    // methods defined by the NoticeDialogFragment.NoticeDialogListener
    // interface.
    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        // User taps the dialog's positive button.
        ...
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        // User taps the dialog's negative button.
        ...
    }
}

由於主機活動會實作 NoticeDialogListener:這是由 onAttach() 回呼方法,對話方塊片段 請使用介面回呼方法將點擊事件傳送至活動:

Kotlin

    override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
        return activity?.let {
            // Build the dialog and set up the button click handlers.
            val builder = AlertDialog.Builder(it)

            builder.setMessage(R.string.dialog_start_game)
                    .setPositiveButton(R.string.start,
                            DialogInterface.OnClickListener { dialog, id ->
                                // Send the positive button event back to the
                                // host activity.
                                listener.onDialogPositiveClick(this)
                            })
                    .setNegativeButton(R.string.cancel,
                            DialogInterface.OnClickListener { dialog, id ->
                                // Send the negative button event back to the
                                // host activity.
                                listener.onDialogNegativeClick(this)
                            })

            builder.create()
        } ?: throw IllegalStateException("Activity cannot be null")
    }

Java

public class NoticeDialogFragment extends DialogFragment {
    ...
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Build the dialog and set up the button click handlers.
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(R.string.dialog_start_game)
               .setPositiveButton(R.string.start, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // Send the positive button event back to the host activity.
                       listener.onDialogPositiveClick(NoticeDialogFragment.this);
                   }
               })
               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       // Send the negative button event back to the host activity.
                       listener.onDialogNegativeClick(NoticeDialogFragment.this);
                   }
               });
        return builder.create();
    }
}

顯示對話方塊

如要顯示對話方塊,請建立 DialogFragment並撥號 show(), 傳遞 FragmentManager 以及對話方塊片段的標記名稱

如要取得 FragmentManager,請呼叫 getSupportFragmentManager()FragmentActivity 或撥號 getParentFragmentManager() 來自 Fragment。請參閱以下範例:

Kotlin

fun confirmStartGame() {
    val newFragment = StartGameDialogFragment()
    newFragment.show(supportFragmentManager, "game")
}

Java

public void confirmStartGame() {
    DialogFragment newFragment = new StartGameDialogFragment();
    newFragment.show(getSupportFragmentManager(), "game");
}

第二個引數 "game" 是不重複的標記名稱, 並在必要時儲存及還原片段狀態。代碼也會 可讓您呼叫 findFragmentByTag()

以全螢幕或內嵌片段顯示對話方塊

您可能會希望某些 UI 設計顯示為對話方塊 並以全螢幕或嵌入片段的形式顯示您可能也會發現 或是根據裝置的螢幕大小,以不同的方式顯示縮圖。 DialogFragment 類別具有彈性來達成此效果。 因為它可以做為嵌入式 Fragment 的行為。

但無法使用 AlertDialog.Builder 或其他 在此情況下,用於建構對話方塊的 Dialog 物件。如果您希望 要嵌入的 DialogFragment,請在 然後將版面配置載入 onCreateView() 回呼。

以下是可以顯示為對話方塊或DialogFragment 嵌入的片段,方法是使用名為 purchase_items.xml:

Kotlin

class CustomDialogFragment : DialogFragment() {

    // The system calls this to get the DialogFragment's layout, regardless of
    // whether it's being displayed as a dialog or an embedded fragment.
    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        // Inflate the layout to use as a dialog or embedded fragment.
        return inflater.inflate(R.layout.purchase_items, container, false)
    }

    // The system calls this only when creating the layout in a dialog.
    override fun onCreateDialog(savedInstanceState: Bundle): Dialog {
        // The only reason you might override this method when using
        // onCreateView() is to modify the dialog characteristics. For example,
        // the dialog includes a title by default, but your custom layout might
        // not need it. Here, you can remove the dialog title, but you must
        // call the superclass to get the Dialog.
        val dialog = super.onCreateDialog(savedInstanceState)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        return dialog
    }
}

Java

public class CustomDialogFragment extends DialogFragment {
    // The system calls this to get the DialogFragment's layout, regardless of
    // whether it's being displayed as a dialog or an embedded fragment.
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // Inflate the layout to use as a dialog or embedded fragment.
        return inflater.inflate(R.layout.purchase_items, container, false);
    }

    // The system calls this only when creating the layout in a dialog.
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // The only reason you might override this method when using
        // onCreateView() is to modify the dialog characteristics. For example,
        // the dialog includes a title by default, but your custom layout might
        // not need it. Here, you can remove the dialog title, but you must
        // call the superclass to get the Dialog.
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
}

以下範例會判斷要將片段顯示為對話方塊還是 全螢幕 UI,視螢幕大小而定:

Kotlin

fun showDialog() {
    val fragmentManager = supportFragmentManager
    val newFragment = CustomDialogFragment()
    if (isLargeLayout) {
        // The device is using a large layout, so show the fragment as a
        // dialog.
        newFragment.show(fragmentManager, "dialog")
    } else {
        // The device is smaller, so show the fragment fullscreen.
        val transaction = fragmentManager.beginTransaction()
        // For a polished look, specify a transition animation.
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
        // To make it fullscreen, use the 'content' root view as the container
        // for the fragment, which is always the root view for the activity.
        transaction
                .add(android.R.id.content, newFragment)
                .addToBackStack(null)
                .commit()
    }
}

Java

public void showDialog() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    CustomDialogFragment newFragment = new CustomDialogFragment();

    if (isLargeLayout) {
        // The device is using a large layout, so show the fragment as a
        // dialog.
        newFragment.show(fragmentManager, "dialog");
    } else {
        // The device is smaller, so show the fragment fullscreen.
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // For a polished look, specify a transition animation.
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
        // To make it fullscreen, use the 'content' root view as the container
        // for the fragment, which is always the root view for the activity.
        transaction.add(android.R.id.content, newFragment)
                   .addToBackStack(null).commit();
    }
}

如需進一步瞭解如何執行片段交易,請參閱 片段

在這個範例中,mIsLargeLayout 布林值指定 目前裝置必須使用應用程式的大型版面配置設計,因此會顯示 將片段做為對話方塊,而非全螢幕。要將這類模型 布林是用來宣告 布林值資源 值,並將 替代文案 資源值。例如,以下是針對不同螢幕大小的布爾資源的兩個版本:

res/values/bools.xml

<!-- Default boolean values -->
<resources>
    <bool name="large_layout">false</bool>
</resources>

res/values-large/bools.xml

<!-- Large screen boolean values -->
<resources>
    <bool name="large_layout">true</bool>
</resources>

接著就可以在 mIsLargeLayout 的 活動的 onCreate() 方法,如以下範例所示:

Kotlin

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    isLargeLayout = resources.getBoolean(R.bool.large_layout)
}

Java

boolean isLargeLayout;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    isLargeLayout = getResources().getBoolean(R.bool.large_layout);
}

在大螢幕上顯示活動對話方塊

與其在小螢幕上以全螢幕 UI 顯示對話方塊,您可以 將 Activity 顯示為大型對話方塊,進而產生相同結果 螢幕。選擇的方法取決於應用程式的設計 在應用程式專為小型螢幕設計的情況下 而您希望在平板電腦上顯示 來解釋一下短期活動

如要在大螢幕上將活動顯示為對話方塊,請套用 Theme.Holo.DialogWhenLarge <activity> 資訊清單元素的主題:

<activity android:theme="@android:style/Theme.Holo.DialogWhenLarge" >

如要進一步瞭解如何使用主題設定活動樣式,請參閱 樣式與主題

關閉對話方塊

當使用者輕觸由 AlertDialog.Builder,系統會為您關閉對話方塊。

當使用者輕觸對話方塊中的項目時,系統也會關閉對話方塊 ,除非清單使用圓形按鈕或核取方塊。否則, 請撥打電話,手動關閉對話方塊 dismiss() 位於 DialogFragment

如果您需要在對話方塊消失時執行特定動作 實作 onDismiss() 方法,DialogFragment

你也可以「Cancel」對話方塊。這個特殊活動 表示使用者在未完成工作時離開對話方塊。這個 如果使用者輕觸「返回」按鈕或輕觸螢幕以外的畫面,就會發生這種情形 區域,或是您特別撥打 cancel() Dialog,例如回應「取消」按鈕 (位於 對話方塊

如以上範例所示,您可以透過 實作 onCancel()DialogFragment 類別中。