Nik Myers
Nik Myers

Reputation: 1873

Why use "setLayoutParams" after "getLayoutParams"?

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?

Upvotes: 10

Views: 3315

Answers (3)

Bruce Yu
Bruce Yu

Reputation: 3

If you don't use the setLayoutParams(), your layout setting would be effective when the View.onLayout() is 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.

Upvotes: 0

sakiM
sakiM

Reputation: 4932

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();
}

Upvotes: 7

Rey Pham
Rey Pham

Reputation: 605

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.

Upvotes: 0

Related Questions