Getting Down to the Nitty Gritty of Android Development

As you can see from the following excerpt of ConstraintLayout's supported attributes, there is no layout_constraintStart_toCenterX attribute. Thus you cannot directly align the left edge of one view to the center of another view.

But ConstraintLayout is flexible enough to get your view aligned to the center of another view without such an attribute. Even though the solutions is a tad hacky 🙂

Say you have view A and want another view B to left-align to the center of A. To achieve this you can add yet another view C. Align both edges of C to the respective edges of A. C is thus centered to A. Now you can align the left edge of B to the right edge of C. Finally set the visibility of the helper view C to View.GONE – and you are done.

Here’s the screen showing it before the view is set to View.GONE:

Left align a view to the center of another view – how it looks before the helper view is marked GONE

And this is the desired result after setting the helper view to View.GONE:

The final result of a view appearing to be left aligned to the center of another view

Keep in mind: You cannot use a view and simply set it’s layout_width and layout_height to 0dp – since this is equivalent to stretching within a ConstraintLayout. To make a view have a height and width of zero, you have to set it’s visibility to GONE. That’s the only way to achieve this!

I think I mentioned it already in my previous ConstraintLayout article. But maybe it’s time to repeat myself: I really like what Google’s devs are doing with ConstraintLayout. Keep up the good work 🙂

Wolfram Rittmeyer lives in Germany and has been developing with Java for many years.

In recent years he shifted his attention to Android and blogs about anything interesting that came up while developing for Android.

Your solution is the best if you want some view to be centered to its parent – but not if it should be left- or right-aligned to the center of another view within the container.

For left- or right-aligning a view to the center of the container, guidelines are the best solution. The solution shown in this post is for arbitrary views. If for example the other view you are aligning to is stretched, but isn’t using the full width of the container (because it is itself bound to another view) there isn’t another solution available right now.