Android自定义View自定义view

源码阅读分析-view的绘制流程

2018-07-07  本文已影响3人  Peakmain

高级面试题:首先看案例

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.text_view);
        Log.e("TAG", "height1 -> " + mTextView.getMeasuredHeight()); // 0

        mTextView.post(new Runnable() {
            // 保存到Queue中,什么都没干,会在dispatchAttachedToWindow会在测量完毕之后调用中执行,executeActions()
            @Override
            public void run() {
                Log.e("TAG", "height2 -> " + mTextView.getMeasuredHeight()); // 高度
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.e("TAG", "height3 -> " + mTextView.getMeasuredHeight()); // 0
    }

}

上面我们可以看到oncreate和onResume中获得高度为0,即没有获得高度,而开个线程后会获得高度,这是为什么?

首先我们需要了解activity的启动流程,我以前写过一篇文章,但是只有流程图,今天也不详细说,若有需要则会抽时间写一篇文章,android插件化架构-activity的启动流程https://www.jianshu.com/p/911ec7004301也写过一篇文章invalidate和postinvalidate源码分析https://www.jianshu.com/p/6c5d65009ba1

我们直接从Activity的启动流程的handleResumeActivity源码开始分析

//首先会走这个方法,这个方法会走向activity的onResume方法,这时候还是没有调用onMeasure方法
 r = performResumeActivity(token, clearHide, reason);
  ....
//之后会调用这个方法,我们点击进去后会发现这是个抽象方法,我们看wm的实例怎么创建的
 wm.addView(decor, l);
//我们会发现这个方法会创建一个WindowManager
 ViewManager wm = a.getWindowManager();
  public WindowManager getWindowManager() {
        return mWindowManager;
    }

我们都知道WindowManager的实现类是PhoneWindow,查看其getWindowManager源码,我们会发现,实际这个走的是Window中的getWindowManager()方法

//实际最终创建的是WindowManagerImpl这个实例,查看这个源码中的addView方法
 mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
   @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
    }

WindowMangerImp中的addView源码分析

ViewRootImpl root;
 root = new ViewRootImpl(view.getContext(), display);
  try { 
            //设置view进去
                root.setView(view, wparams, panelParentView);
            } catch (RuntimeException e) {
                // BadTokenException or InvalidDisplayException, clean up.
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
                throw e;
            }

调用的ViewRootImpl中的setView方法,调用其中的 requestLayout()-> scheduleTraversals();->mTraversalRunnable->doTraversal->performMeasure->view的measure-.onMeasure方法这时候我们就看到了onMeasure实际是在onResume方法之后调用的

以LinearLayout为例:LinearLayout的onMeasure->measureVertical->measureChildBeforeLayout->measureChildWithMargins->ViewGroup的measureChildWithMargins

 protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

我们自定义view的时候widthMeasureSpec=childWidthMeasureSpec

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 指定宽高
        // widthMeasureSpec = childWidthMeasureSpec
        // heightMeasureSpec = childHeightMeasureSpec

        // wrap_content = AT_MOST
        // match_parent fill_parent 100dp = EXACTLY
        // 模式和大小是由父布局和自己决定的
        // 比方 父布局是包裹内容 就算子布局是match_parent,这个时候计算的测量模式还是 AT_MOST
        // 比方 父布局是match_parent  子布局是match_parent,这个时候计算的测量模式还是 EXACTLY

        // setMeasuredDimension();
    }

getChildMeasureSpec源码分析

 public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
       //父布局是EXACTLY模式
        case MeasureSpec.EXACTLY:
          //子布局是精确的值,则子布局是EXACTLY
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//子布局如果是MATCH_PARENT,子布局是EXACTLY
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {//子布局是WRAP_CONTENT,则子布局是AT_MOST
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        //父布局是AT_MOST
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                //子布局是EXACTLY
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//子布局是MATCH_PARENT,返回的是AT_MOST
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {//子布局是WRAP_CONTENT,返回的是AT_MOST
                   resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;
       //父布局是UNSPECIFIED的模式
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {//子布局还是EXACTLY
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            }
      //其他啊不管是什么布局都是UNSPECIFIED
     else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

子布局设置为精确的值,无论父布局什么布局返回的都是精确的值。其他和父布局设置是一样的

View的绘制流程.png
上一篇下一篇

猜你喜欢

热点阅读