[Solved] Why do we use setLayoutParams?

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?

Solution #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();
}
Respondent: sakiM

Solution #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.

Respondent: Rey Pham

Solution #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.

Respondent: Bruce Yu

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.