我试图在Android中生成一个自定义对话框。 我像这样创建我的Dialog:

dialog = new Dialog(this);
dialog.setContentView(R.layout.my_dialog);

除了对话框的标题,一切都很好。 即使我没有设置对话框的标题,对话框弹出窗口在对话框的位置有一个空白。

有没有办法隐藏对话的这一部分?

我尝试了一个AlertDialog,但似乎布局设置不正确:

LayoutInflater inflater = 
    (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.map_dialog, null);

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(view);

// dialog = new Dialog(this);
// dialog.setContentView(R.layout.map_dialog);

dialog = builder.create();

((TextView) dialog.findViewById(R.id.nr)).setText(number);

如果我使用这段代码,我在最后一行得到一个空指针异常。对话框不是空,所以我试图检索的TextView不存在。 如果我取消注释我使用对话框构造函数的部分,一切正常,但对话框布局上面的标题。


当前回答

将整个对话框的“gravity”属性设置为“center”。然后,您将需要覆盖对话框中所有不希望居中的子组件的设置。

其他回答

如果我们只是使用没有setTitle()的对话框,那么这将在删除标题的空间工作吗?

mUSSDDialog = new AlertDialog.Builder(context).setView(dialogView)
.setPositiveButton(R.string.send_button,DialogListener)
.setNegativeButton(R.string.cancel,DialogListener)
.setCancelable(false).create();

将整个对话框的“gravity”属性设置为“center”。然后,您将需要覆盖对话框中所有不希望居中的子组件的设置。

FEATURE_NO_TITLE在从头创建对话框时起作用,如下所示:

Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

但在创建AlertDialog(或使用Builder)时,它不起作用,因为它已经禁用了标题,并在内部使用自定义标题。

我已经看过SDK源代码,我认为这是不可避免的。因此,要移除顶部间距,唯一的解决方案是通过直接使用dialog类从头开始创建一个自定义对话框。

同样,也可以通过样式来实现,例如在styles.xml中:

<style name="FullHeightDialog" parent="android:style/Theme.Dialog">
   <item name="android:windowNoTitle">true</item>
</style>

然后:

Dialog dialog = new Dialog(context, R.style.FullHeightDialog);

在setcontentview之前使用以下代码

    Dialog dialog = new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 
    dialog.setContentView(R.layout.custom_dialog);

注:你必须有以上代码,顺序和行相同。 requestWindowFeature必须在setContentView行之前。

在你的代码中如果你使用requestWindowFeature(Window.FEATURE_NO_TITLE);确保它放在dialog.setContentView()之前;否则会导致应用程序崩溃。