8

I try to add a View at the same place of an other View in a ConstraintLayout but the added View don't get the LayoutParams of the other View.

The added View take place on the top|left of the container.

This is my code :

TextView cloneView = new TextView(getContext());
cloneView.setLayoutParams(otherView.getLayoutParams());
mainContainer.addView(cloneView);

1 Answer 1

11

To add views to a ConstraintLayout you have to add the constraints using a ConstraintSet.

View v = findViewById(...);
ConstraintLayout cl = (ConstraintLayout) findViewById(...);


ConstraintSet c = new ConstraintSet();
cl.addView(v);
int id = v.getId();

c.clone(cl);
c.connect(id, ConstraintSet.Top, otherViewIdAboveV, ConstraintSet.BOTTOM, 0);
...
other constraints
...
c.applyTo(cl);
2
  • clone() - Copy the constraints from a layout, what if the layout is parent and have no constraints? Mar 2, 2018 at 12:11
  • @PavelPoley I am not sure I understand the comment. The case is that the parent is a ConstraintLayout and by doing this you add Views to it with the corresponding contraints. If it doesn't have constraints at the time of adding a new view, still, new constraints will have to be added for it.
    – Juan
    Mar 2, 2018 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.