Android 悬浮窗体问题

通过WindowManager的addView方法创建View,这样产生出来的View根据WindowManager.LayoutParams属性不同,效果也就不同了。
比如创建系统顶级窗口,实现悬浮窗口效果!


WindowManager wm = getWindow().getWindowManager();
TextView bb = new TextView();
WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
wmParams.type=WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG; 
wmParams.format=PixelFormat.TRANSLUCENT;
wmParams.width=WindowManager.LayoutParams.MATCH_PARENT;
wmParams.height=WindowManager.LayoutParams.WRAP_CONTENT;


try{
wm.addView(bb, wmParams);  //
} catch(Exception e) {
//TODO
}


备注:
TYPE_APPLICATION_ATTACHED_DIALOG Window type: like TYPE_APPLICATION_PANEL, but layout of the window happens as that of a top-level window, not as a child of its container.
如上就可以添加一个悬浮的窗体,但是会存在这样一个问题,只有bb可以接受事件,但其后的一些空间如有触发点击事件则无法做到。分析原因,可能是通过WindowManager的
addView方法添加的view默认获取焦点,并且无法转移。
通过查阅资料,发现在WindowManager的LayoutParams属性中,有一个flag属性可以设置其相关的获取焦点状态。


FLAG_NOT_TOUCH_MODAL Window flag: Even when this window is focusable (its {@link #FLAG_NOT_FOCUSABLE is not set), allow any pointer events outside of the window to be sent to the windows behind it.


重新设置WindowManager.LayoutParams的相关属性。具体如下:




     WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION_ATTACHED_DIALOG,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                PixelFormat.TRANSLUCENT);
     params.gravity = Gravity.TOP;
       
然后,通过WindowManager的addView方法,重新把bb添加到屏幕上去就OK了。



你可能感兴趣的:(Android 悬浮窗体问题)