본문 바로가기

Android

[Android] 안드로이드 Layout

안드로이드 개발에서 사용되는 레이아웃의 종류에 대해 알아보겠습니다. 
 
안드로이드가 가지고 있는 기본 레이아웃의 종류가 다양한데요. 필요한 상황에 따라 사용하기 편한 레이아웃을 선택하셔서 사용하면 될 것 같습니다. 
 
Android Layout 의 종류에는

  • LinearLayout
  • ConstarintLayout
  • RelativeLayout
  • TableLayout
  • GridLayout     
  • FrameLayout

등이 있습니다.
 

LinearLayout

LinearLayout은 세로 또는 가로의 단일 방향으로 모든 하위 요소를 정렬하는 레이아웃입니다.
Linearlayout은 다양한 요소들을 단순한 구조로 배치할 때 유용합니다. 그러나 복잡한 레이아웃을 구성하거나 복잡한 UI 디자인을 구현해야 할 때는 다른 레이아웃 유형인 Relative Layout이나 Constraint Layout을 고려할 수 있습니다.
 
사용할 수 있는 속성은 다음과 같습니다.

더보기

1. 방향 (android:orientation)

수평 방향("horizontal")이나 수직 방향("vertical")으로 요소들을 정렬할 수 있습니다.

이 속성을 통해 요소들의 배치 방향을 결정할 수 있습니다.

 

2. Weight 설정 (android:layout_weight)

요소들에 가중치를 부여하여 화면 공간을 분배할 수 있습니다. android:layout_weight 속성을 사용하여 각 요소의 가중치를 설정하면, 화면의 사용 가능한 공간을 가중치에 따라 분배합니다.

 

3.크기 조정 (android:layout_width, android:layout_height)

각 요소의 폭과 높이를 설정할 수 있습니다. "wrap_content"로 설정하면 요소의 내용에 맞게 크기가 조정되며, "match_parent"로 설정하면 부모 컨테이너의 크기에 맞춰 확장됩니다.

 

4.정렬 (android:gravity, android:layout_gravity)

리니어 레이아웃 내부에서 요소들을 정렬하기 위해 android:gravity 속성을 사용할 수 있습니다. 부모 컨테이너 내에서 요소의 위치를 설정하기 위해 android:layout_gravity 속성을 활용할 수도 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/to" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/subject" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="top"
        android:hint="@string/message" />
    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="@string/send" />
</LinearLayout>

 

ConstarintLayout

안드로이드 앱 개발에서 사용되는 강력한 레이아웃 유형 중 하나입니다.
다양한 디바이스 크기와 화면 해상도에 대응하기 위해 유연하게 UI를 디자인할 수 있는 도구로, 복잡한 레이아웃을 구현하는 데 유용합니다. 복잡한 레이아웃을 단순한 계층 구조를 이용하여 표현함으로서 레이아웃을 구성하는 방식에서 자유로워질 수 있습니다.
형제 View들과 관계를 정의해서 레이아웃을 구성한다는 점이 RelativeLayout과 비슷하지만, 보다 유연하고 다양한 기능을  제공합니다. 
 
특징은 다음과 같습니다.

더보기

1. 상대적인 위치 설정

다른 뷰나 부모 레이아웃에 상대적인 위치를 설정할 수 있습니다. 이를 통해 뷰 간의 연관성을 나타내며, 여러 제약 조건을 사용하여 위치를 결정할 수 있습니다.

 

2. 제약 조건 설정

뷰의 위치와 크기를 지정하는 데 사용되는 제약 조건(Constraints)을 설정할 수 있습니다. 제약 조건은 뷰의 상하좌우와 부모 레이아웃에 대한 상대적인 위치, 뷰의 크기 등을 지정하는 역할을 합니다.

 

3. 가로 및 세로 체인

여러 뷰를 연결하여 가로나 세로로 체인을 형성할 수 있습니다. 이를 통해 여러 뷰들이 연속적으로 정렬되거나 그룹화될 수 있습니다.

 

4. 가이드라인

수직 또는 수평 방향으로 가이드라인을 생성하여 뷰의 위치를 정렬하는 데 사용할 수 있습니다. 가이드라인은 가로와 세로로 뷰를 정렬하거나 레이아웃의 일관된 공간을 유지하는 데 도움이 됩니다.

 

5. 비율과 가중치

뷰의 크기를 설정할 때 비율과 가중치를 활용할 수 있습니다. 이를 통해 화면 공간을 유연하게 분배하거나 뷰의 크기를 설정할 수 있습니다.

