public PopupWindow(View contentView, int width, int height, boolean focusable)
其中contentView为要显示的view,width和height为宽和高,值为像素值,也可以是MATCHT_PARENT和WRAP_CONTENT。还有:
public PopupWindow (Context context)
用这个构造方法初始化PopupWindow中的view则可以用这种方法:
PopupWindow popupWindow = new PopupWindow(context);
popupWindow.setContentView(contentview);
构造方法3:
public PopupWindow(View contentView, int width, int height)
因此这种构造方法的视图初始化可以是:
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentview = inflater.inflate(R.layout.popup_process, null);
PopupWindow popupWindow = new PopupWindow(contentview, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
构造方法4:
public PopupWindow(View contentView)
同样也可以得到它的初始化视图方法:
PopupWindow popupWindow = new PopupWindow(contentview);
popupWindow.setWidth(LayoutParams.WRAP_CONTENT);
popupWindow.setHeight(LayoutParams.WRAP_CONTENT);
显示PopupWindow:
-
showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
-
showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
-
showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
-
设置PopupWindow的高和宽:
有setWidth()、setHeigth方法,也可以在构造函数里面设置,构造方法3。必须设置高和宽,否则PopupWindow不会显示任何东西。其中,高度和宽度的具体数值可以使用精确的数字,也可以使用WindowManager.LayoutParams.WRAP_CONTENT、MATCH_PATENT等设置。高度和宽度都是显示的是PopupWindow的视图的大小,当该视图是来自XML文件的时候,那么xml的第一层view的大小属性将被忽略。相当于popupWindow的width和height属性直接和第一层View相对应,也就是将XML文件的第一层VIEW的大小当作Parent了。
点击PopupWindow外面的地方可以使其消失:
应该注意的是setOutsideTouchable方法并不会让点击外围的空白部分消失PopupWindow成功,即使它设置为true也不行,要成功消失PopupWindow要调用setBackgroundDrawable(new BitmapDrawable())方法才能成功,只是给它设置了一个背景,不影响总体视图,可以设置为空;但BitmapDrawable()方法已经被弃用了,用ColorDrawable(int color)更合适,比如new ColorDrawable(0x00000000);背景透明,不影响其它部分。
如果有背景,则会在contentView外面包一层PopupViewContainer之后作为mPopupView,如果没有背景,则直接用contentView作为mPopupView。
而这个PopupViewContainer是一个内部私有类,它继承了FrameLayout,在其中重写了Key和Touch事件的分发处理