首先Popupwindow和alertDialog是经常拿来比较的,其区别在于Popupwindow是阻塞的,alertDialog是不阻塞的,看情况适时的选用。
首先说怎么实现Popupwindow弹出时和alertDialog一样的边缘背景半透明的效果,实现方法如下:
在Popupwindow要显示之前设置窗体透明度
WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.5f; getWindow().setAttributes(lp);
WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1f; getWindow().setAttributes(lp);
还有需要注意Popupwindow在创建之后需要设置背景setBackgroundDrawable();
如果不设置PopupWindow的背景,无论是点击外部区域还是Back键都无法dismiss弹框,即使是setOutsideTouchable(true);也没有用,而当我们设置了背景之后,即使setOutsideTouchable(false);点击非PopupWindow区域也会dismiss PopupWindow
最后我发现setOutsideTouchable方法并不是和alertDialog的setCancelable一样的作用(自以为是了一波),setOutsideTouchable方法的意思是,外部可点击,需要和setFocusable(false)配合使用,记住一定要是false,设置当PopupWindow弹出的时候父view依然可以获得焦点,否则即使你设置了setOutsideTouchable为true,父view也不会响应ontouchevent事件,设置了setFocusable(false)时候也有一个问题就是你按返回键的时候不会再dismiss PopupWindow,因为PopupWindow没有获得焦点,解决办法当然就是重写返回键的监听事件,也很简单。
基本上会有比较多不解的就上面这几个,好好理解理解
另如果想要实现点击外围不消失可参考:http://www.cnblogs.com/mengdd/p/3569127.html最后
本文还参考了:http://blog.csdn.net/hustpzb/article/details/7891803