首页 > 解决方案 > 对 AlertDialog 的高度行为感到困惑

问题描述

我有一个简单的 AlertDialog,如下所示:

new AlertDialog.Builder(this)
    .setTitle("Test")
    .setView(R.layout.dialog_test)
    .setPositiveButton("button1", null)
    .show();

这是dialog_test布局的样子:

<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#FF0000"
    android:text="Test"/>

TextView 显示在对话框内容空间的顶部,下方有额外的空间。因此,AlertDialog 似乎定义了某种最小高度。我想摆脱 AlertDialog 的最小高度并包装 TextView 的高度,或者我想至少在 AlertDialog 的内容空间中垂直居中 TextView。

我尝试将对话框的布局设置为在显示之前/之后包装高度,但它没有做任何事情:dialog.window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)

我也尝试过将 TextView 设置为android:layout_heighttowrap_contentandroid:layout_gravityto,center_vertical但 TextView 仍然停留在 AlertDialog 内容空间的顶部。我尝试将 TextView 设置为android:layout_heighttomatch_parentandroid:gravityto,center_vertical但 TextView 的高度没有填充 AlertDialog 的内容空间,并且似乎保持包裹状态并且它停留在 AlertDialog 内容的顶部。

我正在使用android.support.v7.app.AlertDialog但也尝试过android.app.AlertDialog,它有同样的问题。

那么当我的内容的高度小于 AlertDialog 的最小高度时,有没有办法让我删除 AlertDialog 的最小高度或至少垂直居中内容?

谢谢!

更新:查看 AlertDialog 的代码后,我发现添加自定义视图的布局(customPanel)确实具有最小高度。

您可以像这样删除最小高度:

AlertDialog dialog = new AlertDialog.Builder(this)
    .setView(R.layout.dialog_test)
    .show();
dialog.findViewById(R.id.customPanel).setMinimumHeight(0);
// Use R.id.contentPanel if you're using setMessage() instead of setView()

或者,如果你想保持最小高度但想垂直居中内容,我是这样完成的:

AlertDialog dialog = new AlertDialog.Builder(this)
    .setView(R.layout.dialog_test)
    .show();
((FrameLayaout.LayoutParams) dialog.findViewById(R.id.custom).getLayoutParams()).gravity = Gravity.CENTER_VERTICAL

标签: javaandroid

解决方案


推荐阅读