Android Constraint Layout Programmatically?

A little late to the game, but you need to basically treat your views in a constraint layout as regular views that simply have their own LayoutParams.

In the ConstraintLayout case, the documentation is located here: https://developer.android.com/reference/androidx/constraintlayout/widget/ConstraintLayout.LayoutParams

This class contains the different attributes specifying how a view want to be laid out inside a ConstraintLayout. For building up constraints at run time, using ConstraintSet is recommended.

So, the recommended method is to use a ConstraintSet.

There’s a nice code sample there, but the core concept is you need to create a new set (by copying/cloning/new, etc), set its properties, and then apply it to your layout.

E.g.: Suppose your layout contains a ConstraintLayout (called mConstraintLayout here) and inside it contains a view (R.id.go_button in the sample), you could do:

    ConstraintSet set = new ConstraintSet();

    // You may want (optional) to start with the existing constraint,
    // so uncomment this.
    // set.clone(mConstraintLayout); 

    // Resize to 100dp
    set.constrainHeight(R.id.go_button, (int)(100 * density));
    set.constrainWidth(R.id.go_button, (int)(100 * density));

    // center horizontally in the container
    set.centerHorizontally(R.id.go_button, R.id.rootLayout);

    // pin to the bottom of the container
    set.connect(R.id.go_button, BOTTOM, R.id.rootLayout, BOTTOM, 8);

    // Apply the changes
    set.applyTo(mConstraintLayout); 
    // this is my… (ConstraintLayout) findViewById(R.id.rootLayout);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)