Android-WindowManger的应用

为什么需要使用WindowManger呢?当我们需要弹出View的时候,我觉得使用WindowManger来管理我们的弹窗是极佳的,我开始查看了PopWindow的源码,发现其中也是使用WindowManger来实现的,接下来我们就实现一个简单的功能,指定弹窗出现的位置。
这里写图片描述
首先介创建WindowManger的实例:

1.在Activity中
getWindownManger()方法;
2.不在Activity中
context.getApplication().getSystemService(WINDOW_SERVICE);

如此我们的到了windownManger对象,之后,我们需要向Window容器中添加View;
View view = new View(context);
//这里我们需要对WindowManager.LayoutParams进行配置
p = new WindowManager.LayoutParams();
p.flags = WindowManager.LayoutParams.FLAG_DITHER
//我这里让Window位于屏幕的左上角,这样方便定额为
p.gravity = Gravity.TOP|Gravity.LEFT;
//宽高(随意)
p.width = 300;
p.height = 300;
//让windown透明
//p.format = PixelFormat.RGBA_8888;
//设置动画(winowManger无法访问Application的资源,必须为系统资源才能识别)
p.windowAnimations = android.R.style.Animation_Translucent
//要讲Window显示在指定View的下部,所以要获取该View(下面的mButton)的位置
int location[] = new int[2];
mButton.getLocationInWindow(location);
//如此得到了想mButton的x,y位置
p.x = location[0];
p.y = location[1]+mButton.getheight();
mWindowManger.addView(rl,p);
好了,我们来看看效果吧:
这里写图片描述
为啥中间出现了间隔?
==》原因是WindowManger是不包括状态栏的,所以多出了状态栏的高度,好了这下我们就知道了如何处理了,去掉该高度就可以了
//获取状态栏的高度
Rect rec = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rec);
int statsh = rec.top;
p.y = location[1]+mButton.getheight()-statsh;
mWindowManger.addView(rl,p);
这下就ok了,效果如下图:
这里写图片描述

总结:能指定Widow显示的位置后,我想就能实现很多功能了,头条新闻点击进入,滑动动态退出效果,自定义悬浮窗等等,应该就不是什么难事了。这是我第一次写,还请多多包涵,错误之处,还请指出,大家一起共勉。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值