Android常用控件之PopupWindow详解

来源:互联网 发布:云控软件 编辑:程序博客网 时间:2024/04/28 02:35

定义

A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current activity.

PopupWindow即弹出框可以被用来显示任意的一个视图,它是一个悬浮在当前界面上部的容器。

构造方法

PopupWindow有很多构造方法,我们一般使用的是PopupWindow(View contentView, int width, int height, boolean focusable)方法来构造一个PopupWindow

22222222

常用方法

常用的方法有
这里写图片描述

可以通过这三个方法里将PopupWindow显示到对应于某一控件的任何位置。

showAsDropDown(View anchor)方法:将PopupWindow中的视图固定在anchor视图的左下角,默认偏移量为0.示例:

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);        View popup = inflater.inflate(R.layout.popup_window, null);        popupWindow = new PopupWindow(popup, LayoutParams.WRAP_CONTENT, 120,                true);        popupWindow.setOutsideTouchable(false);        popupWindow.setBackgroundDrawable(new BitmapDrawable());        // popupWindow已目标控件的左下方为基准显示,默认偏移量为0;        popupWindow.showAsDropDown(popupButton);

这里写图片描述

showAsDropDown(View anchor,int xoff,int yoff)方法:将PopupWindow中的视图固定在anchor视图的左下角,x,y偏移量分别为xoff,yoff.,偏移量均是相对于anchor视图的左下角定义的!示例:

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);        View popup = inflater.inflate(R.layout.popup_window, null);        popupWindow = new PopupWindow(popup, LayoutParams.WRAP_CONTENT, 120,                true);        popupWindow.setOutsideTouchable(false);        popupWindow.setBackgroundDrawable(new BitmapDrawable());        // popupWindow已目标控件的左下方为基准显示,默认偏移量为0;        // popupWindow.showAsDropDown(popupButton);        // popupWindow已目标控件的左下方为基准显示,x偏移量为0y偏移量为Button的高度与PopupWindow高度之和的负值,即PopupWindow显示在Button的上方        popupWindow.showAsDropDown(popupButton, 0,                -(popupButton.getHeight() + popupWindow.getHeight()));

注意使用PopupWindow.getHeight()方法时,应确保PopupWindow的高度为一确定值,不能为WRAPCONTENT,否则该方法返回的是负值!
这里写图片描述

showAtLocation (View parent, int gravity, int x, int y) 方法: 将视图显示在特定的方向。x,y分别为PopupWindow的x,y偏移量,此偏移量是相对于整个屏幕来说的,gravity则定义了整个屏幕内的基准方向,Gravity.NO_GRAVITY相当于Gravity.LEFT|Gravtiy.TOP.
这里写图片描述

注意事项

1.PopupWindow点击外部区域消失的问题
如果想要实现点击外部区域消失的话必须要设置backgroundDrawable(),否则,无论设置OutsideTouchable()为true或false都将无效,点击外部区域或按下返回键都无任何反应。
如果设置了backgroundDrawable(),则论设置OutsideTouchable()为true或false,点击外部区域或按下返回键PopupWindow都将消失。So。。。Why??

0 0