PopupWindow
一:什么是PopupWindow?
PopupWindow可以创建类似对话框风格的窗口。
弹出窗口(PopupWindow)用来显示一个的任意的视图(view),通常浮动在当前Acitivty之上。
二:如何正确使用PopupWindow呢?
使用它创建对话框风格的窗口只要以下步骤:
①调用PopupWindow的构造器创建PopupWindow对象;
②调用PopupWindow的showAsDrawDown(View v)将PopupWindow作为V组件的下拉组件显示出来
或调用PopupWindow的showAtLocation()方法将PopupWindow在指定位置显示出来。
三:PopupWindow类
构造方法1:
构造方法2:
常用的方法:
public void setAnimationStyle(int animationStyle)——改变窗口显示与消失时的动态样式
注:如果窗口已经显示过,更改此值只能在下一次显示时起作用,或者调用update()方法。
public void setContentView(View contentView)——设置弹出窗口包含的视图
public boolean isFocusable() ——返回当前弹出窗口是否可获得焦点
public boolean isShowing()——判断当前窗口是否已显示
public void showAtLocation(View parent, int gravity, int x, int y)——指定弹出窗口显示的位置。
public void update()——更新弹出窗口的状态, 一些状态:
eg :
LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View menuView = (View)mLayoutInflater.inflate(R.layout.alert_dialog_menu_layout_new, null, true);
//弹出窗口包含的视图
popupWindow = new PopupWindow(menuView, LayoutParams.FILL_PARENT,238, true);
//创建弹出窗口,指定大小
//设置弹出窗口的背景
popupWindow.setAnimationStyle(R.style.PopupAnimation);//设置窗口显示的动画效果
popupWindow.showAtLocation(findViewById(R.id.parent), Gravity.BOTTOM, 0, 0);//设置窗口显示的位置
popupWindow.update();
Style.xml文件:
Meun_up.xml文件:
<set
</set>
五:
PopupWindow的位置按照有无偏移分,可以分为偏移和无偏移两种;
按照参照物的不同,可以分为相对于某个控件(Anchor锚)和相对于父控件。具体如下
- showAsDropDown(View anchor):相对某个控件的位置(正左下方),无偏移
- showAsDropDown(View anchor, int xoff, int yoff):相对某个控件的位置,有偏移
- showAtLocation(View parent, int gravity, int x, int y):相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
注:eg:
pw = new PopupWindow(lv,et_number.getWidth(),200);//显示的view 宽度 高度
//设置可以获得焦点
pw.setFocusable(true);
//窗体外触摸可以关掉窗体
pw.setOutsideTouchable(true);
pw.setBackgroundDrawable(new BitmapDrawable());
//显示
pw.showAsDropDown(et_number, 0, -5);//et_number 确定相对参照物 相对x值 相对y值
解释: mPop.setOutsideTouchable(true);//这里设置显示PopuWindow之后在外面点击是否有效。如果为false的话,那么点击PopuWindow外面并不会关闭PopuWindow。当然这里很明显只能在Touchable下才能使用。
当有mPop.setFocusable(false);的时候,说明PopuWindow不能获得焦点,即使设置设置了背景不为空也不能点击外面消失,只能由dismiss()消失,但是外面的View的事件还是可以触发,back键也可以顺利dismiss掉。当设置为popuWindow.setFocusable(true);的时候,加上下面两行设置背景代码,点击外面和Back键才会消失。
mPop.setFocusable(true);
需要顺利让PopUpWindow
六:
总结:
1、为PopupWindow的view布局,通过LayoutInflator获取布局的view.如:
LayoutInflater
this.anchor.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View
2、显示位置,可以有很多方式设置显示方式
pop.showAtLocation(findViewById(R.id.ll2),
或者
pop.showAsDropDown(View anchor, int xoff, int yoff)
3、进出场动画
pop.setAnimationStyle(R.style.PopupAnimation);
4、点击PopupWindow区域外部,PopupWindow消失
this.window.setTouchInterceptor(new
@Override
public
if(event.getAction()
BetterPopupWindow.this.window.dismiss();
return
}
return
}