Android AlertDialog高度行为异常问题及解决办法
解决AlertDialog自定义视图下方空白或内容不居中的问题
我之前也碰到过一模一样的情况:当用AlertDialog.Builder的setView()添加自定义布局(比如一个简单的TextView)时,视图总是贴在对话框内容区域的顶部,下方留着多余的空白。翻了AlertDialog的源码才明白,这是因为内部的customPanel布局默认设置了最小高度限制。下面给你两种针对性的解决方案:
方案一:移除最小高度,让对话框完全适配视图
如果希望对话框的高度完全贴合自定义视图的大小,直接去掉customPanel的最小高度就行:
AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Test") .setView(R.layout.dialog_test) .setPositiveButton("button1", null) .show(); // 移除customPanel的最小高度限制 dialog.findViewById(R.id.customPanel).setMinimumHeight(0); // 小贴士:如果你的对话框是用setMessage()设置内容而非setView(),请把上面的id换成R.id.contentPanel
对应的自定义布局dialog_test.xml示例:
<?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"/>
方案二:保留最小高度,让内容垂直居中
要是你不想改动对话框的最小高度,只是希望自定义视图在内容区域里垂直居中,可以修改custom视图的布局参数:
AlertDialog dialog = new AlertDialog.Builder(this) .setTitle("Test") .setView(R.layout.dialog_test) .setPositiveButton("button1", null) .show(); // 获取custom视图的布局参数,设置垂直居中 ((FrameLayout.LayoutParams) dialog.findViewById(R.id.custom).getLayoutParams()).gravity = Gravity.CENTER_VERTICAL;
额外说明
- 不管你用的是
android.support.v7.app.AlertDialog还是原生的android.app.AlertDialog,这个问题都会存在,上面两种方案都能生效。 - 之前你尝试的
dialog.window.setLayout(...)、设置TextView的layout_gravity或gravity没效果,是因为这些操作都没触碰到AlertDialog内部的核心布局限制——也就是customPanel的最小高度,或者custom视图的默认位置设置。
内容的提问来源于stack exchange,提问作者Altherat
相关产品推荐
相关产品推荐

