[android] ConstraintLayout에서의 가로 정렬

ConstraintLayout은 안드로이드 앱에서 뷰를 정렬하는 데 사용되는 강력한 레이아웃입니다. 뷰를 가로로 정렬하기 위해서는 몇 가지 방법이 있습니다.

Guideline을 이용한 가로 정렬

가로 정렬을 하기 위해 Guideline을 사용할 수 있습니다. Guideline은 ConstraintLayout 내에서 레이아웃을 정렬하는 데 도움이 되는 무인의 가상 가이드 라인입니다. Guideline을 사용하여 뷰들을 가로로 정렬할 수 있습니다.

<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">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.5" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Left-aligned"
        app:layout_constraintLeft_toLeftOf="@id/guideline" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Right-aligned"
        app:layout_constraintRight_toRightOf="@id/guideline" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

위의 XML 예제에서, Guideline을 사용하여 textView1을 왼쪽에, textView2를 오른쪽에 정렬하고 있습니다. Guideline의 위치는 app:layout_constraintGuide_percent 속성을 사용하여 조절할 수 있습니다.

가중치(Chains)를 이용한 가로 정렬

가중치를 사용하여 여러 뷰를 가로로 정렬할 수도 있습니다. Chain은 여러 뷰를 하나의 그룹으로 묶어 정렬할 때 사용됩니다.

<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">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 1" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button 2"
        app:layout_constraintStart_toEndOf="@id/button1"/>

</androidx.constraintlayout.widget.ConstraintLayout>

위의 XML 예제에서, button1button2가 가로로 연결되어 있습니다. 이를 통해 두 버튼을 가로로 정렬하고 있습니다.

가로 정렬을 위해서는 Guideline이나 가중치(Chains)를 사용하여 뷰를 정렬할 수 있습니다. 각각의 방법은 다양한 상황에 맞게 활용될 수 있으니 상황에 맞게 적절히 선택하여 사용하시면 됩니다.

참고: Android Developers - ConstraintLayout