Differences between: myView.getLayoutParams().heig

2019-07-14 13:41发布

问题:

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.