如果创建自定义Dialog类是您要走的路线,则olivierg的答案对我有用,并且是最佳解决方案。但是,令我困扰的是我无法使用AlertDialog类。我希望能够使用默认的系统AlertDialog样式。创建自定义对话框类不会具有这种样式。
因此,我找到了一个无需创建自定义类即可使用的解决方案(黑客),您可以使用现有的构建器。
AlertDialog在您的内容视图上方放置一个View作为标题的占位符。如果找到该视图并将高度设置为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;
}
当我进一步测试时,我将确保进行任何需要的其他调整。