ConstraintLayout:以编程方式更改约束

新手上路,请多包涵

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

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

 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"

等等。

原文由 Big Coach 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 495
2 个回答
  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);

原文由 vishakha yeolekar 发布,翻译遵循 CC BY-SA 4.0 许可协议

您还可以使用 TransitionManager 为更改设置动画:

 public static void animateConstraintLayout(ConstraintLayout constraintLayout, ConstraintSet set, long duration) {
    AutoTransition trans = new AutoTransition();
    trans.setDuration(duration);
    trans.setInterpolator(new AccelerateDecelerateInterpolator());

    TransitionManager.beginDelayedTransition(constraintLayout, trans);
    set.applyTo(constraintLayout);
}

使用 ConstraintSet 更新布局后,您可以这样调用它:

 ConstraintSet set = new ConstraintSet();
set.clone(constraintLayout);
set.connect(R.id.example, ConstraintSet.BOTTOM, R.id.anotherExample, ConstraintSet.BOTTOM);
set.connect(R.id.example, ConstraintSet.TOP, R.id.anotherExample, ConstraintSet.TOP);

animateConstraintLayout(constraintLayout, set, 500);

原文由 Mohamed Salah 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题