使用WindowManager实现悬浮窗

Window表示一个窗体的概念。

所有的界面中的View其实都是依附在Window上。
我们可以通过WindowManager来对Window上的View进行管理。常见的方法有:

windowManager.addView(View,WindowManager.LayoutParam);
windowManager.removeView();
windowManager.getDefaultDisplay();

我们采用addView 来添加一个悬浮的按钮。
首先,先获取WindowManager实例。

WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);

然后在定义我们的按钮以及布局属性。

Button mFloatingButton = new Button(this);
mFloatingButton.setText("button");

这里属性就不详细写了。

WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(               WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT,0,0,
        PixelFormat.TRANSPARENT);
        layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
layoutParams.x = 100;
layoutParams.y = 300;

最后通过addView方法将按钮添加到window上:

windowManager.addView(mFloatingButton,layoutParams);

这里我们的功能略显得简单了,但是使用WindowManager来实现悬浮窗确是非常普遍的被使用。如我们平时见到的如下的界面:
这里写图片描述

上面使用了WindowManager添加了一个全屏的ImageView,并未ImageView添加了图片资源,实现了上述效果。

当然我们也还可以使用removeView来进行悬浮View的移除。
比如说我们自己的例子,便是在上面添加的悬浮按钮的点击事件中移除它。

mFloatingButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                windowManager.removeView(mFloatingButton);
            }
        });

点击之后移除成功。使用WIndowManager实现简单的悬浮窗就是这么简单!

注意:在添加View时,对布局参数的type属性一定要设置为:

layoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;

并在AndroidManifest.xml中声明相关权限。
不然会报错哟:

Process: com.example.zoutao.test, PID: 19346 java.lang.RuntimeException: Unable to start activity ComponentInfo
{com.example.zoutao.test/com.example.zoutao.test.MainActivity}: android.view.WindowManager$InvalidDisplayException: 
Unable to add window android.view.ViewRootImpl$W@38cabbd1 -- the specified window type is not valid                  

猜你喜欢

转载自blog.csdn.net/scuzoutao/article/details/77759014