Sharas
Sharas

Reputation: 2135

center 2 views vertically in ConstraintLayout

I have 2 views which I need to center vertically (both). I need to have fixed top margin between the 2 views (40 dp) How can I do it with ConstraintLayout?

Thanks.

Upvotes: 0

Views: 46

Answers (1)

Philio
Philio

Reputation: 4185

You need to use chains, in this case app:layout_constraintVertical_chainStyle="packed" will achieve what you're looking for.

Try something like this:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/text_view_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView 1"
        app:layout_constraintBottom_toTopOf="@+id/text_view_2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="packed" />

    <TextView
        android:id="@+id/text_view_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:text="TextView 2"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text_view_1" />
</androidx.constraintlayout.widget.ConstraintLayout>

Upvotes: 2

Related Questions