Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a view programmatically in ConstraintLayout

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);
like image 419
BenjaminBihr Avatar asked Mar 16 '17 21:03

BenjaminBihr


1 Answers

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);
like image 199
Juan Avatar answered Oct 16 '22 20:10

Juan