获取已设置为WRAP_CONTENT的PopupWindow高度

时间:2018-09-11 10:19:03

标签: android view kotlin

这是我的代码:

val inflater = LayoutInflater.from(this)
val popupView = inflater.inflate(R.layout.small_player, null)
val popupWindow = PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT/*, focusable*/)
popupWindow.elevation = 1.0f
popupWindow.showAtLocation(window.decorView, Gravity.CENTER, 0, window.decorView.height)
val height = popupWindow.contentView.height //returns 0

我也尝试了popupView.height,但是它返回0,而popupWindow.contentView.layoutParams.height返回-1

那我怎么能达到这个高度?

2 个答案:

答案 0 :(得分:0)

这是一个非常普遍的问题,当您尝试获取其高度时,您的视图不在屏幕上

尝试一下。

val inflater = LayoutInflater.from(this)
val popupView = inflater.inflate(R.layout.small_player, null)
val popupWindow = PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT/*, focusable*/)
popupWindow.elevation = 1.0f
popupWindow.showAtLocation(window.decorView, Gravity.CENTER, 0, window.decorView.height)

popupView.post{
    val height = popupWindow.contentView.height 
}

还要检查更多View's getWidth() and getHeight() returns 0

答案 1 :(得分:0)

您可以使用View.getMeasuredHeight()来提供视图的实际高度。

您现在获取的值是用于MATCH_PARENT和WRAP_CONTENT的数字表示形式