androidandroid-layoutandroid-layout-weight

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 ?


Solution

  • 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.