小编典典

ConstraintLayout:以编程方式更改约束

all

我需要帮助ConstraintSet。我的目标是在代码中更改视图的约束,但我不知道如何正确地做到这一点。

我有 4TextView和 1 ImageView。我需要为ImageView其中一个设置约束TextView

check_answer4 = (TextView) findViewById(R.id.check_answer4);
check_answer1 = (TextView) findViewById(R.id.check_answer1);
check_answer2 = (TextView) findViewById(R.id.check_answer2);
check_answer3 = (TextView) findViewById(R.id.check_answer3);

correct_answer_icon = (ImageView) findViewById(R.id.correct_answer_icon);

如果第一个答案是正确的,我需要将约束设置ImageView

app:layout_constraintRight_toRightOf="@+id/check_answer1"
app:layout_constraintTop_toTopOf="@+id/check_answer1"

如果第二个答案是正确的,我需要将约束设置ImageView

app:layout_constraintRight_toRightOf="@+id/check_answer2"
app:layout_constraintTop_toTopOf="@+id/check_answer2"

等等。


阅读 97

收藏
2022-07-28

共1个答案

小编典典

  1. 要将图像视图的约束设置为:
     app:layout_constraintRight_toRightOf="@+id/check_answer1"
    

    app:layout_constraintTop_toTopOf=”@+id/check_answer1”

利用:

     ConstraintLayout constraintLayout = findViewById(R.id.parent_layout);
 ConstraintSet constraintSet = new ConstraintSet();
 constraintSet.clone(constraintLayout);
 constraintSet.connect(R.id.imageView,ConstraintSet.RIGHT,R.id.check_answer1,ConstraintSet.RIGHT,0);
 constraintSet.connect(R.id.imageView,ConstraintSet.TOP,R.id.check_answer1,ConstraintSet.TOP,0);
 constraintSet.applyTo(constraintLayout);
  1. 要将图像视图的约束设置为:
     app:layout_constraintRight_toRightOf="@+id/check_answer2"
    

    app:layout_constraintTop_toTopOf=”@+id/check_answer2”

利用:

     ConstraintLayout constraintLayout = findViewById(R.id.parent_layout);
 ConstraintSet constraintSet = new ConstraintSet();
 constraintSet.clone(constraintLayout); 
 constraintSet.connect(R.id.imageView,ConstraintSet.RIGHT,R.id.check_answer2,ConstraintSet.RIGHT,0);      
 constraintSet.connect(R.id.imageView,ConstraintSet.TOP,R.id.check_answer2,ConstraintSet.TOP,0);
 constraintSet.applyTo(constraintLayout);
2022-07-28