Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Linear Layout Weight Programmatically

I want to add three linear layouts to an activity programatically each of same width. the problem is i am not able to set the weights of these layouts programmatically. I could do this within xml, but I want to do this in program. here is what I want: enter image description here

like image 559
Shahbaz Pothiawala Avatar asked Oct 03 '13 11:10

Shahbaz Pothiawala


People also ask

How do you set linear layout weight programmatically?

LinearLayout. LayoutParams param = new LinearLayout. LayoutParams( 0, LayoutParams. MATCH_PARENT, 1);

How is weight used in linear layout?

Weight can only be used in LinearLayout . If the orientation of linearlayout is Vertical, then use android:layout_height="0dp" and if the orientation is horizontal, then use android:layout_width = "0dp" . It'll work perfectly.

How does layout weight work android?

Layout WeightThis attribute assigns an "importance" value to a view in terms of how much space it should occupy on the screen. A larger weight value allows it to expand to fill any remaining space in the parent view.

What is weight sum in linear layout?

Answer: Per documentation, android:weightSum defines the maximum weight sum, and is calculated as the sum of the layout_weight of all the children if not specified explicitly.


2 Answers

Here its the solution

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);     lp.weight = 1; 

See Full Solution

LinearLayout ll1, ll2, ll3;     /* Find these LinearLayout by ID       i.e ll1=(LinearLayout)findViewById(R.id.ll1);      */      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);     lp.weight = 1;     ll1.setLayoutParams(lp);     ll2.setLayoutParams(lp);     ll3.setLayoutParams(lp); 
like image 172
Tofeeq Ahmad Avatar answered Sep 16 '22 15:09

Tofeeq Ahmad


Use new LinearLayout.LayoutParams(int width, int height, float weight) to set weights when setting layout params to the subviews

like image 42
Ivo Beckers Avatar answered Sep 17 '22 15:09

Ivo Beckers