Removing/Adding constraint programmatically in ConstraintLayout

后端 未结 3 889
囚心锁ツ
囚心锁ツ 2020-12-14 05:47

I want to remove and add constraint programmatically based on some condition. Here are the screenshots:

and I want to remove it like this but in code:

相关标签:
3条回答
  • 2020-12-14 06:05

    another way this can be done without ConstraintSet.clear is like this with ConstraintLayout.LayoutParams.UNSET

    Assuming we want to remove the bottom constraint of our constraintLayout itself but can be any view:

    val containerParams = cl_container.layoutParams as ConstraintLayout.LayoutParams
    containerParams.bottomToBottom = ConstraintLayout.LayoutParams.UNSET
    cl_container.layoutParams = containerParams
    
    0 讨论(0)
  • 2020-12-14 06:12

    I have not worked through your code, but the following illustrates how to break and make the constraint using ConstraintSet.

        ConstraintSet set = new ConstraintSet();
        ConstraintLayout layout;
    
        layout = (ConstraintLayout) findViewById(R.id.layout);
        set.clone(layout);
        // The following breaks the connection.
        set.clear(R.id.bottomText, ConstraintSet.TOP);
        // Comment out line above and uncomment line below to make the connection.
        // set.connect(R.id.bottomText, ConstraintSet.TOP, R.id.imageView, ConstraintSet.BOTTOM, 0);
        set.applyTo(layout);
    
    0 讨论(0)
  • 2020-12-14 06:23

    Here is the Java version of the answer from j2emanue using ConstraintLayout.LayoutParams, which works without specifying the id of the element that the layout is contrained to:

    final ConstraintLayout constraintLayout = findViewById(R.id.constraintLayout);
    final ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) constraintLayout.getLayoutParams();
    layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.UNSET;
    constraintLayout.setLayoutParams(layoutParams);
    
    0 讨论(0)
提交回复
热议问题