10. Dynamic constraints

The library still has room for exploration, but up to this point, we have been dealing only with static XML code. It’s about time we tackle its dynamic aspect which is the Java/Kotlin approach.

We can update a view and its constraints like the old way using ConstraintLayout.LayoutParams . In any case, we all know that this approach is quite inconvenient.

Well, ConstraintLayout as a modern library comes with its own perception of the UI. Mainly, it perceives views and their relationships(constraints) as two different things. Put differently, constraints themselves are represented as a single concept. This is impressive as now we can manage the layout via a single object without the overhead of re-inflating everything.

So, the library comes with its own layout maestro. ConstraintSet! Primarily, it’s an extra class that allows handling widgets/constraints in a dynamic way.

The ConstraintSet class helps define and manipulate programmatically a set of constraints to be used within the layout. Its usage is very straightforward, and it’s just four easy steps:

1. Instantiation like any Java class

ConstraintSet c = new ConstraintSet();

2. Optional — When dealing with an existing ConstraintLayout, we have to take a snapshot of the layout using the clone method, meaning, we have to make our ConstraintSet object save the current state of every widget’s constraints and attributes within the layout

From an XML layout file

clone(Context context, int layoutId)

From a ConstraintLayout instance

clone(ConstraintLayout constraintLayout)

From a Constraints instance

clone(Constraints constraints)

From another ConstraintSet instance

clone(ConstraintSet constraintSet)

3. In this step, we just have to manipulate widgets and their constraints.

For instance, we can apply relative positioning constraints using the connect() method.

c.connect(R.id.source_view_ID, ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP);

The best part is that we do not need a View instance to manipulate constraints. We simply use IDs. Hooray for clean code!

4. Finally, we have to apply the new constraints/state on the layout:

c.applyTo(constraintLayout);

That’s it! To sum it up:

Instantiation. Optional — Cloning state. Updating constraints. Applying constraints to the layout.