以编程方式约束布局更改约束

Constraint layout change constraint programmatically

我有一个文本视图:

<TextView
    android:id="@+id/textViewChat"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginLeft="8dp"

    android:layout_marginRight="16dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="26dp"
    android:background="@drawable/rounded_corner"
    android:fontFamily="serif"
    android:text="I have one listView "
    android:textAlignment="textStart"
    android:textColor="@color/bb_darkBackgroundColor"
    android:textSize="15sp"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintLeft_toRightOf="@+id/imageViewChat"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintWidth_default="wrap"/>

我想要的是以编程方式删除最后一行,因为有时我不需要它。

我的理解是您想将 app:layout_constraintWidth_default="wrap" 更改为默认的 app:layout_constraintWidth_default="spread"

以下代码显示了如何使用 ConstraintSet 来执行此操作。 XML 正是您提供的内容,但 ConstraintLayout 的 ID 为 constraintLayout

此代码获取布局中存在的所有约束,进行所需的更改并重新应用更改。

protected void onCreate(Bundle savedInstanceState) {
    final ConstraintSet cs = new ConstraintSet();
    ConstraintLayout layout;

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    layout = (ConstraintLayout) findViewById(R.id.constraintLayout);
    cs.clone(this, R.layout.activity_main);
    cs.constrainDefaultWidth(R.id.textViewChat, ConstraintSet.MATCH_CONSTRAINT_SPREAD);
    cs.applyTo(layout);
}