androidandroid-layoutandroid-linearlayoutandroid-relativelayoutandroid-layout-editor

Align vertical center of two view in Android


How can I align vertical center of two views align in LinearLayout or RelativeLayout (iOS equivallent of view1.centerY = view2.centerY)?

I am trying to achieve below layout. How can I make the all the three views in first line aligned vertically in xml? The middle view in first line is fixed. I want the left and right view's vertical center line equal to middle views vertical center line.

enter image description here


Solution

  • Constraint layout:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ConstraintLayout">
    
        <View
            android:id="@+id/left"
            android:layout_width="70dp"
            android:layout_height="30dp"
            android:layout_marginBottom="8dp"
            android:layout_marginStart="8dp"
            android:background="#FF2600"
            app:layout_constraintBottom_toBottomOf="@+id/center"
            app:layout_constraintEnd_toStartOf="@+id/center"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/center" />
    
        <View
            android:id="@+id/center"
            android:layout_width="100dp"
            android:layout_height="60dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:background="#0633FF"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <View
            android:id="@+id/right"
            android:layout_width="70dp"
            android:layout_height="30dp"
            android:layout_marginEnd="8dp"
            android:background="#FF40FF"
            app:layout_constraintBottom_toBottomOf="@+id/center"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/center"
            app:layout_constraintTop_toTopOf="@+id/center" />
    </android.support.constraint.ConstraintLayout>
    

    Design