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

Kotlin으로 안드로이드 액티비티 간 객체 전달하기 – Serializable 완벽 가이드

이 튜토리얼에서는 Kotlin을 사용해 안드로이드에서 한 액티비티(Activity)에서 다른 액티비티로 객체(Object)를 전달하는 방법을 단계별로 알아봅니다. 인텐트(Intent)에 커스텀 객체를 담아 전송하려면 해당 클래스가 Serializable 또는 Parcelable 인터페이스를 구현해야 하는데, 이 예제에서는 간편한 Serializable 방식을 사용합니다.

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_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        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="Click here to pass object to Second Activity!" />
</RelativeLayout>

3단계 – MainActivity.kt 작성

src/MainActivity.kt에 다음 코드를 추가합니다. 버튼을 클릭하면 Character 객체를 생성해 인텐트의 엑스트라(Extra)에 담아 두 번째 액티비티로 전달합니다.

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import java.io.Serializable;
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "KotlinApp"
        val button: Button = findViewById(R.id.button)
        button.setOnClickListener {
            val intent = Intent(applicationContext, SecondActivity::class.java)
            val sports = Character("CR7", "Football", "Left Winger", arrayOf("Best player in the World"))
            intent.putExtra("Character", sports)
            startActivity(intent)
        }
    }
}
class Character(var name: String, var profession: String, var position: String, var abilities: Array<String>) : Serializable

참고: 데이터 클래스인 Character는 이름, 직업, 포지션, 능력 배열을 속성으로 가지며, Serializable 인터페이스를 구현해 인텐트로 전달될 수 있도록 합니다.

4단계 – 두 번째 액티비티 생성

새로운 빈 액티비티(Empty Activity)를 생성하고 아래 코드를 추가합니다.

activity_second.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=".SecondActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="70dp"
        android:background="#008080"
        android:padding="5dp"
        android:text="TutorialsPoint"
        android:textColor="#fff"
        android:textSize="24sp"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

SecondActivity.kt

두 번째 액티비티에서는 getSerializableExtra()로 전달받은 객체를 꺼내 화면에 출력합니다.

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class SecondActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)
        title = "KotlinApp"
        val sports = intent.getSerializableExtra("Character") as Character?
        val textView: TextView = findViewById(R.id.textView)
        textView.text = """
        ${sports!!.name}
        ${sports.profession}
        ${sports.position}
        """.trimIndent() + sports!!.abilities.contentToString()
    }
}

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 Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘 Kotlin으로 안드로이드 액티비티 간 객체 전달하기 – Serializable 완벽 가이드 을 클릭하세요. 실행 옵션에서 자신의 모바일 기기를 선택하면, 기기 화면에 앱이 실행된 것을 확인할 수 있습니다.

버튼을 누르면 첫 번째 액티비티에서 생성한 Character 객체가 두 번째 액티비티로 전달되어, 아래와 같이 선수의 이름·직업·포지션·능력 정보가 화면에 표시됩니다.

Kotlin으로 안드로이드 액티비티 간 객체 전달하기 – Serializable 완벽 가이드

Kotlin으로 안드로이드 액티비티 간 객체 전달하기 – Serializable 완벽 가이드