JooTC
android-card-1908-blue

[안드로이드/JAVA] ScrollView 내 레이아웃 높이 가득 채우기

ScrollView 안의 레이아웃 높이를 가득 채우기


안드로이드 레이아웃 파일(XML)을 작성하다 보면 종종 ScrollView를 사용하는 경우가 있습니다. ScrollView는 길어지는 높이로 인해 화면에서 일부 뷰가 잘리는 현상을 상하 스크롤을 통해 해소할 수 있는 뷰입니다.

android-scrollview-example

ScrollView 내에는 하나의 자식 뷰만 포함되어야 합니다. 여러개의 뷰를 넣으려면 LinearLayout이나 RelativeLayout 등의 뷰그룹을 자식 뷰로 지정하고 그 안에 다양한 뷰를 넣는 구조를 택하여 해결할 수 있습니다. 만약 두 개 이상의 뷰 또는 뷰그룹을 ScrollView에 넣게 되면 다음과 같은 에러 메시지가 나타납니다.

A scroll view can have only one child less... (Ctrl+F1) 
Inspection info:ScrollViews can only have one child widget. If you want more children, wrap them in a container layout.

Issue id: ScrollViewCount

그런데 LinearLayout, RelativeLayout과 같은 뷰 그룹 내에 각종 뷰를 작성한 후에 레이아웃이 나타나는 결과를 확인해보면 높이에 여백이 생기는 경우가 있을 것입니다. 아래와 같은 예시를 살펴보겠습니다.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:background="@color/colorBlue"
            android:text="TEST"
            android:textSize="50sp"
            android:textColor="@color/colorWhite"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
</ScrollView>

특별한 문제가 없어보이는 코드이지만 미리보기 화면에서는 다음과 같이 나타납니다.

android-scrollview-empty-space-1

ScrollView의 자식 뷰의 높이는 wrap_content여야 합니다. 위 예시에서는 LinearLayout의 높이가 wrap_content이며 TextView의 높이가 match_parent이므로 결과적으로는 TextView의 높이는 화면을 가득 채워야 할 것입니다. 그러나 TextView의 높이가 match_parent임에도 불구하고 화면의 전체 높이이자 ScrollView의 높이인 파란 테두리만큼 채워지지 않는 것을 확인할 수 있습니다.

그렇다면 어떻게 남아있는 공간을 꽉 채울 수 있을까요?

방법은 간단합니다. ScrollView의 속성에 다음 한 줄만 추가해주시면 됩니다.

android:fillViewport="true"

android:fillViewport="true"‘남아있는 공백을 자식 뷰의 높이만큼 채우겠다’고 해석할 수 있습니다. 다음은 위 예시를 통해 적용된 코드의 예시입니다.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillViewport="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:background="@color/colorBlue"
            android:text="TEST"
            android:textSize="50sp"
            android:textColor="@color/colorWhite"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    </LinearLayout>
</ScrollView>

이제 다시 미리보기를 확인해보면, 문제 없이 화면을 모두 채우게 된 모습을 확인할 수 있습니다.

android-scrollview-empty-space-2

 

참고 링크


구독
알림
guest

0 Comments
Inline Feedbacks
모든 댓글 보기
0
이 포스트에 대한 의견을 남겨주세요!x
error: 콘텐츠 무단 사용, 도용 사례로 인해 복사가 제한됩니다. 링크(URL)첨부를 사용해주세요. (소스코드는 복사할 수 있어요)