Mat*_*att 24 android popupwindow
我正在开发一个Android应用程序,当用户点击屏幕底部的特定菜单栏对象(由水平排列的小图像组成)时,我正在使用弹出窗口.
在单击时,我希望弹出窗口锚定到被单击并显示在顶部的视图的左上角.
唯一似乎相关的方法是showAsDropDown(View anchor,int xoff,int yoff)和showAtLocation(View parent,int gravity,int x,int y).showAsDropDown的问题在于它锚定在视图的左下角.
还有其他方法可以实现吗?
Wil*_*iam 37
popupWindow.showAtLocation(...)实际上显示窗口绝对定位在屏幕上(甚至不是应用程序).该调用中的锚点仅用于其窗口令牌.坐标是给定重力的偏移量.
你真正想要使用的是:
popupWindow.showAsDropDown(anchor, offsetX, offsetY, gravity);
Run Code Online (Sandbox Code Playgroud)
此调用仅适用于API 19+,因此在早期版本中您需要使用:
popupWindow.showAsDropdown(anchor, offsetX, offsetY);
Run Code Online (Sandbox Code Playgroud)
这些调用显示相对于指定锚点视图的弹出窗口.请注意,默认重力(在没有指定重力的情况下调用时)是Gravity.TOP|Gravity.START如此,如果您明确Gravity.LEFT在应用程序中的各个位置使用,您将有一个糟糕的时间:)
popupWindow.showAtLocation(anchor, Gravity.BOTTOM, 0, anchor.getHeight());
Run Code Online (Sandbox Code Playgroud)
我写了一个示例 Kotlin 代码,它将PopupWindow在锚视图上方显示一个。
private fun showPopupWindow(anchor: View) {
PopupWindow(anchor.context).apply {
isOutsideTouchable = true
val inflater = LayoutInflater.from(anchor.context)
contentView = inflater.inflate(R.layout.popup_layout, null).apply {
measure(
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
)
}
}.also { popupWindow ->
// Absolute location of the anchor view
val location = IntArray(2).apply {
anchor.getLocationOnScreen(this)
}
val size = Size(
popupWindow.contentView.measuredWidth,
popupWindow.contentView.measuredHeight
)
popupWindow.showAtLocation(
anchor,
Gravity.TOP or Gravity.START,
location[0] - (size.width - anchor.width) / 2,
location[1] - size.height
)
}
}
Run Code Online (Sandbox Code Playgroud)
你想要使用的是showAtLocation(...).您指定锚视图(用户单击的视图),并通过gravity参数和偏移将其相对于该视图定位.可以想象gravity参数类似于PopupWindow子视图,父视图就像容器布局.
你应该能够Gravity.LEFT | Gravity.TOP作为参数.
您只需要使用showAsDropDown(View anchor,int xoff,int yoff)语法中的yoff参数将popupWindow按其锚点的高度移动。
popupWindow.showAsDropDown(anchor, 0, -anchor.getHeight()+popupView.getHeight);
Run Code Online (Sandbox Code Playgroud)
另外,请注意,如果允许锚定的最大高度不允许进行转换,则弹出窗口可能无法正确显示。
我有这个代码:PopupWindow在所有sdk版本的特定视图(Gravity End)下面.
// display the popup[![enter image description here][1]][1]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mPopupWindow.showAsDropDown(v, 0, 0, Gravity.END);
} else {
mPopupWindow.showAsDropDown(v, v.getWidth() - mPopupWindow.getWidth(), 0);
}
Run Code Online (Sandbox Code Playgroud)
这里View v是ImageButton Calendar.
| 归档时间: |
|
| 查看次数: |
36350 次 |
| 最近记录: |