ConstraintLayout:以编程方式更改约束 [英] ConstraintLayout: change constraints programmatically

查看:178
本文介绍了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);
    

  • 这篇关于ConstraintLayout:以编程方式更改约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