java - 对 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_height
towrap_content
和android:layout_gravity
to,center_vertical
但 TextView 仍然停留在 AlertDialog 内容空间的顶部。我尝试将 TextView 设置为android:layout_height
tomatch_parent
和android:gravity
to,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
解决方案
推荐阅读
- google-analytics - 如何更改谷歌分析中的网站网址路径?
- java - Java 执行时间不加起来
- sql-server - 从 Excel 粘贴时 SQL Server 显示 Null,即使单元格中有值
- mysql - 无法从终端登录 mysql 上的任何帐户
- visual-studio - 是否可以在 Developer Powershell Terminal 中更改字体?
- docker-compose - 如何在启动时在 kong docker 容器中运行 curl 命令?
- cordova - 内容安全策略框架祖先错误地阻止来自文件系统的 safari
- javascript - 为什么我的 Javascript 不为该文本设置动画以更改颜色?
- java - 如何使用 MPAndroidChart 检索 JSON 数据并绘制 LineChart 并在 android 上进行改造
- gpu - 模拟低功耗 GPU 以帮助生成最低要求