Meaning: Measuerspce is a combination of a set of measured values (size) and patterns (mode) that the parent passes to child.
Usage scenarios: Often we work with the spec in the onmeasure (int widthmeasurespec,int heightmeasurespec) function of child to determine the length and width of the child.
Here we see that the MEASURESPEC has 3 measurement modes:
MeasureSpec.AT_MOST:child up to the size of the parent, which is usually attributed to "wrap_content".
The size of the MeasureSpec.EXACTLY:child is a definite value, which is usually attributed to "match_parent" or to a definite value.
Measurespec.unspecifed: This is hardly used, unspecified, and child can get whatever size they want.
Measure makemeasurespec,getmode,getsize I don't say much here, very simple is a bitwise operation.
Said for a long while, in the end this widthmeasurespec and heightmeasurespec how to come? This needs to look at the source code.
We know that the measurement and rendering of the view is triggered by its parent, so go directly into the ViewGroup
The entry point is measure:
Here we see a parentwidthmeasurespec and parentheightspec, here we don't care, probably know this is its parent to its spec.
To continue into the function:
As you can see, here in switch mode is similar to the onmeasure we deal with view.
Continue down:
Here, spec has been assembled, the next step should be passed to child calculation.
So far, ViewGroup's measurements have been completed. The next step is to give to child's own calculations, and then back to our original onmeasure function.
Above we also talk about this parentwidthmeasurespec and parentheightspec, in fact, is the current viewgroup of the parent to its measurement mode and value. Follow the steps above, exactly the same.
So after the problem like this, the solution of ideas and methods is very simple.
View view=getlayoutinflater (). Inflate (R.layout.layout_item, NULL);
Toast.maketext (Mainactivity.this, "view_w=" +view.getmeasuredwidth () + "," +view.getlayoutparams (), 0). Show ();
Why is the width of view 0,layoutparams null?
The width of the view is 0, which is obvious: The view is not measure, because we are a view that is parsed from a pull in an XML file, it has no parent and no parent measurement, so it is 0.
The solution is Measure,view.measure (0,0), we preach 0, 0, and ultimately view ourselves. Here's another layoutparams null, why?
We know that Layoutparams is the layout parameter of the parent to child. In the view source, we see
and a Get,set method.
We went back to the ViewGroup.
Here we see AddView will pass a params, how does this params come from?
Here we see that the layoutparams of the child is assigned in the AddView, so the above layoutinflate view is not layoutparams because there is no parent.
Workaround:
You are welcome to correct and criticize!
The origin and use of Android MEASUERSPCE