이 튜토리얼에서는 안드로이드 애플리케이션이 기기의 화면 방향 변경(가로·세로 회전)을 무시하도록 만드는 방법을 단계별로 살펴봅니다. 화면 방향을 고정하면 사용자가 기기를 돌려도 액티비티가 다시 생성되지 않아 레이아웃이 초기화되는 문제를 예방할 수 있습니다.
구현 단계
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project를 선택한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 생성합니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.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: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" /> </androidx.constraintlayout.widget.ConstraintLayout>
3단계 — MainActivity 작성
src/MainActivity.java에 아래 코드를 추가합니다. 핵심은 setRequestedOrientation() 메서드입니다.
package com.app.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)를 호출하면 해당 액티비티가 항상 세로 모드로 유지됩니다. 반대로 가로 모드로 고정하고 싶다면 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE를 인자로 전달하면 됩니다.
4단계 — 매니페스트 설정
Manifests/AndroidManifest.xml에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.app.sample"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <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>
참고로 자바 코드 대신 매니페스트에서 바로 방향을 고정할 수도 있습니다. <activity> 태그에 android:screenOrientation="portrait" 속성을 추가하면 위 코드와 동일한 효과를 얻을 수 있습니다.
실행 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 실행(Run)
아이콘을 클릭합니다. 기기 목록에서 사용 중인 모바일 기기를 선택한 뒤 화면을 확인합니다.
기기를 회전시켜도 화면이 세로 모드로 그대로 고정되어 있는 것을 확인할 수 있습니다.
