Computer >> 컴퓨터 >  >> 프로그래밍 >> 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"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:background = "#dde4dd">
   <EditText
      android:id = "@+id/editText"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content" />
</LinearLayout>

위 코드는 LinearLayout과 EditText로 구성된 간단한 레이아웃입니다. 이 상태에서는 아래와 같이 가로 모드와 세로 모드가 모두 지원됩니다.

안드로이드에서 가로 모드(가로 방향)를 비활성화하는 방법

위 출력 결과는 가로 모드 화면입니다.

안드로이드에서 가로 모드(가로 방향)를 비활성화하는 방법

위 출력 결과는 세로 모드 화면입니다.

3단계: 매니페스트에서 화면 방향 고정하기

가로 모드를 비활성화하려면 AndroidManifest.xml 파일에 screenOrientation 속성을 추가해야 합니다. 아래 코드를 참고하세요.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android" package = "com.example.andy.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:screenOrientation = "portrait">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

위 코드에서 MainActivity의 screenOrientation 속성을 portrait로 지정했습니다. 따라서 해당 액티비티는 세로 모드만 지원하게 됩니다. 만약 앱 전체를 세로 모드로 고정하고 싶다면 application 태그 내부에 screenOrientation 속성을 추가하면 됩니다.

참고: screenOrientation의 주요 값

  • portrait: 세로 모드로 고정
  • landscape: 가로 모드로 고정
  • sensor: 기기 센서에 따라 자동 회전
  • unspecified: 시스템이 임의로 결정 (기본값)

앱 실행 및 결과 확인

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

안드로이드에서 가로 모드(가로 방향)를 비활성화하는 방법

위 결과에서 확인할 수 있듯이 화면이 세로 모드로만 표시됩니다. 이제 기기를 돌려도 화면 방향에 따라 뷰가 더 이상 변경되지 않습니다.