一、概述
项目中使用很多弹窗,大部分都是了AlertDialog,Dialog,DialogFragment还没用过PopUpWindow,这次有时间看一下相关知识,
PopUpWindow 表示一个可用于显示任意视图的弹出窗口。弹出窗口是一个浮动容器,出现在当前activity的顶部。AlertDialog不能指定显示位置,只能默认显示在屏幕最中间(当然也可以通过设置WindowManager参数来改变位置),而PopupWindow是可以指定显示位置的,随便哪个位置都可以,更加灵活。
二、使用方法
1、创建
1.1、常用四种构造方法
//方法一:
public PopupWindow (Context context)
//方法二:
public PopupWindow(View contentView)
//方法三:
public PopupWindow(View contentView, int width, int height)
//方法四:
public PopupWindow(View contentView, int width, int height, boolean focusable)
1.2、创建PopuWindow必要的三个条件:
void setHeight (int height) // 因为PopupWindow没有默认布局所以必须指定宽高
void setWidth (int width)
void setContentView (View contentView) // 需要显示的内容
1.3、使用布局中的宽高
PopupWindow popupWindow = new PopupWindow(popupView,
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
2.显示/隐藏
显示PopupWindow可以分为两种方式:
- 附着某个控件
showAsDropDown
- 设置屏幕坐标
showAtLocation
隐藏将窗体 void dismiss ()
2.1、相对于当前控件
默认是PopupWindow的左上角对其控件的左下角
// 弹窗显示在anchor控件左下方
void showAsDropDown (View anchor)
// 以控件左下角为原点的偏移坐标
void showAsDropDown (View anchor,
int xoff,
int yoff)
// 弹窗显示在控件的左下方还是右下方, 参数Gravity.RIGHT/Gravity.LEFT. 默认是左下方
void showAsDropDown (View anchor,
int xoff,
int yoff,
int gravity)
2.2、相对于当前窗口
当前窗口的任意位置(不包括状态栏)
void showAtLocation (View parent, // 该属性只要是屏幕上任意控件对象即可
int gravity, // 屏幕位置
int x, // 偏移坐标
int y)
parent:该属性只要是当前任意控件对象即可(View和ViewGroup都行), 官方文档介绍该对象参数主要是为了得到该对象的getWindowToken()
方法.
参考文章PopUpWindow使用详解