android杂记AndroidAndroid View

从requestLayout()初探View的绘制原理

2016-12-22  本文已影响849人  houskii

在自定义View时,涉及到View的大小变化时,通常会涉及到一个函数requestLayout(),字面意思大家都知道是要求重新执行View的绘制中的layout,但是requestLayout()是如何做到让View重新绘制的呢?只是简单调用本身的layout(...)方法么?

    public void requestLayout() {
        ...
        if (mParent != null && !mParent.isLayoutRequested()) {
            mParent.requestLayout();
        }
        ....
    }

可以看到,View类的requestLayout()是调用ViewParentrequestLayout()方法,但是ViewParent类只是一个接口没有实现,所以我们去找mParent的引用。

我们逐级打印出mParent,会发现最后指向了PhoneWindow$DecorView,也就是我们常说的根View。但是再看下去,发现DecorView其实是FrameLayout的子类,也就是说又指回了View,这下似乎陷入了循环……

mParent也只有在assignParent方法中实现了赋值,但View类本身并没有调用这个方法

void assignParent(ViewParent parent) {
        if (mParent == null) {
            mParent = parent;
        } else if (parent == null) {
            mParent = null;
        } else {
            throw new RuntimeException("view " + this + " being added, but"
                    + " it already has a parent");
        }
    }

那么我们只能从DecorView生成的地方来考虑了,众所周知DecorView作为Activity的根View,那么肯定和Activity生成的地方有关。我们从Activity的创建开始找,最后在ActivityThread类中的handleResumeActivity()方法中,找到对Activity中DecorView的赋值

 final void handleResumeActivity(IBinder token, boolean clearHide, boolean isForward, boolean reallyResume) {
        ...
        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 the window has already been added, but during resume
            // we started another activity, then don't yet make the
            // window visible.
            }
        ...
        }

getDecorView()Window类下的一个抽象方法,而Android中实现了Window的类只有PhoneWindow,于是我们去PhoneWindow中找

这里说明一点,mDecor的创建时间并不是调用getDecorView()时,而是ActivityonCreate方法,因为ActivityThread先调用了performLaunchActivity方法创建了activity并执行onCreate方法,而onCreate方法中的setContentView会调用PhoneWindowsetContentView方法,这里最先执行了installDecor()

@Override
    public final View getDecorView() {
        if (mDecor == null) {
            installDecor();
        }
        return mDecor;
    }
    
   private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor();
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        }
        
  protected DecorView generateDecor() {
        return new DecorView(getContext(), -1);
  }

好像还是没有线索……但是我们发现在handleResumeActivity方法中DecorView的实例最后被一个ViewManager的子类WindowManager通过addView()添加进去了,会不会跟这个WindowManager有关系呢?

//handleResumeActivity中指向的方法,在Activity.java中
public WindowManager getWindowManager() {
        return mWindowManager;
    }

指向了Activity中的一个变量mWindowManager,其在Activityattach方法中被初始化

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) {
            ...
            mWindowManager = mWindow.getWindowManager();
            ...
           }

调用到Window类中的方法

/**
     * Return the window manager allowing this Window to display its own
     * windows.
     *
     * @return WindowManager The ViewManager.
     */
    public WindowManager getWindowManager() {
        return mWindowManager;
    }

再去找mWindowManager赋值的地方

 public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
            boolean hardwareAccelerated) {
        if (wm == null) {
            wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
        }
        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
    }

终于发现了一个不一样的类WindowManagerImpl,这应该就是实现了WindowManager接口的类,看下它的addView()方法

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

又扔给了一个mGlobal变量,这个变量属于WindowManagerGlobal类,可以看下这个类的介绍

**
 * Provides low-level communication with the system window manager for
 * operations that are not associated with any particular context.
 *
 * This class is only used internally to implement global functions where
 * the caller already knows the display and relevant compatibility information
 * for the operation.  For most purposes, you should use {@link WindowManager} instead
 * since it is bound to a context.

