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

안드로이드에서 화면 방향 변경(오리엔테이션) 처리하는 방법

안드로이드 화면 방향 변경 처리 개요

이 튜토리얼에서는 안드로이드 앱에서 화면 방향 변경(세로 모드 ↔ 가로 모드 전환)을 감지하고 처리하는 방법을 단계별로 살펴봅니다. onConfigurationChanged() 콜백 메서드와 매니페스트의 configChanges 속성을 함께 활용하면, 액티비티가 재생성되지 않고도 방향 변화에 즉시 대응할 수 있습니다.


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"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/actionEvent"
      android:textSize = "40sp"
      android:layout_marginTop = "30dp"
      android:layout_width = "wrap_content"
      android:layout_height = "match_parent" />
</LinearLayout>

위 코드에서는 화면 방향 변화를 사용자에게 표시하기 위해 TextView 하나를 배치했습니다.

3단계: MainActivity 작성

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

package com.example.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 {
   TextView actionEvent;
   @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      actionEvent = findViewById(R.id.actionEvent);
   }
   @Override
   public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
         actionEvent.setText("ORIENTATION LANDSCAPE");
      } else {
         actionEvent.setText("ORIENTATION PORTRAIT");
      }
   }
}

onConfigurationChanged() 메서드는 시스템 설정이 변경될 때 호출됩니다. 이 예제에서는 새로운 설정(newConfig)의 orientation 값이 ORIENTATION_LANDSCAPE인지 확인하여 현재 상태가 가로 모드인지 세로 모드인지 판단하고, 그 결과를 TextView에 출력합니다.

4단계: 매니페스트 설정

manifest.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|screenSize">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

여기서 핵심은 activity 태그의 android:configChanges = "keyboardHidden|orientation|screenSize" 속성입니다. 이 속성을 지정하면 화면 방향이 바뀌더라도 액티비티가 재생성되지 않고, 대신 onConfigurationChanged() 콜백이 호출되어 원하는 로직을 직접 처리할 수 있습니다.

앱 실행 및 결과 확인

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

안드로이드에서 화면 방향 변경(오리엔테이션) 처리하는 방법

이제 아래와 같이 화면을 회전시켜 봅니다.

안드로이드에서 화면 방향 변경(오리엔테이션) 처리하는 방법

화면을 가로로 돌리면 TextView에 "ORIENTATION LANDSCAPE" 문구가, 다시 세로로 돌리면 "ORIENTATION PORTRAIT" 문구가 표시되는 것을 확인할 수 있습니다. 이처럼 configChanges 속성과 onConfigurationChanged() 콜백을 조합하면 방향 변경 시 데이터 손실 없이 유연하게 대응할 수 있습니다.