Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

런타임에 안드로이드 뷰(View)의 크기를 확인하는 방법

안드로이드 앱을 개발하다 보면 화면이 실제로 배치된 이후에 뷰(View)의 실제 크기, 즉 너비와 높이를 알아야 하는 경우가 자주 있습니다. 하지만 onCreate() 메서드가 실행되는 시점에는 뷰가 아직 측정(measure)·배치(layout)되지 않았기 때문에 getWidth()getHeight()를 호출하면 0이 반환됩니다.

이 예제에서는 ViewTreeObserver.OnGlobalLayoutListener를 활용해 레이아웃이 완료된 시점에 뷰의 크기를 정확하게 가져오는 방법을 단계별로 살펴보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio를 실행한 뒤 File ⇒ New Project 메뉴로 이동하고, 새 프로젝트 생성에 필요한 모든 정보를 입력해 프로젝트를 만듭니다.

2단계 — 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:layout_gravity="center"
        android:layout_margin="20sp"
        android:src="@drawable/image"/>
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginTop="20sp"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_below="@id/imageView"/>
</RelativeLayout>

레이아웃은 ImageView 하나와, 뷰 크기를 표시할 TextView 하나로 구성되어 있습니다.

3단계 — 이미지 리소스 추가

화면에 표시할 이미지 파일(.png / .jpg / .jpeg)을 res/drawable 폴더에 복사해 붙여넣습니다. 파일 이름은 image.png처럼 영문 소문자로 지정하는 것이 좋습니다.

4단계 — MainActivity.java 코드 작성

src/MainActivity.java에 다음 코드를 추가합니다.

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new GetViewSize());
    }
    class GetViewSize implements ViewTreeObserver.OnGlobalLayoutListener {
        @Override
        public void onGlobalLayout() {
            View v = findViewById(R.id.imageView);
            String x = Integer.toString(v.getWidth());
            String y = Integer.toString(v.getHeight());
            ((TextView)findViewById(R.id.textView)).setText(String.format("Width %s, Height: %s", x, y));
        }
    }
}

핵심 포인트: OnGlobalLayoutListener는 뷰 계층 구조의 레이아웃이 완료되는 순간 호출됩니다. 따라서 이 시점에는 getWidth()getHeight()가 픽셀(px) 단위의 실제 크기를 반환합니다. 참고로 이 리스너는 레이아웃이 변경될 때마다 반복 호출될 수 있으므로, 크기를 한 번만 얻고 싶다면 값을 읽은 후 removeOnGlobalLayoutListener()로 리스너를 제거하는 것이 좋습니다.

5단계 — AndroidManifest.xml 설정

androidManifest.xml에 아래 코드를 추가합니다.

<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 안드로이드 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 버튼을 클릭하세요. 실행 옵션으로 사용 중인 모바일 기기를 선택하면, 연결된 기본 화면에 앱이 표시됩니다.

앱이 실행되면 ImageView의 실제 너비와 높이가 픽셀 값으로 계산되어 화면 중앙의 TextView에 "Width ○○○, Height: ○○○" 형태로 출력되는 것을 확인할 수 있습니다.

런타임에 안드로이드 뷰(View)의 크기를 확인하는 방법