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

안드로이드(Android)에서 현재 화면 방향(세로·가로 모드)을 확인하는 방법


앱을 개발하다 보면 현재 액티비티의 화면 방향이 세로 모드(Portrait)인지 가로 모드(Landscape)인지 확인해야 하는 경우가 종종 있습니다. 이 글에서는 안드로이드에서 현재 화면 방향을 가져와 화면에 표시하는 방법을 단계별 예제를 통해 알아보겠습니다.

1단계 — 새 프로젝트 생성

Android Studio에서 File ⇒ New Project를 선택해 새 프로젝트를 만들고, 필요한 모든 정보를 입력하여 프로젝트를 완성합니다.

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

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

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
    android:id = "@+id/parent"
    xmlns:tools = "https://schemas.android.com/tools"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".MainActivity"
    android:gravity = "center"
    android:orientation = "vertical">
    <TextView
        android:id = "@+id/text"
        android:textSize = "28sp"
        android:textAlignment = "center"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content" />
</LinearLayout>

위 코드에는 TextView 하나만 배치되어 있습니다. 화면 방향에 따라 이 TextView의 텍스트가 자동으로 갱신됩니다.

3단계 — MainActivity 코드 작성

src/MainActivity.java 파일에 아래 코드를 추가합니다.

package com.example.andy.myapplication;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
    int view = R.layout.activity_main;
    TextView textview;
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(view);
        textview = findViewById(R.id.text);
        int orientation = this.getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_PORTRAIT) {
            textview.setText("Portrait mode");
        } else {
            textview.setText("landscape mode");
        }
    }
}

핵심 로직은 화면 방향 값을 정수형 변수로 받아온 뒤, Configuration 클래스의 방향 상수와 비교하는 부분입니다.

int orientation = this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
    textview.setText("Portrait mode");
} else {
    textview.setText("landscape mode");
}

코드 설명: getResources().getConfiguration().orientation은 현재 화면 방향을 정수 값으로 반환합니다. 반환된 값이 Configuration.ORIENTATION_PORTRAIT이면 세로 모드이고, 그 외의 값(ORIENTATION_LANDSCAPE)이면 가로 모드로 판단할 수 있습니다.

4단계 — 앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 목록에서 본인의 모바일 기기를 선택하세요. 그러면 기기 화면에 다음과 같은 결과가 표시됩니다.

안드로이드(Android)에서 현재 화면 방향(세로·가로 모드)을 확인하는 방법

기기를 세로로 들고 있으면 위와 같이 Portrait mode가 표시됩니다. 이제 기기를 옆으로 돌려 가로 모드로 전환하면 아래와 같은 결과가 나타납니다.

안드로이드(Android)에서 현재 화면 방향(세로·가로 모드)을 확인하는 방법

참고: 화면 회전 시 동작 처리하기

기본적으로 기기를 회전하면 액티비티가 다시 생성(recreate)되므로 onCreate()가 재호출되어 위 코드도 자연스럽게 동작합니다. 만약 액티비티가 재생성되지 않은 상태에서 방향 변화를 감지하고 싶다면, 매니페스트의 해당 액티비티에 android:configChanges="orientation|screenSize" 속성을 추가하고 onConfigurationChanged() 콜백에서 방향 값을 확인하면 됩니다.