How to align TextView with ConstraintLayout parent to the left

Sergi Llamas Guerrero
Tiendeo Tech
Published in
3 min readApr 27, 2020

Android’s ConstraintLayout is a layout that allows us to order the views in a xml without having to nest them.

In the case of the TextView, I found an issue when we want to align it to the left or to the right and we don’t know the length of the text.

What happens if, for example, we have this kind of TextView with a ConstraintLayout as parent?

Let’s suppose that we want to add a TextView in a ConstraintLayout aligned to the left. It would be as easy as add app:layout_constraintStart_toStartOf=”parent” to the TextView.

This is an example:

And the visual result would be the following:

But, sometimes we don’t know how long would be the text. Let’s suppose that the text is set programatically after a web service response is received. And we receive This is a very very long text just to see what happens in these cases. Then, the visual result would be the following:

Ok, this is because the TextView is not constrained to the right. So let’s add app:layout_constraintEnd_toEndOf=”parent”. But the result is not yet what we expected:

The margins disappeared. So if we want to keep them we should add app:layout_constrainedWidth=”true”. And the result would be the following:

WOW! Great! Everything looks fantastic and wonderful! But wait… What if the text is not so long, like the one we had at the beginning? It would look like this:

This is because we have both app:layout_constraintStart_toStartOf=”parent” and app:layout_constraintEnd_toEndOf=”parent” but the text doesn’t fill the screen, so text is centered.

But we can pin it to the left, keeping all the changes we have done, adding app:layout_constraintHorizontal_bias=”0.0”:

And this will work for any text length!

The TextView with all changes looks like this:

That’s all! I hope this helps someone.

Thank you for reading!

--

--