How to programmatically add views and constraints to a ConstraintLayout?

LeoColman picture LeoColman · Oct 27, 2016 · Viewed 38.7k times · Source

I'm having a problem to programmatically add views to a ConstraintLayout, and set up all the constraints required for the layout to work.

What I have at the moment doesn't work:

ConstraintLayout layout = (ConstraintLayout) findViewById(R.id.mainConstraint);
ConstraintSet set = new ConstraintSet();
set.clone(layout);

ImageView view = new ImageView(this);
layout.addView(view,0);
set.connect(view.getId(), ConstraintSet.TOP, layout.getId(), ConstraintSet.TOP, 60);
set.applyTo(layout);

The ImageView doesn't even appear on the layout. When adding to a RelativeLayout, it works like a charm.

What can I do to create the constraints I need, so that my layout work again?

Answer

rerashhh picture rerashhh · Nov 10, 2016

I think you should clone the layout after adding your ImageView.

    ConstraintLayout parentLayout = (ConstraintLayout)findViewById(R.id.mainConstraint);
    ConstraintSet set = new ConstraintSet();

    ImageView childView = new ImageView(this);
    // set view id, else getId() returns -1
    childView.setId(View.generateViewId());
    layout.addView(childView, 0);

    set.clone(parentLayout);
    // connect start and end point of views, in this case top of child to top of parent.
    set.connect(childView.getId(), ConstraintSet.TOP, parentLayout.getId(), ConstraintSet.TOP, 60);
    // ... similarly add other constraints
    set.applyTo(parentLayout);