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

Kotlin으로 Android 화면 방향(가로/세로) 변경 감지하는 방법

Kotlin으로 Android에서 레이아웃 방향 변경 감지하기

Android 앱을 개발하다 보면 사용자가 기기를 가로 모드나 세로 모드로 회전할 때 이를 감지하고 그에 맞는 동작을 처리해야 하는 경우가 많습니다. 이번 튜토리얼에서는 Kotlin을 사용하여 Android에서 화면 방향 변경을 감지하는 방법을 단계별로 알아보겠습니다.

방향 변경을 감지하는 핵심은 onConfigurationChanged() 콜백 메서드입니다. 이 메서드를 오버라이드하면 시스템 구성(configuration)이 변경될 때마다 알림을 받을 수 있으며, 전달되는 Configuration 객체의 orientation 값을 확인하여 현재 방향이 가로인지 세로인지 판단할 수 있습니다.

1단계: 새 프로젝트 생성

Android Studio를 열고 File ⇒ New Project 메뉴로 이동한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다. 언어는 Kotlin으로 선택하세요.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml 파일에 아래 코드를 추가합니다. 화면 상단에는 앱 제목용 TextView가, 중앙에는 'Hello World!' 문구가 표시되도록 구성했습니다.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Tutorials Point"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />
    <TextView
        android:layout_centerInParent="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

3단계: MainActivity.kt 작성

src/MainActivity.kt 파일에 아래 코드를 추가합니다. 여기서 핵심은 onConfigurationChanged() 메서드입니다. 새로운 구성 정보가 전달되면 newConfig.orientation 값을 확인하여 ORIENTATION_LANDSCAPE(가로 모드) 또는 ORIENTATION_PORTRAIT(세로 모드)에 따라 토스트 메시지를 표시합니다.

import android.content.res.Configuration
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
    }
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Toast.makeText(baseContext, "Landscape Mode", Toast.LENGTH_SHORT).show()
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Toast.makeText(baseContext, "Portrait Mode", Toast.LENGTH_SHORT).show()
        }
    }
}

4단계: AndroidManifest.xml 설정

androidManifest.xml 파일에 아래 코드를 추가합니다. 중요한 부분은 <activity> 태그 안에 android:configChanges="orientation|screenSize" 속성을 추가하는 것입니다. 이 속성이 있어야 기기가 회전할 때 액티비티가 재생성되지 않고 onConfigurationChanged() 콜백이 호출됩니다.

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

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 다음, 툴바에서 Kotlin으로 Android 화면 방향(가로/세로) 변경 감지하는 방법 Run 아이콘을 클릭하세요.

옵션 목록에서 연결된 모바일 기기를 선택하면, 해당 기기에 앱이 설치되고 기본 화면이 표시됩니다.

Kotlin으로 Android 화면 방향(가로/세로) 변경 감지하는 방법

기기를 가로로 회전하면 onConfigurationChanged()가 자동으로 호출되어 'Landscape Mode' 토스트 메시지가 나타나고, 다시 세로로 돌리면 'Portrait Mode' 메시지가 표시되는 것을 확인할 수 있습니다.

Kotlin으로 Android 화면 방향(가로/세로) 변경 감지하는 방법

마무리 및 추가 팁

위 예제에서는 토스트 메시지만 표시했지만, 실제 프로젝트에서는 방향에 따라 다른 레이아웃 리소스를 적용하거나 UI 요소를 재배치하는 등의 처리를 할 수 있습니다. 참고로 android:configChanges 속성을 사용하지 않으면 기기 회전 시 액티비티가 자동으로 재생성되며, 이 경우 onCreate()에서 resources.configuration.orientation 값을 확인하는 방식으로도 현재 방향을 파악할 수 있습니다. 두 방식의 차이를 이해하고 상황에 맞게 활용하시기 바랍니다.