Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How do I specify weight programmatically for a RelativeLayout?

I want to do something like this programmatically -

<LinearLayout>
  <RelativeLayout1 weight = 1>
  <RelativeLayout2 weight = 3>
  <RelativeLayout3 weight = 1>
<LinearLayout>

It does not let me do a setWeight programmatically. However, I do see that RelativeLayout has an android:layout_weight parameter in XML. Am I missing something?

like image 775
Suchi Avatar asked May 20 '11 14:05

Suchi


People also ask

Can we use weight in RelativeLayout?

Last year, android has introduced a new layout called PercentRelativeLayout which gives us the functionality of both relativelayout and weight property together .

How do you add weight in relative layout?

RelativeLayouts do not support weight. You need to use a LinearLayout as a parent container if you want to use weights.

How do you use layout weight?

Layout WeightA larger weight value allows it to expand to fill any remaining space in the parent view. Child views can specify a weight value, and then any remaining space in the view group is assigned to children in the proportion of their declared weight. Default weight is zero.

Which is better LinearLayout or RelativeLayout?

Relativelayout is more effective than Linearlayout. From here: It is a common misconception that using the basic layout structures leads to the most efficient layouts. However, each widget and layout you add to your application requires initialization, layout, and drawing.


1 Answers

When you add the RelativeLayout to the LinearLayout using addView you have to provide a LinearLayout.LayoutParams, something like this :

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, height, weight);
linearLayout.addView(relativeLayout, params);

Reference here

like image 93
martiall Avatar answered Oct 08 '22 17:10

martiall