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

안드로이드 앱에서 세로 모드(화면 방향)를 확인하는 방법


개요

이 예제는 안드로이드 앱에서 현재 화면이 세로 모드(포트레이트)인지 확인하는 방법을 다룹니다. 기기가 회전하거나 화면 방향이 바뀔 때 이를 감지하여 UI나 동작을 변경해야 하는 경우에 유용하게 활용할 수 있는 기법입니다.

1단계 — 새 프로젝트 생성

Android Studio를 실행한 후 File → New Project를 선택하고, 프로젝트 생성에 필요한 모든 정보를 입력해 새 프로젝트를 만듭니다.

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

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

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/conf"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

위 코드에서는 화면의 현재 모드 이름을 표시하기 위해 TextView 하나를 화면 중앙에 배치했습니다.

3단계 — 메인 액티비티 코드 작성

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

package com.example.myapplication;

import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView conf;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        conf = findViewById(R.id.conf);
    }
    @Override
    public void onConfigurationChanged(Configuration _newConfig) {
        super.onConfigurationChanged(_newConfig);
        if (_newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            conf.setText("It is landscape");
        } else {
            conf.setText("It is portrait mode");
        }
    }
}

이 코드의 핵심은 onConfigurationChanged() 콜백 메서드입니다. 이 메서드는 시스템 구성(화면 방향 등)이 변경될 때마다 호출되며, 전달된 Configuration 객체의 orientation 값을 검사해 현재 화면이 가로 모드(ORIENTATION_LANDSCAPE)인지 세로 모드인지 판단한 후 그 결과를 TextView에 표시합니다.

4단계 — AndroidManifest.xml 설정

AndroidManifest.xml 파일에 아래 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.myapplication">

    <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"
            android:configChanges="keyboardHidden|orientation" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

여기서 주목해야 할 부분은 액티비티 태그의 android:configChanges="keyboardHidden|orientation" 속성입니다. 이 속성을 지정하면 화면 방향이 바뀔 때 액티비티가 재생성되지 않고 onConfigurationChanged() 콜백을 통해 변경 사항을 직접 처리할 수 있습니다. 이 속성이 없으면 위의 콜백 메서드가 호출되지 않으므로 반드시 함께 설정해야 합니다.

앱 실행 및 결과 확인

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

이후 기기를 가로 또는 세로로 회전시켜 보면, 화면에 표시된 문구가 "It is landscape"(가로 모드) 또는 "It is portrait mode"(세로 모드)로 즉시 갱신되는 것을 확인할 수 있습니다.

안드로이드 앱에서 세로 모드(화면 방향)를 확인하는 방법