본문 바로가기
깡샘 코틀린

07-1 선형으로 배치 - LinearLayout

by 농농씨 2023. 6. 19.

// 실습하다가 책이 최신버전 안드로이드스튜디오랑 살~짝 달라서 이론만 공부하고 실습은 나중에 몰아서 해보도록 할게요

 

7장에서는 뷰를 화면에 적절하게 배치하는 방법을 다룬다. 이때 뷰를 배치하는 클래스를 레이아웃 클래스라 한다.

 

06장에서 다루었듯, 레이아웃 클래스는 화면을 독자적으로 출력하지 않고 다른 뷰 객체를 포함하는 일종의 그릇 역할을 한다.

안드로이드가 제공하는 레이아웃 클래스는 저마다 뷰를 배치하는 규칙이 있다. 지금부터 대표적인 레이아웃 클래스 5가지를 살펴보자.

 

LinearLayout 배치 규칙

LinearLayout은 뷰를 가로나 세로 방향으로 나열하는 레이아웃 클래스이다.

orientation이라는 속성에 horizontal이나 vertical값으로 방향을 지정한다.

// LinearLayout의 방향 속성 설정
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"> // vertical 주목
    <Button
    	android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button1" />
    <Button
    	android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android/text="Button2" />
</LinearLayout>

버튼의 속성을 vertical로 지정했으면 버튼 두개를 세로로, horizontal로 지정했으면 가로로 나열한다.

LinearLayout은 방향만 설정하면 뷰를 추가한 순서대로 나열한다. 화면에서 벗어나도 줄을 자동으로 바꾸지 않는다. 매우 단순하다.

그럼, 가로세로가 중첩된 구조는 LinearLayout으로 만들 수 없는가? 아니다.

이럴때는 LinearLayout을 중첩하면 가능하다. 레이아웃 클래스도 뷰이므로 다른 레이아웃 클래스에 포함할 수 있다. 따라서 LinearLayout으로 복잡한 화면을 만들 수 있다.

 

여백을 채우는 layout_weight 속성

화면에 뷰를 배치하다 보면 가로나 세로 방향으로 여백이 생길 수 있다. 그 여백을 뷰로 채울 수 있다.

 

뷰 1개로 여백 채우기

여백을 뷰로 채우려면 layout_weight 속성을 이용한다. 그러면 수치를 따로 계산하지 않아도 각 뷰에 설정한 가중치로 여백을 채울 수 있어 편리하다.

버튼 두개를 출력하고 여백을 뷰로 채워보겠다. 

// 버튼 두개고 여백 없이 채우기
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"> 
    <Button
    	android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button1" 
        android:layout_weight="1" /> // 이 줄 주목!
    <Button
    	android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android/text="Button2" />
</LinearLayout>

이렇게 하면 버튼1이 늘어나서 여백을 다 채운다.

 

뷰 여러 개로 여백을 나누어 채우기

// 뷰 여러개에 layout_weight 속성 추가
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"> 
    <Button
    	android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button1" 
        android:layout_weight="1" /> // 이 줄 주목!
    <Button
    	android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android/text="Button2" 
        android:layout_weight="3" /> // 여기는 숫자가 3임을 주목!
</LinearLayout>

출력해보면 버튼2가 더 길게 나온다. 

layout_weight 속성에 지정한 숫자는 가중치를 나타낸다. 뷰가 차지하는 여백의 비율을 나타낸다. 따라서 버튼 1과 2는 1대 3으로 여백을 나눠가진다.

 

중첩된 레이아웃에서 여백 채우기

그러면 중첩된 레이아웃에서는 layout_weight 값이 어떻게 동작할까?

1
2 3                                                                                                    


4


5

요런느낌...

1, [2,3], 4, 5 는 orientation의 속성값이 vertical로 지정됐고

그 속에 2,3이 포함된 레이아웃은 속성값이 horizontal로 지정돼서 가로로 나열됨

