【问题标题】:How to get Alert Dialog dimensions?如何获取警报对话框尺寸?
【发布时间】:2022-07-18 19:34:18
【问题描述】:

我正在尝试使用“警报”对话框创建自定义工具提示(就像底部工作表上的弹出视图)。这样做时,我试图使用窗口属性将其定位到特定的 x 和 y。我需要测量警报对话框的宽度和高度。

 val alertDialog = AlertDialog.Builder(parent.context)
            .setView(R.layout.sample_layout)
            .create()
 alertDialog.show()
 val alertBoxHeight = alertDialog.window?.decorView?.height
 val alertBoxWidth = alertDialog.window?.decorView?.width

以上返回 0。 即使在 R.layout.sample_layout 中测量父布局后,它也返回相同

其他情况很少,

  1. alertDialog.window?.attributes.width & alertDialog.window?.attributes.height 返回 -2

  2. 测量警报对话框的内容给出了几乎正确的高度,但宽度非常大(大于父级)

    val alertLayout = alertDialog.findViewById<ConstraintLayout>(R.id.parentLayout)
    
    alertLayout?.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED))
    

【问题讨论】:

    标签: android android-layout android-alertdialog


    【解决方案1】:

    我一直在寻找如何获得对话框的高度。 根据这个答案https://stackoverflow.com/a/57104421,您可以通过注册layoutChangeListener 来获取它(您也可以获取宽度)。 这是唯一对我有用的解决方案。 希望对你也有帮助!!!

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      • 2017-04-08
      • 2018-05-10
      • 1970-01-01
      • 2015-07-11
      相关资源
      最近更新 更多