android AlertDialog setView 规则

标签 android android-alertdialog android-custom-view

AlertDialog 类的setView() 方法允许为对话框指定自定义 View 。对于可以包含在此自定义 View 中的控件是否有任何限制?

此外,如果我们设置自定义 View ,我们是否仍可以使用 setPositiveButton()setNegativeButton() 等添加按钮?

最佳答案

AlertDialog 类的 setView() 方法允许为对话框指定自定义 View 。对于可以包含在此自定义 View 中的控件是否有任何限制?

AlertDialog.Builder 中的setView() 方法接受从 View 扩展的任何类(class)(查看它的子类及其子类)。

这意味着 EditTexts、Buttons 等。还有从 viewGroups 扩展的布局。

此外,如果我们设置自定义 View ,我们是否仍可以使用 setPositiveButton、setNegativeButton 等添加按钮?

是的,它只影响 body 。 按钮添加到布局下方。

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    // Get the layout inflater
    LayoutInflater inflater = getLayoutInflater();
    // Inflate and set the layout for the dialog
    // Pass null as the parent view because its going in the dialog
    // layout
    builder.setView(inflater.inflate(R.layout.YourLayout, null))
        .setPositiveButton(AlertDialog.BUTTON_NEGATIVE, "Yes!",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    //
                }
         })
        .setNegativeButton(AlertDialog.BUTTON_NEGATIVE, "Cancel",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {
                    LoginDialogFragment.this.getDialog().cancel();
                }
         });
    return builder.create();
}

更新:

自 2 年前以来,这个答案似乎有了一些新的 Activity ,并且有些事情发生了变化。

我稍微更新了代码以改进格式,并根据最佳实践的当前状态添加了以下提示。

The AlertDialog defines the style and structure for your dialog, but you should use a DialogFragment as a container for your dialog. The DialogFragment class provides all the controls you need to create your dialog and manage its appearance, instead of calling methods on the Dialog object.

上面的例子是指当你扩展DialogFragment并在onCreateDialog()回调方法中创建一个AlertDialog时。

关于android AlertDialog setView 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14834685/

相关文章:

android - AlertDialog背景颜色问题

java - 创建自定义 View 并添加到 XML

java - 如何删除已膨胀到屏幕的布局

java - 过渡不起作用

android - 如何在 Android 中更改小部件 TabLayout 指示器的重力

android - 像 iOS subview 一样创建 Android subview

Android - 自定义 Spinner 小部件的外观和感觉

android - 如何在 Gradle 中使用方法添加依赖项

java - 我什么时候可以在 AlertView 中编辑 View

android - 自定义 Android 中的警报对话框