Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set weight (percentage) programmatically

I've got two buttons that I'd like to dynamically weight give a preference. They start out each with a weight of .5 (which of course adds to the LinearLayout's weight of 1), but if the preference is true, then I'd like to change their weights to .7 and .3 respectively. I can set the weight in XML but I can't seem to find how to change it programmatically.


Solution

LinearLayout.LayoutParams PO = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, .60f);
LinearLayout.LayoutParams MO = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, .20f);
like image 689
ecirish Avatar asked Sep 04 '11 02:09

ecirish


1 Answers

If the constructor with width, height and weight is not working, try using the constructor with width and height. And then manually set the weight.

And if you want the width to be set according to the weight, set width as 0 in the constructor. Same applies for height. Below code works for me.

LinearLayout.LayoutParams childParam1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.3f;
child1.setLayoutParams(childParam1);

LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.7f;
child2.setLayoutParams(childParam2);

parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);
like image 111
Ganindu Avatar answered Sep 21 '22 15:09

Ganindu