开发者

Does every new view need a new layoutparams?

So let's say that I want to create multiple TextViews programatically inside a relative layout. It looks l开发者_C百科ike with each new TextView I also have to create a new LayoutParams like so:

RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);

Then I add whatever rules I want using:

p.addrule(...,...);

It seems that I cannot use this single LayoutParams to set the rules for multiple TextViews. Is this a true statement?

Thanks,


Using the same LayoutParams for multiple views is fine, modulo the caveat that changing the LayoutParams before the views have been through layout will apply the changes to all the views.

If you're just looking to save code then you may look into LayoutParams' copy constructor. This allows you to create a new LayoutParams from the data in another LayoutParams without having the two refer to the same LayoutParams instance.


After creating and constructing the correct LayoutParams instance you could use it for every View in that parent:

view1.setLayoutParams(params0);

If you want to have independent copies of params (which you want, I think), you can change it so:

RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams(params0);
view1.setLayoutParams(params);


If you give the same LayoutParams object to multiple TextViews, they will share all of the settings. This means if you change something in it, the change will apply to all TextViews. In general, you will want to use a different instance for each TextView.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