Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we use setLayoutParams?

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?

like image 273
Nik Myers Avatar asked Feb 19 '16 07:02

Nik Myers


People also ask

What is layout params?

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.

How do I set LayoutParams to Imageview in android programmatically?

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.


1 Answers

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();
}
like image 112
sakiM Avatar answered Sep 22 '22 17:09

sakiM