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?
LayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports. The base LayoutParams class just describes how big the view wants to be for both width and height.
LayoutParams layoutParams = new LinearLayout. LayoutParams(30, 30); yourImageView. setLayoutParams(layoutParams); This is because it's the parent of the View that needs to know what size to allocate to the View.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With