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

Android에서 세로·가로 방향별로 다른 레이아웃을 지정하는 방법

안드로이드 앱을 개발하다 보면 기기가 세로(Portrait) 모드일 때와 가로(Landscape) 모드일 때 서로 다른 화면 배치를 적용해야 하는 경우가 자주 있습니다. 이 예제에서는 안드로이드에서 방향(오리엔테이션)에 따라 각각 다른 레이아웃을 지정하는 방법을 단계별로 알아보겠습니다.

핵심 원리

안드로이드는 리소스 한정자(Resource Qualifier)를 통해 화면 상태에 맞는 리소스를 자동으로 선택합니다. 레이아웃 폴더 이름 끝에 -land를 붙이면 가로 모드에서 해당 폴더의 레이아웃이 우선적으로 사용되고, 그 외의 경우에는 기본 layout 폴더의 레이아웃이 적용됩니다.

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:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f2f6f4"
    android:padding="10dp"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tvLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button"
        android:layout_centerInParent="true"
        android:layout_marginTop="16sp"
        android:text="Portrait Mode"
        android:textSize="24sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Show Orientation mode" />
</RelativeLayout>

3단계 — 가로 모드용 레이아웃 폴더 생성

다음 순서로 가로 모드 전용 레이아웃을 만듭니다.

  • res 폴더를 마우스 오른쪽 버튼으로 클릭한 뒤 New → Android Resource Directory를 선택합니다.
  • 디렉터리 이름을 지정하고, Available qualifiers 목록에서 Orientation을 선택한 후 >> 버튼을 눌러 추가합니다.
  • UI 모드에서 Landscape를 선택합니다. 그러면 res/layout-land 폴더가 생성됩니다.

생성된 res/layout-land/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:id="@+id/tvLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginStart="64dp"
        android:layout_toEndOf="@id/button"
        android:text="Landscape Mode"
        android:textSize="24sp"
        android:textStyle="bold" />
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginStart="128sp"
        android:text="Show Orientation mode" />
</RelativeLayout>

참고: 두 레이아웃 파일에서 위젯의 ID(tvLayout, button)는 반드시 동일하게 유지해야 합니다. ID가 일치하지 않으면 방향이 바뀔 때 findViewById()가 null을 반환해 앱이 강제 종료될 수 있습니다.

4단계 — MainActivity 코드 작성

src/MainActivity.kt 파일에 아래 코드를 추가합니다. 버튼을 클릭하면 현재 기기의 방향을 판단하여 토스트 메시지로 알려줍니다.

import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
    lateinit var textView: TextView
    lateinit var button: Button
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        textView = findViewById(R.id.tvLayout)
        button = findViewById(R.id.button)
        button.setOnClickListener {
            if (button.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                Toast.makeText(this@MainActivity, " We are in portrait mode",
                    Toast.LENGTH_SHORT).show()
            }
            else {
                Toast.makeText(this@MainActivity, "We are in Landscape mode",
                    Toast.LENGTH_SHORT).show()
            }
        }
    }
}

5단계 — AndroidManifest.xml 확인

androidManifest.xml 파일은 아래와 같습니다. 별도의 설정 변경 없이 기본 구성만으로 동작합니다.

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

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 결과를 확인해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 툴바의 Run 아이콘을 클릭하고, 실행 옵션에서 연결된 모바일 기기를 선택하세요.

기기에서 앱이 실행되면 기본 화면이 표시됩니다. 기기를 회전시키면 세로 모드와 가로 모드에서 각각 다른 레이아웃이 자동으로 적용되는 것을 확인할 수 있으며, 버튼을 누르면 현재 방향을 알려주는 토스트 메시지가 나타납니다.

Android에서 세로·가로 방향별로 다른 레이아웃을 지정하는 방법

Android에서 세로·가로 방향별로 다른 레이아웃을 지정하는 방법