问题
For example, if you want ot change LayoutParams
of some view to WRAP_CONTENT
for both width
and height
programmaticaly, it will look somethong like this :
final ViewGroup.LayoutParams lp = yourView.getLayoutParams();
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
As i undestood getLayoutParams
returns reference for params, so this code would be enough, but i often see in examples and so on that after this lines, one follows:
yourView.setLayoutParams(lp);
And i wonder what is the point of this line. Is this just for the sake of better code readability or there are cases when it wont work without it?
回答1:
setLayoutParams()
also trigger resolveLayoutParams()
and requestLayout()
, which will notify the view something has changed, refresh it. Or we can't ensure the new layout parameters work actually.
see View.setLayoutParams
sources code:
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params == null) {
throw new NullPointerException("Layout parameters cannot be null");
}
mLayoutParams = params;
resolveLayoutParams();
if (mParent instanceof ViewGroup) {
((ViewGroup) mParent).onSetLayoutParams(this, params);
}
requestLayout();
}
回答2:
There is no way to ensure that any change you made to LayoutParams that returned by getLayoutParams()
will be reflected correctly. It can be varied by Android version. So you have to call setLayoutParams()
to make sure the view will update those changes.
回答3:
If you don't use the setLayoutParams(), your layout setting would be effective while the View.onLayout() be called.
Here is the source code of View.setLayoutParams()
public void setLayoutParams(ViewGroup.LayoutParams params) {
if (params == null) {
throw new NullPointerException("Layout parameters cannot be null");
}
mLayoutParams = params;
resolveLayoutParams();
if (mParent instanceof ViewGroup) {
((ViewGroup) mParent).onSetLayoutParams(this, params);
}
requestLayout();
}
As you see, the requestLayout would be called in the setLayoutParams. This view would be relayout again immediately. The onLayout would be also called.
来源:https://stackoverflow.com/questions/35500090/why-do-we-use-setlayoutparams