Differences between: myView.getLayoutParams().height = screenHeight and myView.setLayoutParams(lp)?

て烟熏妆下的殇ゞ 提交于 2019-12-24 04:29:25

问题


When it comes to change the height of a layout dynamically, I usually set the desired dimensions using LayoutParams like:

RelativeLayout myView = (RelativeLayout) v.findViewById(R.id.myView);     
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        RelativeLayout.LayoutParams.FILL_PARENT,
                        screenHeight);

    myView.setLayoutParams(lp);

But there is this shorter version as well:

myView.getLayoutParams().height = screenHeight;

Both are working in my case, I would prefer the second version of course because is much simpler, but is there any difference between the two I need to be aware of?

Thanks!


回答1:


You can a look at the source code of View.

When calling setLayoutParams the following statements are also executed.

resolveLayoutParams();
if (mParent instanceof ViewGroup) {
    ((ViewGroup) mParent).onSetLayoutParams(this, params);
}
requestLayout();

So basically the requestLayout() is called immediately. Also the parent is informed about the changes.

When using myView.getLayoutParams().height = screenHeight; the View also must be relayouted. This might be done by the View itself at an other point or has to be done manually.

This depends on the time when you call myView.getLayoutParams().height = screenHeight;

If getLayoutParams().height = screenHeight; is called before the View is layouted/measured the first time, this should work.



来源:https://stackoverflow.com/questions/31770206/differences-between-myview-getlayoutparams-height-screenheight-and-myview-s

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