从ViewRootImpl开始,分析View的原理

本文详细解析了Android中视图的绘制流程,从Activity启动到视图显示的过程,包括DecorView的创建、添加及显示,以及View的绘制原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

通过http://blog.youkuaiyun.com/super_kingking/article/details/52486966这篇博客,我们知道了怎么样加载自定义的xml添加到DecorView中,但是DecorView是怎么添加到窗口的呢?

View是android的视图呈现方式,view不能单独存在,必须依附于window,那要了解window的创建过程,我们必须要了解activity的启动启动过程。activity的启动过程比较复杂(不作为本次的重点讨论对象),但是最终在ActivityThread的performLaunchActivity()来完成整个启动过程。在activity的attach()方法中创建window对象
mWindow = PolicyManager.makeNewWindow(this);
mWindow.setCallback(this);

由于activity实现了window的内部接口calllback,,当window接收到外界的状体改变时,就会回调activity的方法。

 public void setContentView(int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

window创建完毕,然后通过activity提供的getWindow().setContentView(layoutResID);`里面包含了DecorView的创建和添加自定义的xml加载到DecorView中(如有疑问查看上篇博客http://blog.youkuaiyun.com/super_kingking/article/details/52486966)。虽然这时window和decorView都被创建,但是decorView并没有被windowManager识别,并不能显示。在activityThread的handleResumeActivity方法中

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume) {

----------

        //调用该方法
        ActivityClientRecord r = performResumeActivity(token, clearHide);
                    ----------



            if (r.window == null && !a.mFinished && willBeVisible) {
                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (a.mVisibleFromClient) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                }
                    ----------
         if (!r.activity.mFinished && willBeVisible
                    && r.activity.mDecor != null && !r.hideForNow) {
                   .................
                if (r.activity.mVisibleFromClient) {
                    r.activity.makeVisible();
                }  
}        

首先会调用performResumeActivity();

public final ActivityClientRecord performResumeActivity(IBinder token,
            boolean clearHide) {
        ActivityClientRecord r = mActivities.get(token);    
                    ----------
                r.activity.performResume();   
                    ----------

此处调用的是activity的performResume()方法,进入该方法源码查看

    final void performResume() {

                        ----------

        // mResumed is set by the instrumentation
        mInstrumentation.callActivityOnResume(this);
                   ----------

进入callActivityOnResume()会看到

  public void callActivityOnResume(Activity activity) {
                ----------
        activity.onResume();
                ----------       

最调用的是acitivity的onResume()方法。接着看handleResumeActivity方法,

 if (!r.activity.mFinished && willBeVisible
                  && r.activity.mDecor != null && !r.hideForNow) {
                   .................
                        if (r.activity.mVisibleFromClient) {
                        r.activity.makeVisible();
                } 

如果activity没有结束,要显示,decoreView不为null……等条件后,调用了activity.makeVisible();
查看activity的makeVisiable()方法;

 void makeVisible() {
        if (!mWindowAdded) {
        //viewManager是个接口,在其实现类WindowManagerImpl中实现
            ViewManager wm = getWindowManager();
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        mDecor.setVisibility(View.VISIBLE);
    }

if (!mWindowAdded)判断如果window没有被添加,创建windowmanager对象,调用 wm.addView(mDecor, getWindow().getAttributes());mDecor.setVisibility(View.VISIBLE);

在makevisible()方法中,decorView被添加和显示,activity的视图才能被看见。 这是为什么在activity的OnResume方法中,界面才开始显示的原因。

View是怎么绘制的?看代码 wm.addView(mDecor, getWindow().getAttributes())的源码

public interface ViewManager
{
//WindowManager是viewManager的子类,主要对View的增删改操作
    public void addView(View view, ViewGroup.LayoutParams params);
    public void updateViewLayout(View view, ViewGroup.LayoutParams params);
    public void removeView(View view);
}

进入了接口viewManager,查看其实现类,WindowManagerImpl.java

  @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }

mGlobal是WindowManagerGlobal的对象,查看mGlobal.addView方法

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        if (view == null) {
            throw new IllegalArgumentException("view must not be null");
        }
        if (display == null) {
            throw new IllegalArgumentException("display must not be null");
        }
        if (!(params instanceof WindowManager.LayoutParams)) {
            throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
        }

        final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
        if (parentWindow != null) {
            parentWindow.adjustLayoutParamsForSubWindow(wparams);
        } else {
            // If there's no parent, then hardware acceleration for this view is
            // set from the application's hardware acceleration setting.
            final Context context = view.getContext();
            if (context != null
                    && (context.getApplicationInfo().flags
                            & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
                wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            }
        }

        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {
            // Start watching for system property changes.
            if (mSystemPropertyUpdater == null) {
                mSystemPropertyUpdater = new Runnable() {
                    @Override public void run() {
                        synchronized (mLock) {
                            for (int i = mRoots.size() - 1; i >= 0; --i) {
                                mRoots.get(i).loadSystemProperties();
                            }
                        }
                    }
                };
                SystemProperties.addChangeCallback(mSystemPropertyUpdater);
            }

            int index = findViewLocked(view, false);
            if (index >= 0) {
                if (mDyingViews.contains(view)) {
                    // Don't wait for MSG_DIE to make it's way through root's queue.
                    mRoots.get(index).doDie();
                } else {
                    throw new IllegalStateException("View " + view
                            + " has already been added to the window manager.");
                }
                // The previous removeView() had not completed executing. Now it has.
            }

            // If this is a panel window, then find the window it is being
            // attached to for future reference.
            if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
                    wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
                final int count = mViews.size();
                for (int i = 0; i < count; i++) {
                    if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
                        panelParentView = mViews.get(i);
                    }
                }
            }

            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        }

        // do this last because it fires off messages to start doing things
        try {
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
    }

在WindowManagerGlobal内部有如下几个列表比较重要:

private final ArrayList<View> mViews = new ArrayList<View>();  
private final ArrayList<ViewRootImpl> mRoots = new ArrayList<ViewRootImpl>();  
private final ArrayList<WindowManager.LayoutParams> mParams =  
        new ArrayList<WindowManager.LayoutParams>();  
private final ArraySet<View> mDyingViews = new ArraySet<View>(); 

在上面的声明中吗,mViews存储的是所有Window所对应的View,mRoots存储的是所有Window所对应的ViewRootImpl,mParams存储的是所有Window所对应的布局参数,而mDyingViews存储了那些正在被删除的View对象,或者说是那些已经调用removeView方法但是还没有删除的Window对象。在addView方法中通过如下方式将Window的一系列对象添加到列表中。

root = new ViewRootImpl(view.getContext(), display);  

view.setLayoutParams(wparams);  

mViews.add(view);  
mRoots.add(root);  
mParams.add(wparams);

通过ViewRootImpl来更新界面并完成Window的添加过程
这个步骤由ViewRootImpl的setView方法来完成

root.setView(view, wparams, panelParentView);  

view的绘制过程通过ViewRootImpl来完成,
setView方法内部会通过requestLayout来完成异步刷新请求。scheduletraversals是view绘制的入口。最后进入performTraversals()函数。

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值