首页 > 解决方案 > 自定义 AlertDialog 布局宽度和高度未正确应用

问题描述

我有一个像这样的自定义对话框

class CustomDialogFragment2(context: Context) : DialogFragment() {

    private val builder: MaterialAlertDialogBuilder = MaterialAlertDialogBuilder(context)

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        builder.setTitle("Custom Dialog")
        builder.setMessage("content")
        builder.setPositiveButton("OK", object: DialogInterface.OnClickListener{
            override fun onClick(dialog: DialogInterface?, which: Int) {

            }
        })
        builder.setView(R.layout.layout_image2)
        return builder.create()
    }
}

布局图像2

<?xml version="1.0" encoding="utf-8"?>
<ImageView
    android:id="@+id/image"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    android:layout_marginTop="25dp"
    android:layout_width="60dp"
    android:layout_height="60dp"
    app:srcCompat="@drawable/ic_success" />

结果:图像尺寸很小,因为它只是显示图标的默认尺寸,宽度和高度 60dp 被忽略。
在此处输入图像描述

但是,如果我在约束布局内扭曲图像视图,现在将应用 60dp 的宽度和高度

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <ImageView
        android:id="@+id/image"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="25dp"
        android:layout_width="60dp"
        android:layout_height="60dp"
        app:srcCompat="@drawable/ic_success" />
</androidx.constraintlayout.widget.ConstraintLayout>

结果:图像现在变大了,因为它对图像应用了 60dp 的宽度和高度。

在此处输入图像描述

请在此处解释为什么自定义 AlertDialog 需要约束布局。

2个布局不是有确切的含义吗?谢谢

标签: androidandroid-alertdialog

解决方案


推荐阅读