Android: Set popup window width same as achor view width

Viewed 142

I am using constraint layout in which I have arranged views using flow.
These views are added dynamically.
enter image description here

On clicking any of view a popup window should open like shown in the illustration below:
enter image description here

I have managed to show the popup window but it is not taking complete width of anchor view. This is how it is looking right now:

enter image description here

This is the snippet from my code which shows the popup window

anchorView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
val width = anchorView.measuredWidth
val height = ViewGroup.LayoutParams.WRAP_CONTENT

val focusable = true
val popupWindow = PopupWindow(popupCardBinding.root, width, height, focusable)
popupWindow.showAsDropDown(anchorView)

How can I make it's width same as anchorView's width?

1 Answers

I'm not sure where you're calling measure for the anchor view, but try measuring after the view has been drawn - using UNSPECIFIED doesn't always return the correct values, if you use measure too early:

anchorView.post {
  anchorView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
  val width = anchorView.measuredWidth
  val height = ViewGroup.LayoutParams.WRAP_CONTENT

  val focusable = true
  val popupWindow = PopupWindow(popupCardBinding.root, width, height, focusable)
  popupWindow.showAsDropDown(anchorView)
}

If it doesn't work, try showing more code about how and when anchorView is created

Related