I have an AlertDialog with a ConstraintLayout as a view and all of the children have a height of 0dp
, i.e match constraints:
<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 -->
I want the dialog to take as much height as possible on screen, to a maximum of 400dp
. However the layout above produces a dialog with 0 height, invisible.
I tried using dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
. The dialog took the whole screen height but the ConstraintLayout was still invisible.
Is there any way to do this?
I found a solution after diving deep into Android's source code. The code below finds the maximum dimensions that the dialog can take and compares it with my own maximum dimensions. After that I set the size of the dialog and the size of my view manually.
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;
}
Note: context
can be replaced with getActivity()
.