olivierg的答案对我有用,如果你想要创建自定义Dialog类,则是最佳解决方案。然而,我很困扰的是我不能使用AlertDialog类。我希望能够使用默认的系统AlertDialog样式。创建一个自定义对话框类将没有这个样式。
因此,我找到了一个解决方案(hack),可以在不创建自定义类的情况下工作,您可以使用现有的构建器。
AlertDialog将一个View放置在您的内容视图上方,作为标题的占位符。如果您找到该视图并将其高度设置为0,则该空间会消失。
我已经在2.3和3.0上测试过了,可能还不能在每个版本上工作。
以下是两个辅助方法:
public static void showDialogWithNoTopSpace(final View customView, final Dialog dialog, boolean show) {
customView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (customView.getHeight() > 0) {
LinearLayout dialogLayout = findDialogLinearLayout(customView);
if (dialogLayout == null) {
} else {
View child = dialogLayout.getChildAt(0);
if (child != customView) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();
lp.height = 0;
child.setLayoutParams(lp);
} else {
}
}
customView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
if (show)
dialog.show();
}
public static LinearLayout findDialogLinearLayout(View view) {
ViewParent parent = (ViewParent) view.getParent();
if (parent != null) {
if (parent instanceof LinearLayout) {
return (LinearLayout) parent;
} else if (parent instanceof View) {
return findDialogLinearLayout((View) parent);
}
}
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;
}
如果我进一步测试,我会确保更新任何需要的额外调整。