13

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);
Cœur
  • 37,241
  • 25
  • 195
  • 267
ecirish
  • 511
  • 1
  • 5
  • 18
  • Check my answer on http://stackoverflow.com/questions/4641072/how-to-set-layout-weight-attribute-dynamically-from-code#answer-13943330 – Andres Felipe Dec 18 '12 at 23:51

3 Answers3

9

Look into LayoutParams, it has a field for setting the weight

Will Kru
  • 5,164
  • 3
  • 28
  • 41
  • 4
    Yop, I ended up with: ` 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);` – ecirish Sep 04 '11 at 21:08
  • 2
    @ecirish I added your solution to tail of question, for better visibility – Marek Sebera Nov 27 '12 at 23:06
3

Use this to recycle the LayoutParam object:

((LinearLayout.LayoutParams) view.getLayoutParams()).weight = 0.2f;
view.refreshDrawableState(); // This is to explicit force the refresh.
Daniel De León
  • 13,196
  • 5
  • 87
  • 72
3

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);
Ganindu
  • 351
  • 4
  • 4