ConstraintLayout:以编程方式更改约束

ConstraintLayout:以编程方式更改约束

问题描述:

我需要有关ConstraintSet的帮助.我的目标是更改代码中视图的约束,但我不知道如何正确执行此操作.

I need help with ConstraintSet. My goal is to change view's constraints in code, but I cant figure out how to do this right.

我有4个TextView和一个ImageView.我需要将ImageView约束设置为TextView之一.

I have 4 TextViews and one ImageView. I need to set ImageView constraints to one of the TextViews.

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的约束设置为

If 1st answer is right, I need to set constraints of ImageView to

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

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

If 2nd answer is right, I need to set constraints of ImageView to

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

以此类推.

  1. 要将图像视图的约束设置为:

  1. To set constraints of image view to:

 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);

  • 要将图像视图的约束设置为:

  • To set constraints of image view to:

     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);