How to set layout_weight attribute dynamically from code?


Question

How can I set the value for the attribute layout_weight for button in android dynamically from java code ?

1
219
7/31/2018 10:07:32 AM

Accepted Answer

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.

417
2/27/2017 1:08:28 PM

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!


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon