如何以编程方式更改约束布局中的约束边距?

how to change constraint margin in my constraint layout programatically?

我有这样的文本视图

<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent" android:layout_height="wrap_content">

    <TextView
            android:id="@+id/textView_data_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:layout_marginBottom="8dp"
            android:textColor="@color/grey_dark_top"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="data in here" />


</androidx.constraintlayout.widget.ConstraintLayout>

如您所见,我将上下边距设置为 8 dp。但是当满足特定条件时,我需要将顶部和底部约束更改为 32 dp。所以我需要以编程方式更改它。怎么做?

你可以这样做:-

ConstraintLayout.LayoutParams params= (ConstraintLayout.LayoutParams) 
    textView.getLayoutParams();
    int margin=getResources().getDimensionPixelSize(R.dimen.vertical_padding_small);
    params.topMargin=margin;
    params.bottomMargin=margin;