Window和WindowManager

来源:互联网 发布:80网络验证防 编辑:程序博客网 时间:2024/06/05 02:13

一.概述

1.1平时基本用不到除非遇到要实现一个如游戏中sdk的悬浮球或者如360手机助手中的悬浮球的功能。

1.2知识梳理

Window是个abstract的类,具体的实现是PhoneWindow,创建和使用通过WindowManager即可。Window是View的直接管理者,也不能脱离View产生意义。

Window有addView(View view, ViewGroup.LayoutParams params);(添加)

updateViewLayout(View view, ViewGroup.LayoutParams params);(刷新)

removeView(View view);(销毁)等三个方法。

2.简单实现

添加:

WindowManager winManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);WindowManager.LayoutParams mWmParams = new WindowManager.LayoutParams();mWmParams.gravity = Gravity.LEFT | Gravity.TOP;mWmParams.x = 20;mWmParams.y = 100;mWmParams.width = FrameLayout.LayoutParams.WRAP_CONTENT;mWmParams.height = FrameLayout.LayoutParams.WRAP_CONTENT;mWmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;mWmParams.type = WindowManager.LayoutParams.TYPE_TOAST;TextView txtView = new TextView(this);txtView.setText("测试Window");winManager.addView(txtView, mWmParams);

说明:

a.mWmParams.flags:用来标识是否处理手势事件

b.mWmParams.type:标定等级,分为应用Window(0~99),子Window(1000~1999),系统Window(2000~2999)三级。

刷新:(给activity添加了一个手势监听,这里只为了说明怎么更新window)

@Override    public boolean onTouchEvent(MotionEvent event) {        int rawX = (int) event.getRawX();        int rawY = (int) event.getRawY();        mWmParams.x = rawX;        mWmParams.y = rawY;        winManager.updateViewLayout(txtView, mWmParams);        return super.onTouchEvent(event);    }

三.sdk中用到Window的地方

3.1Activity中window

Activity中Window创建在attach方法中如下

final void attach(Context context, ActivityThread aThread,            Instrumentation instr, IBinder token, int ident,            Application application, Intent intent, ActivityInfo info,            CharSequence title, Activity parent, String id,            NonConfigurationInstances lastNonConfigurationInstances,            Configuration config, String referrer, IVoiceInteractor voiceInteractor,            Window window) {        ...省略代码...        mWindow = new PhoneWindow(this, window);        ...省略代码...    }

3.2Dialog中的Window

注意创建Dialog的时候context要用Activity的Context用Application的是不行的(里面用到token而Activity有Application没有)

3.3Toast中的Window

系统级别,但是如果关掉通知中心中的推送功能它就不能正常工作了,前面的文章中有解决方案。

原创粉丝点击