Modifying topMargin of a Relativelayout programmatically

92 Views Asked by At

I need to modify the top margin of a RelativeLayout programmatically

myScrollView.marginTop = 250

Unfortunately I receive the error val cannot be reassigned

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    ...
    <RelativeLayout
        android:id="@+id/myScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="100dp"
        android:layout_marginRight="100dp"
        android:layout_marginTop="125dp"
        tools:context=".QuizActivity">
        ...

Is there a different way to do it please?

Thanks in advance for the appreciated help.

1

There are 1 best solutions below

6
On

You have to get the layoutparams of the view first and then setMargins.

val param = myScrollView.layoutParams as ViewGroup.MarginLayoutParams
param.setMargins(left,top,right,bottom)

then set the params to the layout or the view.

myScrollView.layoutparams = param