<?xml version="1.0" encoding="utf-8"?>
<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"
    android:padding="16dp"
    android:background="#ECECEC">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="안녕하세요,"
        android:textSize="18sp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"/>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="컨스트레인트 레이아웃 예시입니다."
        android:textSize="18sp"
        app:layout_constraintTop_toBottomOf="@+id/textView1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="8dp"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="클릭하세요"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"
        app:layout_constraintHorizontal_bias="0.5"
        android:backgroundTint="#FF5722"
        android:textColor="#FFFFFF"/>

    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/ic_android_logo"
        android:contentDescription="안드로이드 로고"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_marginTop="16dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

 

RleativaLayout

RelativeLayout은 부모(Parent) View 또는 자식(Child) View의 상대적 위치 관계를 정의하여 UI를 배치하는 Layout입니다.

LinearLayout은 가로 또는 세로 방향으로 View가 순서대로 배치되었지만 RelativeLayout은 객체간의 상대적인 위치 관계를 정의하지 않으면 배치가 되지 않습니다. 이때 기준이 되는 뷰를 지정하기 위해서는 기준뷰에 id값이 설정되어 있어야 합니다.
상대적인 위치를 정의하지 않으면 기본적으로 가로축은 부모의 왼쪽, 세로축은 부모의 위쪽으로 정의가 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp" >
    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/reminder" />
    <Spinner
        android:id="@+id/dates"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@+id/times" />
    <Spinner
        android:id="@id/times"
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:layout_alignParentRight="true" />
    <Button
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_below="@id/times"
        android:layout_alignParentRight="true"
        android:text="@string/done" />
</RelativeLayout>

 

TableLayout

TableLayout은 행과 열로 하위 view 요소를 표시하는 viewgroup입니다.
자신의 하위 요소를 행과 열에 배치합니다. tablelayout 컨테이너는 행, 열 또는 셀의 테두리 선을 표시하지 않습니다. 

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1">
    <TableRow>
        <TextView
            android:text="@string/table_layout_4_open"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_4_open_shortcut"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>

    <TableRow>
        <TextView
            android:text="@string/table_layout_4_save"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_4_save_shortcut"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>
</TableLayout>

 

GridLayout

gridlayout은 2차원 격자무늬 형태의 레이아웃으로 행과 열의 집합형태로 구성된 레이아웃입니다.
TableLayout의 단점을 보완한 레이아웃으로
LinearLayout 또는 다음으로 소개할 FrameLayout 과 같은 다른 레이아웃의 장점을 포함하는 레이아웃입니다.
GridLayout을 사용할 시 다른 레이아웃과 중첩으로 사용할 필요가 없어 메모리 사용량을 줄일 수 있다는 장점을 가집니다.

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="1">

    <!-- 첫 번째 행 -->
    <TableRow>
        <TextView
            android:text="@string/table_layout_4_open"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_4_open_shortcut"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>

    <!-- 두 번째 행 -->
    <TableRow>
        <TextView
            android:text="@string/table_layout_4_save"
            android:padding="3dip" />
        <TextView
            android:text="@string/table_layout_4_save_shortcut"
            android:gravity="right"
            android:padding="3dip" />
    </TableRow>

    <!-- 추가 행을 원하는 만큼 여기에 추가할 수 있습니다. -->

</TableLayout>

 

FrameLayout

마지막으로 FrameLayout 입니다.
FrameLayout은 자식으로 추가된 여러 뷰 위젯들 중 하나를 layout의 전면에 표시할 때 사용하는 클래스입니다.
frame이 액자라는 점을 생각하면 액자에 딱 맞는 사진을 끼울 수도 있지만 작은 사진을 앞쪽에 끼워 겹쳐 보이게 할 수 있다는 것을 생각하면 조금 더 이해가 쉬울 것 같습니다.
framelayout이 화면에 보여지게 될 때 제일 앞쪽에 표시되는 뷰는 xml 코드에서 가장 마지막에 추가된 뷰입니다.
예시 코드를 보면 다음과 같습니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/button31"
            android:layout_width="match_parent"
            android:layout_height="162dp"
            android:text="VIEW3" />

        <Button 
            android:id="@+id/button32"
            android:layout_width="149dp"
            android:layout_height="100dp"
            android:background="@color/black"
            android:text="VIEW2" />

        <Button
            android:id="@+id/button33"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/white"
            android:text="VIEW1" />
    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 
지금까지 layout의 종류와 간단한 코드에 대해 알아보았습니다.