How to set layout_weight attribute dynamically from code?
How can I set the value for the attribute layout_weight
for button in android dynamically from java code ?
You can pass it in as part of the LinearLayout.LayoutParams
constructor:
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f
);
YOUR_VIEW.setLayoutParams(param);
The last parameter is the weight.
Use LinearLayout.LayoutParams
:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);
EDIT: Ah, Erich's answer is easier!
If you already define your view in your layout(xml) file, only want to change the weight programmatically, this way is better
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);
new a LayoutParams overwrites other params defined in you xml file like margins, or you need to specify all of them in LayoutParams.
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);
childParam2.weight = 0.7f;
child2.setLayoutParams(childParam2);
parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);
If I someone looking for answer, use this:
LinearLayout.LayoutParams lay = (LinearLayout.LayoutParams) myLayout.getLayoutParams();
lay.weight = 0.5;
If you are initializing your layout from xml file, this will be much more convenient than providing new layout parameters for Linear Layout.