PopupWindow组件的使用问题

时间:2023-03-09 23:48:40
PopupWindow组件的使用问题

//如果默认屏幕的话,父view就写自己

popupWindow.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);

PopupWindow 
顾名思义为弹出式菜单, 
不同于Dialag对话框,PopupWindow 
不会使宿主activity组件失去焦点, 
也就是说PopupWindow弹出后, 
你可以与宿主activity进行交互, 
Dialog却不能做到这一点。

注意:PopupWindow组件的使用问题,PopupWindow是一个阻塞对话框,如果你直接在Activity创建的方法中显示它,则会报错:android.view.WindowManager$BadTokenException:Unable to add window -- token null is not valid; is your activity running? 
总结: PopupWindow必须在某个事件中显示或者是开启一个新线程去调用,不能直接在onCreate方法中显示一个Popupwindow,否则永远会有以上的错误

常用设置: 
// PopupWindow定义,显示view,以及初始化长和宽  
PopupWindow menu = new PopupWindow(view, 200, 60);  
// 必须设置,否则获得焦点后页面上其他地方点击无响应  
menu.setBackgroundDrawable(new BitmapDrawable());  
// 设置焦点,必须设置,否则PopupWindow内的空间无法响应事件  
menu.setFocusable(true);  
// 设置点击其他地方 popupWindow消失    
menu.setOutsideTouchable(true);  
// 显示在某个位置  
menu.showAsDropDown(anchor);

除了setBackgroundDrawable(new BitmapDrawable());还可以使用下面两种解决页面无法响应问题 
a、处理响应 
有点麻烦,有兴趣可以自己看看http://zhoudan241.iteye.com/blog/1147730

b、最笨的方法将listView中元素拿出来放到LinearLayout中,对于非listView都无需设置setFocusable(true),从而解决问题,具体可以见http://blog.csdn.net/ihrthk/article/details/7338791 
但这种方法对于动态变化的菜单需要配置多份layout文件

//设置在屏幕

View inflate = LayoutInflater.from(this).inflate(R.layout.activity_main, null);

    	popupWindow.showAtLocation(inflate, Gravity.BOTTOM, 0,0);