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);
BenjaminBihr
  • 1,252
  • 2
  • 10
  • 15

1 Answers1

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);
Juan
  • 5,525
  • 2
  • 15
  • 26
  • clone() - Copy the constraints from a layout, what if the layout is parent and have no constraints? – Pavel Poley Mar 02 '18 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 02 '18 at 12:43