7

I'm having a problem with android. I'm setting the Weight parameter in Java, but it's doing exactly the oposite of what I want.

Here's the code

LinearLayout container = new LinearLayout(context);
// some code ...
container.setWeightSum(1f);

View v1 = new View(context);
v1.setBackgroundColor(Color.parseColor("#ff0000"));
LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
p1.weight=0.1f;

View v2 = new View(context);
v2.setBackgroundColor(Color.parseColor("#000000"));
LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
p2.weight=0.9f;

container.addView(v1,p1);
container.addView(v2,p2);

I repeat this process 7 times with adding a black line between the container layout. Normally I should get a small red column on the lef, and a large black one, but here's what I get with this code :

https://i.stack.imgur.com/PPgoy.png

Why does it doing exactly the opposite of the code ?

Luuklag
  • 3,897
  • 11
  • 38
  • 57
Firas
  • 562
  • 6
  • 19

2 Answers2

11

When we use the weight width should be Zero

try with width 0 for with children inside the container.............

 LinearLayout.LayoutParams p1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.WRAP_CONTENT);



LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.WRAP_CONTENT);
Dharmendra
  • 33,296
  • 22
  • 86
  • 129
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
1

You are setting both widths to "wrap_content"... when using weights you should set the affected orientation to "0dp" (or it's programatic equivalent).

Barak
  • 16,318
  • 9
  • 52
  • 84