使用WindowManager实现悬浮窗
来源:互联网 发布:linux 下编程工具 编辑:程序博客网 时间:2024/05/22 02:00
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
阅读全文
0 0
- 使用WindowManager实现悬浮窗
- 使用WindowManager实现悬浮窗
- Android悬浮窗实现 使用WindowManager
- Android悬浮窗实现 使用WindowManager
- Android悬浮窗实现 使用WindowManager
- Android悬浮窗实现 使用WindowManager
- Android悬浮窗实现 使用WindowManager
- Android悬浮窗实现 使用WindowManager
- Android悬浮窗实现 使用WindowManager
- 使用WindowManager实现Android悬浮窗
- Android悬浮窗实现 使用WindowManager
- Android使用WindowManager实现悬浮窗
- WindowManager实现悬浮窗
- 使用WindowManager实现悬浮窗口
- 利用WindowManager实现悬浮窗
- WindowManager 实现悬浮窗 详解
- Android 使用WindowManager实现悬浮窗及源码解析
- Android 使用WindowManager实现悬浮窗及源码解析
- 《MySQL入门很简单》学习笔记(5)之第5章操作数据库(关键词:数据库/创建数据库/删除数据库/存储引擎)
- 视频 秒开,美颜,卡顿
- Linux驱动学习之:PWM驱动
- Django之分页功能
- C++
- 使用WindowManager实现悬浮窗
- Excel中Vlookup公式和IFError公式的使用
- linux驱动中使用定时器的设置
- YP.1.1 What We Will Try to Do and 1.2 How We Will Get There(双语)
- 告诉各位为如何学习linux系统
- 年度总结-感谢遇见
- 两个栈实现一个队列,两个队列实现一个栈-JAVA
- poj 4124:海贼王之伟大航路
- ACM-8月31号周四周中训练心得