For example, if you want to change LayoutParams
of some view to WRAP_CONTENT
for both width
and height
programmatically, it will look something like this:
final ViewGroup.LayoutParams lp = yourView.getLayoutParams();
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
As I understood getLayoutParams
returns a reference for Params, so this code would be enough. But I often see in examples and so on that after this lines, this 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 are there cases when it won't work without it?
It is used because setLayoutParams()
also trigger resolveLayoutParams()
and requestLayout()
, which will notify the view that something has changed and refresh it.
Otherwise we can't ensure that the new layout parameters are actually updated.
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();
}