Window与WindowManager

基础

        Window是应用的主窗口,它的具体实现子类为PhoneWindow。对于Window的操作,都是通过WindowManager进行的。而WindowManager只是一个接口,它的具体实现子类为WindowManagerImpl。

使用

        对于WindowManager的操作,非常简单。如下:

        TextView tv = new TextView(this);
        tv.setTextColor(Color.WHITE);
        tv.setText("window");
        tv.setBackgroundColor(Color.BLACK);
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams();;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.width = WindowManager.LayoutParams.WRAP_CONTENT;
        params.format = PixelFormat.OPAQUE;
        params.type = WindowManager.LayoutParams.TYPE_TOAST;
        params.setTitle("Toast");
        params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        WindowManager mWindowManager = (WindowManager)getApplication().getSystemService(WINDOW_SERVICE);
        mWindowManager.addView(tv,params);
//        mWindowManager.removeView(tv);
//        mWindowManager.updateViewLayout(tv,params);
WindowManager继承于ViewManager,提供的方法比较少,见名知义。如下:

    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);

addView()

        由于WindowManager是一个接口,因此该方法的实现在WindowManagerImpl.java中,而在该类中会将实现又交给了mGlobal完成(桥接模式),它是一个WindowManagerGlobal对象,而WindowManagerGlobal#addView()最终又会调用到如下代码:

try {
            root.setView(view, wparams, panelParentView);//root为ViewRootImpl对象
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
因此,最终的添加会调用到ViewRootImpl#setView()方法。



你可能感兴趣的:(Window与WindowManager)