呃……英文不好自行找词典,大概意思就是提供了一个全局变量来实现底层系统与表现层的沟通,再来看他的addView()方法

public void addView(View view, ViewGroup.LayoutParams params,Display display, Window parentWindow) {
         ViewRootImpl root;
         synchronized (mLock) {
            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        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;
        }
}

可以看到,这里最关键的操作就是初始化了一个ViewRootImpl类的对象,调用它的setView方法注入之前的View。

那么ViewRootImpl类是什么?它的setView方法又做了什么呢?

我们先来看一下ViewRootImlp类的Javadoc

* The top of a view hierarchy, implementing the needed protocol between View
 * and the WindowManager.  This is for the most part an internal implementation
 * detail of {@link WindowManagerGlobal}.
 public final class ViewRootImpl implements ViewParent,
        View.AttachInfo.Callbacks, HardwareRenderer.HardwareDrawCallbacks
        
//View阶层的顶级,实现了View和WindowManager之间需要的协议,这是WindowManagerGlobal

来研究一下它的setView方法

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if(mView ==null){
                 //省略了部分无关代码
                 mView = view;
                requestLayout();
                ...
                view.assignParent(this); 
            }
        }
}

可以看到,setView方法基本只有在第一次调用时才会生效,它先调用了自己的requestLayout()方法,然后又调用ViewassignParent(ViewParent v)方法把自己注入View中

这下就可以确定View最上层的mParent变量,最终指向的是ViewParentImpl类的实例引用

那让我们再来看看ViewParentImpl中如何实现requestLayout()方法的

@Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread(); //这里是Android中为什么不能用子线程修改ui的关键
            mLayoutRequested = true; //修改标记为true
            scheduleTraversals();
        }
    }

众所周知,Android中是不能用子线程来更新ui的,原因就是在于ViewRootImpl类中的requestLayout方法在执行时,会首先检查当前线程是否是ViewRootImpl实例创建的线程。而唯一的ViewRootImpl对象是在主线程中被系统创建的。所以子线程中更新ui,就会导致checkThread()方法验证失败而抛出异常

除了checkThread()以外,还执行了scheduleTraversals()方法

void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

这里执行了Choreographer类的实例的postCallback方法,方法最后将这个Runnable放入Message中发出到MessageQueue中并执行,我们来看这个Runnable做了什么

final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
    
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();

再看看doTraversal()

void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }

            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }

其中最关键的是执行了performTraversals()方法,这也是View绘制中最关键的一个方法

private void performTraversals() {
     //省略了部分无关代码
     final View host = mView;
     ...
     host.dispatchAttachedToWindow(mAttachInfo, 0);//注入AttachInfo
     ...
     boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
     if (layoutRequested) {
            mLayoutRequested = false;   //清除标记
     }
     ...
     if (!mStopped || mReportNextDraw) {
            ...
            int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
            int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
            ...
     }
     ...
     final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
     if (didLayout) {
            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
     }
     ...
     boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() ||
                viewVisibility != View.VISIBLE;
        if (!cancelDraw && !newSurface) {
            if (!skipDraw || mReportNextDraw) {
                ...
                performDraw();
            }
        }
     ...
}

其中performMeasureperformLayoutperformDraw最后基本都是去执行了View的measure、layout、draw方法,这也是View绘制三大步骤调用的时间点。

这里我还特地标注一下host.dispatchAttachedToWindow(mAttachInfo, 0)方法,这个方法给View中注入了mAttachInfo的引用,而mAttachInfo的初始化是在ViewRootImpl的构造函数里

public ViewRootImpl(Context context, Display display) {
    ...
    mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
    ...
}

AttachInfo这个类基本就是提供各种底层信息的,借此,Window和View的联系就建立起来了。

最后上一张图来整理下整个调用链

requestLayout

最后欢迎关注我的GithubBlog

上一篇下一篇

猜你喜欢

热点阅读