对话框

试用 Compose 方式
Jetpack Compose 是推荐在 Android 设备上使用的界面工具包。了解如何在 Compose 中添加组件。
<ph type="x-smartling-placeholder"></ph> AlertDialog →

对话框是提示用户 或输入更多信息。对话框未填满整个屏幕, 通常用于要求用户先执行操作的模态事件。 可以继续处理

<ph type="x-smartling-placeholder">。 <ph type="x-smartling-placeholder">
</ph> 显示基本对话框的图片
图 1.基本对话框。

Dialog 类是对话框的基类,但不要将 Dialog 实例化 。而是应使用下列子类之一:

AlertDialog
一个对话框,可显示标题、最多三个按钮、一系列可供选择的按钮 项目或自定义布局。
DatePickerDialogTimePickerDialog
此类对话框具有预定义界面,可让用户选择日期或 。
<ph type="x-smartling-placeholder">

这些类定义对话框的样式和结构。您还需要 一 DialogFragment 用作对话框的容器DialogFragment 类提供 创建对话框和管理其外观所需的所有控件, 而不是对 Dialog 对象调用方法。

使用 DialogFragment 管理对话框可以使其正确 处理生命周期事件,例如当用户点按“返回”按钮或设备屏幕旋转 屏幕上。借助 DialogFragment 类,您还可以重复使用 对话框的界面作为较大界面中的可嵌入组件, 传统 Fragment - 例如 因为您希望对话框界面在大屏幕和小屏幕 屏幕。

本文档的以下部分将介绍如何使用 将 DialogFragmentAlertDialog 组合使用 对象。如果您想创建日期或时间选择器,请参阅 将选择器添加到您的 app

创建对话框 fragment

您可以完成各种对话框设计,包括自定义 以及上文中介绍的 Material Design Dialogs - 通过扩展 DialogFragment 并创建 AlertDialog(在 onCreateDialog() 回调方法。

例如,以下是在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 中的其他回调方法,包括 基本的 fragment 生命周期方法

构建提醒对话框

借助 AlertDialog 类,您可以构建各种对话框 设计,而且这通常是您需要的唯一对话框类。如下所示 如图所示,提醒对话框有三个区域:

  • 标题:可选,仅在内容区域为 被详细消息、列表或自定义布局占据。如果您需要 简单的消息或问题,则不需要标题。
  • 内容区域:可在此处显示消息、列表或其他自定义 布局。
  • 操作按钮:每个网页上最多可以包含 3 个操作按钮 对话框。

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() 方法需要为 按钮,由 string resource(字符串资源)和 一 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 以便异步加载内容有关详情,请参阅 构建布局 使用适配器加载器

<ph type="x-smartling-placeholder">

添加永久性多选列表或单选列表

添加多选项目(复选框)或单选项目列表 (单选按钮),请使用 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。创建 activity 并 将其主题设为 Theme.Holo.Dialog<activity> 清单元素:

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

Activity 现在会显示在一个对话框窗口中,而非全屏显示。

将事件传回对话框的宿主

当用户点按对话框中的某个操作按钮或选择某一项时 您的 DialogFragment 可能会执行必要的 但通常情况下,您会希望将事件传递到 activity 或 fragment。为此,请定义一个接口 为每个类型的点击事件分别创建一个然后,在主机中实现该接口 从对话框接收操作事件的组件。

例如,以下 DialogFragment 定义了一个接口 将事件传回宿主 activity:

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

托管对话框的 activity 会创建一个对话框实例,其中包含 对话框 Fragment 的构造函数,并通过 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.
        ...
    }
}

由于宿主 activity 会实现 NoticeDialogListener,由 onAttach() 回调方法(如上例所示),对话框 Fragment 可以 使用接口回调方法向 Activity 传递点击事件:

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 和对话框 fragment 的标记名称。

您可以调用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" 是标记名称, 系统用于保存和恢复 fragment 状态(如有必要)。该代码还会 可让您通过调用 findFragmentByTag()

以全屏模式或作为嵌入式 fragment 显示对话框

您可能想让一部分界面设计以对话框的形式显示 在其他情况下以全屏或嵌入式 fragment 形式呈现。您可能还会 希望它能够根据设备的屏幕尺寸以不同的方式显示通过 DialogFragment 类可让您灵活地完成此操作, 因为它可以充当可嵌入的 Fragment

但是,您不能使用 AlertDialog.Builder 或其他 在本例中使用 Dialog 对象构建对话框。如果您希望 DialogFragment 设为可嵌入,在 然后在 onCreateView() 回调。

下面是一个 DialogFragment 示例,它可以显示为对话框或 一个可嵌入的 fragment,使用名为 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;
    }
}

以下示例可确定是将 fragment 显示为对话框还是显示为对话框 全屏界面:

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

如需详细了解如何执行 fragment 事务,请参阅 fragment

在此示例中,mIsLargeLayout 布尔值指定 当前设备必须使用应用的大布局设计,因此要显示 Fragment 显示为对话框而非全屏。将此类 这个布尔值表示声明一个 布尔值资源 值替换为 备选 resource值。例如,以下两个版本的布尔资源适用于不同屏幕尺寸:

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

在大屏设备上将 activity 显示为对话框

您可以不再将对话框显示为小屏幕上的全屏界面,而是获取 将 Activity 显示为大型对话框,效果是一样的 屏幕。您选择的方法取决于您的应用设计 如果您的应用是针对小型 并且您希望在平板电脑上显示 短期有效的 activity 作为对话框使用。

如需仅在大屏幕上将 activity 显示为对话框,请将 Theme.Holo.DialogWhenLarge 主题添加到 <activity> 清单元素中:

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

如需详细了解如何使用主题设置 activity 的样式,请参阅 样式和主题

关闭对话框

当用户点按使用 AlertDialog.Builder,系统会为您关闭该对话框。

当用户点按对话框中的项时,系统还会关闭对话框 除非列表使用单选按钮或复选框。或者,您也可以 通过调用 dismiss() 在您的DialogFragment上。

如果您需要在对话框消失时执行某些操作,可以 实施 onDismiss() 方法。DialogFragment

您还可取消对话框。这是一个特殊的活动 表示用户未完成任务就离开了对话框。本次 当用户点按“返回”按钮或点按对话框外的屏幕时触发 或者如果你明确调用 cancel() 针对 Dialog,例如,为了响应“Cancel”按钮(位于 对话框。

如上例所示,您可以通过 正在实现 onCancel()DialogFragment

<ph type="x-smartling-placeholder">