Why do we use setLayoutParams?

守給你的承諾、 提交于 2021-02-07 12:44:14

问题


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?


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



回答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.




回答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.



来源:https://stackoverflow.com/questions/35500090/why-do-we-use-setlayoutparams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!