0

我有一个带有 ConstraintLayout 的 AlertDialog 作为视图,并且所有子项的高度为0dp,即匹配约束:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:maxHeight="400dp">

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <!-- Other children -->

我希望对话框在屏幕上占据尽可能高的高度,最大为400dp. 然而,上面的布局会产生一个高度为 0 的对话框,不可见。

我尝试使用dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT). 该对话框占据了整个屏幕高度,但 ConstraintLayout 仍然不可见。

有没有办法做到这一点?

4

1 回答 1

0

在深入研究 Android 的源代码后,我找到了解决方案。下面的代码找到对话框可以采用的最大尺寸,并将其与我自己的最大尺寸进行比较。之后,我手动设置对话框的大小和视图的大小。

private int dialogMaxWidth = 1200;  // don't do that
private int dialogMaxHeight = 1200;

@Override
public @NonNull Dialog onCreateDialog(Bundle state) {
    View view = LayoutInflater.from(context).inflate(R.layout.my_dialog, null);

    final Dialog dialog = new Dialog(context);
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialogInterface) {
            // Get maximum dialog dimensions
            // Basically (screen size) - (dialog's drawable padding)
            Rect fgPadding = new Rect();
            dialog.getWindow().getDecorView().getBackground().getPadding(fgPadding);
            DisplayMetrics metrics = context.getResources().getDisplayMetrics();
            int height = metrics.heightPixels - fgPadding.top - fgPadding.bottom;
            int width = metrics.widthPixels - fgPadding.top - fgPadding.bottom;

            // Set dialog's dimensions
            if (width > dialogMaxWidth) width = dialogMaxWidth;
            if (height > dialogMaxHeight) height = dialogMaxHeight;
            dialog.getWindow().setLayout(width, height);

            // Set dialog's content
            view.setLayoutParams(new ViewGroup.LayoutParams(width, height));
            dialog.setContentView(view);
        }
    });

    return dialog;
}

注:context可替换为getActivity().

于 2018-03-10T20:51:49.143 回答