Android:设置弹出窗口宽度与锚视图宽度相同

问题描述

我正在使用约束布局,其中使用流排列视图。
这些视图是动态添加的。

enter image description here

点击任何一个视图时,应该会打开一个弹出窗口,如下图所示:

enter image description here

我设法显示了弹出窗口,但它没有占用锚视图的完整宽度。这是它现在的样子:

enter image description here

这是我的代码片段,它显示了弹出窗口

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)

如何使它的宽度与anchorView的宽度相同?

解决方法

我不确定您为锚视图调用 df1 mpg cyl disp hp df2 mpg cyl disp hp drat df3 mpg cyl disp hp drat wt 的位置,但是在绘制视图后尝试测量 - 使用 measure 并不总是返回正确的值,如果您过早使用 UNSPECIFIED

measure

如果它不起作用,请尝试显示更多有关如何以及何时创建 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) } 的代码