Search code examples
androidandroid-layoutandroid-constraintlayout

Constraining top and bottom of a view to the same guideline to centralize it, is it supposed to work?


I'm using a guideline to split the screen between two views in a certain point. I also need to put a CardView centralized to this same point. I constrained the CardView Top and Bottom line to the same point, the guideline, because it makes sense.

example

It seems to work, but I couldn't find any reference to this approach and also I found some examples using a different one: making a slightly bigger view to wrap the main view, and then aligning the bottom of the CardView to the bottom of this bigger view. Something like this:

<View
     height="X+Y">

    <View
        id="@+id/view"
        height="X">
    </View>

    <CardView
        height="2Y"
        bottom_toBottomOf="view"/>

</View>

So my question is: is it really supposed to work, or it just happens to work in my emulator?


Solution

  • Constraining top and bottom of a view to the same guideline to centralize it, is it supposed to work?

    Yes, In order to vertically center a view to the edge of another (or to a guideline), you need to:

    • Constraint the top of the view to the edge/guideline.
    • Constraint the bottom of the view to the edge/guideline.

    The same applies in centering a view horizontally to a vertical edge/guideline.

    It seems to work, but I couldn't find any reference to this approach

    Here is a source of that, in the Centring to the edge of a sibling in the editor Paragraph.

    also I found some examples using a different one: making a slightly bigger view to wrap the main view, and then aligning the bottom of the CardView to the bottom of this bigger view.

    This will work, but you have to define a predefined heights in layout, like you used X & Y.