본문 바로가기
프로젝트 기록/android

[android/안드로이드] Relative Layout/margin이 적용되지 않는다. +오류상황

by 새아SaeA 2020. 1. 17.

#Relative Layout에서의 error

 

1. margin이 적용되지 않는다.

2. centerInParent/vertical/horizontal이 적용되지 않는다.

 

 

#Solution

두 가지 모두 layout_width와 layout_height 때문이다.

 

오류 예시

 <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <Button
            android:id="@+id/chButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Next page"
            android:textAllCaps="false"
            android:layout_centerInParent="true"
            android:layout_marginBottom="50dp"/>

    </RelativeLayout>

 1.  height가 wrap_content로 버튼의 높이로 설정되어 있으므로 marginBottom을 주어도 적용되지 않는다. margin은 콘텐츠의 바깥 부분을 차지하는 공간이기 때문에 바깥에 공간이 없다면 적용되지 않는다. 동일한 이유요 marginTop, marginVertical도 마찬가지이다.

  하지만 padding의 경우는 적용된다. padding은 컨텐츠 내부에서 차지하는 공간으로 위의 예시를 참고하자면 RelativeLayout의 높이가button의 높이만큼 차지하고 있기 때문에, button의 높이가 길어지거나 짧아지면 그에 맞추어 RelativeLayout의 높이도 변경될 수 있기 때문이다. 

 

 2. 이 경우 layout_centerInParent를 해도 horizontal(수평) 방향으로만 중간에 가있다. 그 이유는 RelativeLayout에서의 정렬은 언제나 RelativeLayout의 width/height를 기준으로 하기 때문이다. 

  예시에서 width는 match_parent로 화면 넓이를 차지하고 있고, height는 wrap_content로 포함되어있는 버튼의 높이만큼만 차지하고 있다. 때문에 centerInParent를 해도 수직방향으로는 움직일 공간이 없기 때문에 수평방향으로만 정렬이 되는 것이다. 

  반대로 width : wrap_content, height : match_parent라면 수평방향으로는 움직이지 않고 수직방향으로만 움직이게 될 것이다.