2

I am trying to create a custom tooltip using the Alert dialog (Like a pop-up view over a bottom sheet). While doing so, I am trying to position it to a particular x and y using window attributes. I will need to measure my alert dialog's width and height.

 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

The above returns 0. Even after measuring the parent layout in R.layout.sample_layout, it returns the same

Few other cases,

  1. alertDialog.window?.attributes.width & alertDialog.window?.attributes.height returns -2

  2. Measuring the content of alert dialog gives almost correct height but width is very large (greater than parent)

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

1 Answers1

0

I was looking for long time how to get the dialog's height. According to this answer https://stackoverflow.com/a/57104421 you can get it (you can get also the width) by registering a layoutChangeListener.

You can use something like :

val alertDialog = AlertDialog.Builder(parent.context)
    .setView(R.layout.sample_layout)
    .create()
alertDialog.window?.decorView?.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ ->
    val alertBoxHeight = v.height
    val alertBoxWidth = v.width
}
alertDialog.show()

It was the only solution that it worked for me.

I hope it is going to help you too!!!

vasberc
  • 81
  • 1
  • 5
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32273422) – The Dreams Wind Jul 21 '22 at 11:36
  • Thanks about your suggestion, was my first answer. – vasberc Jul 28 '22 at 10:35