窗口机制系列

PhoneWindow DecorView View之间的关系,

2017-12-01  本文已影响0人  浪浪许

PhoneWindow DecorView 和 View之间的关系如图所示

PhoneWindow_DecorView_View关系图.png

在activity中,通常我们通过 setContentView(R.layout.activity_main) 加载一个布局就能显示出一个界面,那么我们看看源码,瞧瞧这行代码背后做了些什么,可以让界面显示出来。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

setContentView源码分析

  AppCompatActivity

 @Override
    public void setContentView(@LayoutRes int layoutResID) {
        //点击setContentView发现是一个抽象方法,那么找它的实现类
        getDelegate().setContentView(layoutResID);
    }
@NonNull
    public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
    }
 public static AppCompatDelegate create(Activity activity, AppCompatCallback callback) {
        return create(activity, activity.getWindow(), callback);
    }
    private static AppCompatDelegate create(Context context, Window window,
            AppCompatCallback callback) {
        final int sdk = Build.VERSION.SDK_INT;
        if (BuildCompat.isAtLeastN()) {
            return new AppCompatDelegateImplN(context, window, callback);
        } else if (sdk >= 23) {
            return new AppCompatDelegateImplV23(context, window, callback);
        } else if (sdk >= 14) {
            return new AppCompatDelegateImplV14(context, window, callback);
        } else if (sdk >= 11) {
            return new AppCompatDelegateImplV11(context, window, callback);
        } else {
            return new AppCompatDelegateImplV9(context, window, callback);
        }
    }

    //随便找一个类进入查看实现方法 这里我点击进入 AppCompatDelegateImplV9
  //在AppCompatDelegateImplV9里面找到setContentView方法
  @Override
    public void setContentView(View v) {//这个方法由几个构造,有      //setContentView(int resId) 通过资源id的形式加载我们的布局
        //创建DecorView加载系统布局
        ensureSubDecor();
        //在DecorView添加的系统布局Fraglayout(ViewGroup)里
        //findViewById获取系统跟布局的id android.R.id.content获取跟布局容器
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        //移除跟布局容器里面的所有子View
        contentParent.removeAllViews();  
        //添加我们通过setContentView设置过来的布局
        contentParent.addView(v);
        mOriginalWindowCallback.onContentChanged();
    }
 private void ensureSubDecor() {
        if (!mSubDecorInstalled) {
            mSubDecor = createSubDecor();

            ...代码省略 我们只关心我们关注的重点

            onSubDecorInstalled(mSubDecor);

            mSubDecorInstalled = true;
            ...代码省略 
        }
    }
    private ViewGroup createSubDecor() {
      ..代码省略
       // Now let's make sure that the Window has installed its decor by retrieving it
        mWindow.getDecorView();//获取DecorView

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup subDecor = null;

        ...代码省略
        final ContentFrameLayout contentView = (ContentFrameLayout) subDecor.findViewById(
                R.id.action_bar_activity_content);

        final ViewGroup windowContentView = (ViewGroup) mWindow.findViewById(android.R.id.content);//系统根布局
        if (windowContentView != null) {
            // There might be Views already added to the Window's content view so we need to
            // migrate them to our content view
            while (windowContentView.getChildCount() > 0) {
                final View child = windowContentView.getChildAt(0);
                windowContentView.removeViewAt(0);
                contentView.addView(child);
            }

            // Change our content FrameLayout to use the android.R.id.content id.
            // Useful for fragments.
            windowContentView.setId(View.NO_ID);
            contentView.setId(android.R.id.content);

            // The decorContent may have a foreground drawable set (windowContentOverlay).
            // Remove this as we handle it ourselves
            if (windowContentView instanceof FrameLayout) {
                ((FrameLayout) windowContentView).setForeground(null);
            }
        }
        // Now set the Window's content view with the decor
        mWindow.setContentView(subDecor);//调用windwow的setContentView
        return subDecor;
    }
  PhoneWindow(Window的实现类)的setContentView

 @Override
    public void setContentView(int layoutResID) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            //调用此方法会走 ViewRootImpl的requestLayout方法
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

查看ViewRootImpl源码 对View的绘制流程分析

    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            //检查线程  子线程不能更新UI的原因也是这个,更新UI会走ViewRootImpl,然后会进行线程检查
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

    void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            //重点关注mTraversalRunnable 
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }
  final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
   final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }
  
    void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);

            if (mProfile) {
                Debug.startMethodTracing("ViewAncestor");
            }
            //View的绘制流程从这里开始
            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }
 View的绘制流程从这里开始

 private void performTraversals() {
         ···
          //View的绘制流程第一步 测量 
          performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
         ···
          //View的绘制流程第二部 摆放
           performLayout(lp, mWidth, mHeight);
          ···
         //View的绘制流程第三部 绘制
         performDraw();
        }
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
        try {
            //调用View的measure方法
            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }
 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        mLayoutRequested = false;
        mScrollMayChange = true;
        mInLayout = true;

        final View host = mView;
        ···
        调用View的layout
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
        ···
        mInLayout = false;
    }

    private void performDraw() {
        if (mAttachInfo.mDisplayState == Display.STATE_OFF && !mReportNextDraw) {
            return;
        }

        final boolean fullRedrawNeeded = mFullRedrawNeeded;
        mFullRedrawNeeded = false;

        mIsDrawing = true;
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "draw");
        try {
            draw(fullRedrawNeeded);
        } finally {
            mIsDrawing = false;
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
        ····
    }
    private void draw(boolean fullRedrawNeeded) {

                ...

                if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
                    return;
                }
            }
        }

        if (animating) {
            mFullRedrawNeeded = true;
            scheduleTraversals();
        }
    }
   private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {

           ···
            //调用View的Draw方法
            mView.draw(canvas);
          ··
        }
上一篇下一篇

猜你喜欢

热点阅读