Before reading this blog, let us assume that you have studied view programming (5): examples provided by the study of custom view_01_apidemo source code.
At that time, it was strange why such a log (the test result on the mobile phone is not on the simulator .)
D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!D/mark ( 2924): onMeasure() is invoked!
I had to look at the source code again and find the answer.
In blog view programming (3): invalidate () source code analysis and analysis of invalidate () source code, which also analyzes the relationship between draw () and ondraw () methods.
In fact, the onmeasure () callback method is similar to ondraw (), and also uses the measure () callback.
Let's take a look at the source code of the measure () and onmeasure () methods.
public final void measure(int widthMeasureSpec, int heightMeasureSpec) { if ((mPrivateFlags & FORCE_LAYOUT) == FORCE_LAYOUT || widthMeasureSpec != mOldWidthMeasureSpec || heightMeasureSpec != mOldHeightMeasureSpec) { // first clears the measured dimension flag mPrivateFlags &= ~MEASURED_DIMENSION_SET; if (ViewDebug.TRACE_HIERARCHY) { ViewDebug.trace(this, ViewDebug.HierarchyTraceType.ON_MEASURE); } // measure ourselves, this should set the measured dimension flag back onMeasure(widthMeasureSpec, heightMeasureSpec); // flag not set, setMeasuredDimension() was not invoked, we raise // an exception to warn the developer if ((mPrivateFlags & MEASURED_DIMENSION_SET) != MEASURED_DIMENSION_SET) { throw new IllegalStateException("onMeasure() did not set the" + " measured dimension by calling" + " setMeasuredDimension()"); } mPrivateFlags |= LAYOUT_REQUIRED; } mOldWidthMeasureSpec = widthMeasureSpec; mOldHeightMeasureSpec = heightMeasureSpec;}
We can see two problems:
1. This method is a final method and cannot be overwritten by the quilt class. Only the quilt class can inherit.
2. The onmeasure () method is called:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));}
This method is a protected method, which is a callback method and must be overwritten by subclass.
So when will the measure () method be called? Through the above analysis, we can know that it is definitely called by the view itself. For more information about how to call it, see the invalidate () source code. I will not go into details here.
The following figure shows the call Link sketch. If you are interested, search your own link!