So let's say that I want to create multiple TextViews programatically inside a relative layout. It looks like 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,
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.
Android layout Width & Height In this code you can see layout_width property. This property is used to set the width of the given control. This property has following options:- Wrap_content :- when you set width as wrap_content then it will take the space according to the content.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With