안드로이드 앱을 개발하다 보면 기기의 회전 상태와 관계없이 특정 화면 방향을 유지해야 하는 경우가 많습니다. 이 글에서는 프로그래밍 방식으로 모든 안드로이드 기기에서 화면 방향을 잠그는 방법을 단계별로 살펴보겠습니다.
핵심 아이디어는 간단합니다. 현재 기기의 방향(세로 또는 가로)을 확인한 후, 해당 방향으로 화면을 고정하는 것입니다. 이렇게 하면 사용자가 기기를 회전하더라도 앱 화면은 처음 방향을 그대로 유지하게 됩니다.
1단계 — 새 프로젝트 생성
Android Studio에서 File → New Project를 선택한 후, 필요한 모든 정보를 입력하여 새 프로젝트를 만듭니다.
2단계 — 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Screen Orientation Lock"
android:textSize="24sp"
android:textStyle="bold"/>
</RelativeLayout>레이아웃은 화면 중앙에 "Screen Orientation Lock"이라는 텍스트를 표시하는 단순한 구조입니다.
3단계 — MainActivity 코드 작성
src/MainActivity.java 파일에 다음 코드를 추가합니다.
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
}
}코드 동작 원리
getResources().getConfiguration().orientation을 호출하면 현재 기기의 방향을 가져올 수 있습니다. 현재 방향이 세로(PORTRAIT)라면 setRequestedOrientation() 메서드로 세로 방향을 고정하고, 그렇지 않다면 가로(LANDSCAPE) 방향으로 고정합니다. 즉, 앱이 시작된 방향에 따라 그 방향이 계속 유지되는 방식입니다.
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 아이콘을 클릭하고, 목록에서 자신의 모바일 기기를 선택합니다. 그러면 기기 화면에 아래와 같이 기본 화면이 표시됩니다.

이처럼 몇 줄의 코드만으로도 모든 안드로이드 기기에서 화면 방향을 손쉽게 잠글 수 있습니다. 참고로 코드가 아닌 XML에서 방향을 고정하고 싶다면, 매니페스트의 activity 태그에 android:screenOrientation="portrait" 속성을 추가하는 방법도 활용할 수 있습니다.