olivierg 的回答对我有用,如果创建自定义 Dialog 类是您想要走的路线,这是最好的解决方案。但是,我无法使用 AlertDialog 类让我很困扰。我希望能够使用默认的系统 AlertDialog 样式。创建自定义对话框类不会有这种样式。
所以我找到了一个无需创建自定义类即可工作的解决方案(hack),您可以使用现有的构建器。
AlertDialog 在您的内容视图上方放置一个视图作为标题的占位符。如果您找到视图并将高度设置为 0,空间就会消失。
到目前为止,我已经在 2.3 和 3.0 上对此进行了测试,它可能还不适用于每个版本。
这里有两种辅助方法:
/**
* Show a Dialog with the extra title/top padding collapsed.
*
* @param customView The custom view that you added to the dialog
* @param dialog The dialog to display without top spacing
* @param show Whether or not to call dialog.show() at the end.
*/
public static void showDialogWithNoTopSpace(final View customView, final Dialog dialog, boolean show) {
// Now we setup a listener to detect as soon as the dialog has shown.
customView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// Check if your view has been laid out yet
if (customView.getHeight() > 0) {
// If it has been, we will search the view hierarchy for the view that is responsible for the extra space.
LinearLayout dialogLayout = findDialogLinearLayout(customView);
if (dialogLayout == null) {
// Could find it. Unexpected.
} else {
// Found it, now remove the height of the title area
View child = dialogLayout.getChildAt(0);
if (child != customView) {
// remove height
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
lp.height = 0;
child.setLayoutParams(lp);
} else {
// Could find it. Unexpected.
}
}
// Done with the listener
customView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
// Show the dialog
if (show)
dialog.show();
}
/**
* Searches parents for a LinearLayout
*
* @param view to search the search from
* @return the first parent view that is a LinearLayout or null if none was found
*/
public static LinearLayout findDialogLinearLayout(View view) {
ViewParent parent = (ViewParent) view.getParent();
if (parent != null) {
if (parent instanceof LinearLayout) {
// Found it
return (LinearLayout) parent;
} else if (parent instanceof View) {
// Keep looking
return findDialogLinearLayout((View) parent);
}
}
// Couldn't find it
return null;
}
这是如何使用它的示例:
Dialog dialog = new AlertDialog.Builder(this)
.setView(yourCustomView)
.create();
showDialogWithNoTopSpace(yourCustomView, dialog, true);
如果您将它与 DialogFragment 一起使用,请覆盖 DialogFragment 的onCreateDialog
方法。然后像上面的第一个示例一样创建并返回您的对话框。唯一的变化是您应该将 false 作为第三个参数 (show) 传递,这样它就不会在对话框中调用 show()。DialogFragment 稍后会处理。
例子:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = new AlertDialog.Builder(getContext())
.setView(yourCustomView)
.create();
showDialogWithNoTopSpace(yourCustomView, dialog, false);
return dialog;
}
当我进一步测试时,我一定会更新所需的任何额外调整。