Search code examples
androidmargindeep-copyandroid-layoutparams

How can I know if I need to call setLayoutParams or just change the values of existing LayoutParams?


How can I know if getLayotParams() return a reference to the effective params or it's just a deep copy of the params?

say:

MarginLayoutParams layoutParams = (MarginLayoutParams) getView().getLayoutParams();

layoutParams.leftMargin = horizontalMargin;
layoutParams.rightMargin = horizontalMargin;

is enough, or this line is needed as well?

parent.setLayoutParams(layoutParams);

Solution

  • getLayoutParams returns the actual LayoutParams, not a deep copy. However, updating the parameters won't trigger a layout, you would have to call requestLayout, which is automatically called when you use setLayoutParams.

    So if you want to modify the values and have them applied, you need to either call setLayoutParams or trigger a layout with requestLayout.

    If you use Kotlin, you can use the updateLayoutParams extension function as well.