이때 4에만 가중치 주면 (세로 중에 하나만 가중치 1 받으면 걔가 나머지 꽉 채우나봐) 4가 여백 채우고

2,3은 각각 가중치 1,3으로 받으면 가로 여백을 1대3으로 나눠가짐

이때 2와 3에 설정한 가중치와 4에 설정한 가중치는 서로 영향을 미치지 않는다.

즉, layout_weight 속성은 같은 영역에 있는 뷰끼리만 여백을 나누어 차지한다. 

 

 

여백 채우기로 뷰의 크기 설정하기

layout_weight는 여백을 채우는 속성이지만 뷰의 크기를 0으로 하고 layout_weight값만 설정하기도 한다.

버튼 세개를 모두 크기를 0으로 하고 layout_weight 속성을 0으로 지정하면 셋이서 사이좋게 여백을 3등분비율로 가져간다.

// layout_weight값으로 뷰의 크기 설정
<Button
	android:layout_height="0dp"
	android:layout_weight="1" />

 

 

뷰를 정렬하는 gravity, layout_gravity 속성

이 속성들을 이용하지 않으면 뷰의 기본값은 left/top이다. 즉, 왼쪽 위를 기준으로 정렬한다.

아무 뷰나 출력해보면 왼쪽 위에 딱붙어서 나온다.  정렬을 해보면 다음과 같이 쓴다.

// 정렬 속성 예시
<LinearLayout
	android:orientation="vertical">
	<TextView
		android:gravity="right|bottom"
		android:layout_gravity="center_horizontal" />
</LinearLayout>

gravitylayout_gravity는 모두 뷰를 정렬하는 속성이지만 정렬 대상이 다르다. gravity 속성의 정렬 대상은 콘텐츠이다. 따라서 위 예에서는 (생략된) 텍스트 뷰의 콘텐츠인  "HelloWorld" 문자열이 '텍스트 뷰가 차지하는 영역'에서 오른쪽 아래에 표시된다. 반면에 layout_gravity는 뷰 자체를 정렬하는 속성이다. 따라서 텍스트 뷰 자체가 가로로 가운데에 표시된다. 

 

 

레이아웃에 gravity 속성 적용하기

그런데 위의 에에서 layout_gravity 속성을 center_vertical(세로로 가운데) 값으로 지정하면 정렬이 적용되지 않는다(!!)

즉, layout_gravity 속성을 설정하지 않았을 때와 결과와 같다. 그 이유는 LinearLayout 자체가 '방향으로 뷰를 배치하는 레이아웃'이므로 LinearLayout의 orientation 속성에 설정한 방향과 같은 방향으로는 layout_gravity 속성이 적용되지 않기 때문이다.

"그렇다면 뷰를 LinearLayout 영역의 가운데로 정렬할 수는 없을까?"

뷰를 화면가운데에 표시하려면 뷰에 layout_gravity="center"로 설정하는 게 아니라 레이아웃에 gravity="center"로 설정해야 한다.

// 뷰를 화면 가운데로 정렬하는 예시
<LinearLayout
	android:gravity="center"> // 뷰를 화면 가운데로 정렬해라
    <TextView
    	android:gravity="right|bottom" /> // '뷰 안의' 컨텐츠를 '뷰의 오른쪽 아래로' 정렬해라
</LinearLayout>

다시 한번 짚고 넘어가자면, gravity콘텐츠를 정렬하는 속성이다. 콘텐츠는 해당 레이아웃에 추가한 뷰이므로 LinearLayout에 gravity속성을 추가하면 위의 결과처럼 정렬할 수 있다.

 

 

 

'깡샘 코틀린' 카테고리의 다른 글

07-3 겹쳐서 배치 - FrameLayout  (0) 2023.06.20
07-2 상대 위치로 배치 - RelativeLayout  (0) 2023.06.19
06-4 뷰 바인딩  (2) 2023.06.17
06-3 기본적인 뷰 살펴보기  (1) 2023.06.17
06-2 뷰 클래스  (0) 2023.06.15