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:
LinearLayout. LayoutParams param = new LinearLayout. LayoutParams( 0, LayoutParams. MATCH_PARENT, 1);
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.
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.
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.
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);
Use new LinearLayout.LayoutParams(int width, int height, float weight)
to set weights when setting layout params to the subviews
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