How to set layout_weight attribute dynamically from code?

Adham picture Adham · Jan 9, 2011 · Viewed 227.4k times · Source

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

Answer

Erich Douglass picture Erich Douglass · Jan 9, 2011

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.