이 예제는 안드로이드 기기의 화면 높이(height), 화면 너비(width), 그리고 대각선 길이(인치)까지 구하는 방법을 보여줍니다. 안드로이드에서는 DisplayMetrics 클래스를 활용하면 화면 크기와 관련된 다양한 정보를 손쉽게 얻을 수 있습니다.
Step 1 – 새 프로젝트 생성
Android Studio에서 File → New Project를 선택한 후, 필요한 항목을 모두 입력해 새 프로젝트를 생성합니다.
Step 2 – res/layout/activity_main.xml 코드 작성
레이아웃 파일에 아래 코드를 추가합니다. 화면 높이, 화면 너비, 화면 인치를 각각 표시할 TextView 3개를 세로로 배치했습니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="30dp"
tools:context=".MainActivity">
<TextView
android:id="@+id/getScreenHeight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20sp"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/getScreenWidth"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="@+id/getScreenInches"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
Step 3 – src/MainActivity.java 코드 작성
DisplayMetrics 객체에 화면 정보를 담은 뒤, 픽셀 값으로 높이와 너비를 얻고, DPI(인치당 도트 수) 값을 이용해 대각선 인치까지 계산합니다.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView height, width, inches;
DisplayMetrics displayMetrics;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
height = findViewById(R.id.getScreenHeight);
width = findViewById(R.id.getScreenWidth);
inches = findViewById(R.id.getScreenInches);
displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenHeight = displayMetrics.heightPixels;
int screenWidth = displayMetrics.widthPixels;
// 피타고라스 정리를 이용해 대각선 인치 계산
// 참고: 세로 길이에는 ydpi를 사용해야 정확합니다.
double y = Math.pow(screenHeight / displayMetrics.ydpi, 2);
double x = Math.pow(screenWidth / displayMetrics.xdpi, 2);
double screenInches = Math.sqrt(x + y);
screenInches = (double) Math.round(screenInches * 10) / 10;
height.setText("Screen Height: " + screenHeight + " px");
width.setText("Screen Width: " + screenWidth + " px");
inches.setText("Screen Inches: " + screenInches);
}
}
참고: 원본 예제의 너비 출력 부분에는 "Screen Height"로 표시되는 오타가 있었으며, 대각선 계산 시 세로 길이를
xdpi로 나누는 오류도 있었습니다. 위 코드에서는ydpi를 사용하도록 바로잡았습니다.
Step 4 – AndroidManifest.xml 코드 작성
매니페스트 파일에는 별도의 권한 선언 없이 기본 액티비티 설정만 추가하면 됩니다.
<?xml version="1.0" encoding="utf-8"?>
<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(실행) 아이콘을 클릭하세요. 실행 기기 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같이 화면 높이·너비·인치 정보가 표시됩니다.

추가 팁 – 최신 API(WindowMetrics) 활용하기
위 예제에서 사용한 getWindowManager().getDefaultDisplay() 방식은 API 레벨 30(Android 11)부터 deprecated되었습니다. 최신 프로젝트라면 OS 버전에 따라 분기 처리하여 WindowMetrics를 사용하는 것이 권장됩니다.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
// Android 11(API 30) 이상
WindowMetrics metrics = getWindowManager().getCurrentWindowMetrics();
Rect bounds = metrics.getBounds();
int screenHeight = bounds.height();
int screenWidth = bounds.width();
} else {
// 하위 버전 호환
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
}이처럼 DisplayMetrics 또는 WindowMetrics를 활용하면 반응형 레이아웃 설계나 화면 비율에 따른 UI 조정 등 다양한 상황에서 유용하게 활용할 수 있습니다.