Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every new view need a new layoutparams?

Tags:

android

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,

like image 436
Andi Jay Avatar asked Mar 23 '11 16:03

Andi Jay


People also ask

What is the use of LayoutParams in Android?

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.

What is Android Layout_width?

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.


2 Answers

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.

like image 75
Matthew Willis Avatar answered Sep 22 '22 15:09

Matthew Willis


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);
like image 24
Gangnus Avatar answered Sep 20 '22 15:09

Gangnus