PopupWindow跟AlertDialog类似,也是一种弹窗,最大的区别是前者可以指定任意的位置显示,而且可以使用任意布局的View作为其显示的内容。
PopupWindow的构造函数:
//方法一:
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)
PopupWindow虽然有四种构造函数,但是要显示PopupWindow就必须设置好contentView,width,heigh三个参数,少任意一个都不行。
focusable变量是不必须的。
contentView——是显示的布局文件的view
width——是view的宽度
heigh——是view的高度
focusable——是view是否获取到焦点
PopupWindow的显示函数:
//相对某个控件的位置(正左下方),无偏移
showAsDropDown(View anchor):
//相对某个控件的位置,有偏移;xoff表示x轴的偏移,正值表示向左,负值表示向右;yoff表示相对y轴的偏移,正值是向下,负值是向上;
showAsDropDown(View anchor, int xoff, int yoff):
//相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
showAtLocation(View parent, int gravity, int x, int y):
下面是一个PopupWindow显示的例子:
public void showPopupWindow(){
//创建PopupWindow
contentView2 = LayoutInflater.from(MainActivity.this).inflate(R.layout.iv_quality, null);
mPopWindow2 = new PopupWindow(contentView2, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
//点击popupwindow外部地方,popupwindow消失
mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
mPopWindow2.setAnimationStyle(R.style.AnimBottom);
Button btnHd = (Button) contentView2.findViewById(R.id.iv_quality_bt1);
Button btnEr = (Button) contentView2.findViewById(R.id.iv_quality_bt2);
Button btnFl = (Button) contentView2.findViewById(R.id.iv_quality_bt3);
Button btnCan = (Button) contentView2.findViewById(R.id.iv_quality_bt4);
btnHd.setOnClickListener(this);
btnCan.setOnClickListener(this);
btnEr.setOnClickListener(this);
btnFl.setOnClickListener(this);
//显示PopupWindow
rootView = LayoutInflater.from(MainActivity.this).inflate(R.layout.activity_main, null);
mPopWindow2.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
}