ConstraintLayout - how to align centers of two views vertically
Android Studio 3.5
If it's TL;TR...
Select your desired views, right button :
And you'll get:
Without Guideline, put attributes on every views that you need to align vertically.
app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"
With Guideline
Add horizontal Guideline and make it vertically center with layout_constraintGuide_percent
.
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline"
android:layout_width="1dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5"/>
For every views, anchor them to guideline with attributes
app:layout_constraintTop_toTopOf="@id/guideline"
app:layout_constraintBottom_toBottomOf="@id/guideline"
With guideline, you have more flexibility, as you can change all views position easily by moving the guideline.
Update:
To align a view vertically center against another view then you just need to refer the view id in attribute. To align txt_change_picture
vertically center against img_change_picture
, you can change layout like this:
<TextView
android:id="@+id/txt_change_picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toEndOf="@id/guideline_text"
android:text="@string/settings_main_change_picture"
app:layout_constraintTop_toTopOf="@id/img_change_picture"
app:layout_constraintBottom_toBottomOf="@id/img_change_picture"
/>