安卓:自定义AlertDialog

6

我用以下代码创建了一个自定义的AlertDialog:

AlertDialog.Builder builder;
AlertDialog alertDialog;

LayoutInflater inflater = (LayoutInflater)ActivityName.this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.custom_layout,(ViewGroup)findViewById(R.id.layout_root));

                builder = new AlertDialog.Builder(getParent());
                builder.setView(layout);
                alertDialog = builder.create();
                alertDialog.show();

问题是弹出窗口被默认对话框背景包围,拥有自己的无标题空间(因为未设置标题)。我该如何移除它?我尝试通过ContextThemeWrapper放置自定义样式,例如builder = new AlertDialog.Builder(new ContextThemeWrapper(getParent(), R.style.CustomDialogTheme));,但这并不起作用。我该怎么做?提前感谢您的帮助。 以下是自定义样式xml:
<style name="CustomDialogTheme" parent="android:style/Theme.Dialog.Alert">
            <item name="android:windowIsFloating">false</item>
            <item name="android:windowNoTitle">true</item>
        </style>

This is the output on the emulator


不显示标题会让用户感到困惑,你应该在对话框上显示一个标题,因为这是预期的标准。 - JoxTraex
我在布局中添加了标题(如您所见的“设置为…”)。 - IronBlossom
2个回答

16

使用以下内容

Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);

扩展您的布局并将视图设置为对话框内容

dialog.setContentView(view);

1
谢谢Jitendra!!它移除了默认的背景,但我现在有另一个问题。我正在使用Theme.NoTitleBar.Fullscreen设置的应用程序,但是当对话框弹出时,顶部标题栏会再次滑下来,并且对话框不在中心位置,而是在窗口的左上角(默认位置)。你能帮我解决这个问题吗? - IronBlossom
1
使用 Dialog dialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar.Fullscreen); - jeet
作为更新 - 我使用了这种方法,并通过在相对布局中放置自定义对话框并将重力设置为中心来修复了中心问题。使用Theme_Translucent_NoTitleBar_Fullscreen并没有解决居中问题。 - Rarw

7
AlertDialog dialog = new AlertDialog.Builder(this)
.setView(getLayoutInflater().inflate(R.layout.custom_dialog, null))
.create();

为了监听用户界面(UI)事件:
View view = getLayoutInflater().inflate(R.layout.custom_dialog, null);
Button btn = (Button)view.findViewById(R.id.the_id_of_the_button);
btn.setOnClickListener(blah blah);
AlertDialog dialog = new AlertDialog.Builder(this)
  .setView(view)
  .create();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接