Android开发PopupWindow的使用总结

版权声明:欢迎来到我的个人博客:http://blog.N0tExpectErr0r.cn https://blog.csdn.net/qq_21556263/article/details/82768340

PopupWindow的使用总结

PopupWindow是一个以弹窗的方式呈现的控件,可以利用它实现各种各样的弹窗效果,进行信息的展示或者UI的交互。

使用

使用PopupWindow非常简单,大概分为两步:

  1. 调用PopupWindow的构造器创建PopupWindow对象,并完成一些初始化设置。
  2. 调用PopupWindow的showAsDropDown(View view)将PopupWindow作为View组件的下拉组件显示出来;或调用PopupWindow的showAtLocation()方法将PopupWindow在指定位置显示出来。

创建及初始化设置

PopupWindow popupWindow = new PopupWindow(this); popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT); popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT); 
View view = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow_style01, null);
popupWindow.setContentView(view ); 
popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000)); popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);

其中setWidth、setHeight和setContentView这三个方法必须实现,否则将不会显示。

setwidth和setHeight的参数值可以是具体的数值,也可以是MATCH_PARENT或者是WRAP_CONTENT。

setContentView则是为PopupWindow设置视图内容。

setOutsideTouchable则决定了点击PopupWindow外的地方是否关闭窗口。

img

显示

显示popupWindow可以分为两种:

  • 附着于某个控件之下 showAsDropDown
  • 设置相对屏幕坐标 showAtLocation

附着于某个控件

默认情况下popupWindow会对齐这个控件的左下角 ,设置Gravity.RIGHT后,则对齐控件右下角。

void showAsDropDown (View anchor);

void showAsDropDown (View anchor, int xoff, int yoff);
                
void showAsDropDown (View anchor, int xoff, int yoff, int gravity);

相对于屏幕坐标

可以使popupWindow出现在屏幕任意位置

void showAtLocation (View parent, // 该属性只要是屏幕上任意控件对象即可
                int gravity, // 屏幕位置
                int x,  // 偏移坐标
                int y)

方法中的parent只要是屏幕的任意控件均可。

需要注意的是:多次调用showAtLocation方法,只有第一句生效。

猜你喜欢

转载自blog.csdn.net/qq_21556263/article/details/82768340