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

안드로이드에서 가로 모드(랜드스케이프) 화면 전환을 감지하는 방법

이 튜토리얼에서는 안드로이드 앱에서 기기의 화면 방향이 가로 모드(랜드스케이프)로 변경되었는지 감지하고, 그에 맞게 UI를 업데이트하는 방법을 단계별로 알아봅니다.

1단계: 새 프로젝트 생성

Android Studio를 실행한 뒤 File → New Project 메뉴로 이동하여 필요한 정보를 모두 입력하고 새 프로젝트를 생성합니다.

2단계: 레이아웃 파일 작성 (res/layout/activity_main.xml)

아래 코드를 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단계: MainActivity.java 작성

아래 코드를 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");
        }
    }
}

핵심은 onConfigurationChanged() 콜백 메서드입니다. 화면 방향이 변경될 때마다 이 메서드가 호출되며, 여기서 Configuration.ORIENTATION_LANDSCAPE 값과 비교하여 현재 상태가 가로 모드인지 판단할 수 있습니다. 참고로 세로 모드로 돌아올 때도 별도로 처리하고 싶다면 else if (_newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) 분기를 추가하면 됩니다.

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>

여기서 가장 중요한 부분은 activity 태그의 android:configChanges="keyboardHidden|orientation" 속성입니다. 이 속성을 지정해야 화면 방향이 바뀌어도 액티비티가 재생성되지 않고, 대신 onConfigurationChanged() 콜백이 정상적으로 호출됩니다.

앱 실행 및 결과 확인

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

안드로이드에서 가로 모드(랜드스케이프) 화면 전환을 감지하는 방법

기기를 가로로 회전하면 액티비티가 재시작되지 않고 onConfigurationChanged()가 호출되어, 화면에 "It is landscape"라는 문구가 표시되는 것을 확인할 수 있습니다.