这里我们以解决 PopupWindow 显示的一个问题作为目标来进行分析。
问题描述 想要的效果 在控件上方显示,可能是单行,也可能是多行。
实现方式 使用 showAsDropdown 时,可通过 yOffset 参数指定Y轴方向上的偏移量:
偏移量 = anchorView.height + popupWindow.height
对于第 2 种单行的弹出框来说,实现起来比较简单:
class RawPopupWindowActivity : DemoButtonsActivity() { private var popupWindow: PopupWindow? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) addButton("单行Popup") { v -> showPopup(v, Constants.TEXT_SHORT) } addButton("多行Popup") { v -> showPopup(v, Constants.TEXT_MEDIUM) } addButton("多行Popup") { v -> showPopup(v, Constants.TEXT_LONG) } } private fun showPopup(anchorView: View, content: String) { popupWindow?.run { dismiss() } popupWindow = PopupWindow(applicationContext).apply { isOutsideTouchable = true PopupHelper(applicationContext).run { contentView = binding.root setText(content) } width = WindowManager.LayoutParams.WRAP_CONTENT height = WindowManager.LayoutParams.WRAP_CONTENT setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) // 测量高度 contentView.measure( View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.UNSPECIFIED) ) // 显示时向上移动 anchorView.height + contentView.measuredHeight showAsDropDown(anchorView, 0, -(anchorView.height + contentView.measuredHeight)) } } } 实现效果及问题 最终效果如下:
...