Android
 Computer >> コンピューター >  >> プログラミング >> Android

KotlinでAndroidのアクティビティ間にオブジェクトを渡す方法を徹底解説

Kotlinを使用したAndroid開発では、Intent(インテント)を介してアクティビティ間でデータを受け渡すのが一般的です。本記事では、Serializableインターフェースを実装したカスタムオブジェクトを、あるアクティビティから別のアクティビティへ渡す方法を、サンプルコードとともにステップごとに解説します。

手順1:新規プロジェクトを作成する

Android Studioを起動し、メニューから「File」→「New Project」を選択します。必要な項目をすべて入力して、新しいプロジェクトを作成しましょう。

手順2:レイアウトファイル(activity_main.xml)を編集する

res/layout/activity_main.xmlに以下のコードを記述します。ボタンを1つ配置し、クリック時にオブジェクトを次のアクティビティへ渡す構成になっています。

<?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に以下のコードを追加します。ポイントは、Serializableインターフェースを実装したCharacterクラスを定義し、そのインスタンスをintent.putExtra()でIntentに格納してSecondActivityへ渡している点です。

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

手順4:SecondActivityを作成する

新しい空のアクティビティ(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()メソッドを使って渡されたオブジェクトを取り出し、その内容をTextViewに表示しています。

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スマートフォンがPCに接続されているものとします。Android Studioからアプリを起動するには、プロジェクト内の任意のアクティビティファイルを開き、ツールバーの「Run」アイコン KotlinでAndroidのアクティビティ間にオブジェクトを渡す方法を徹底解説 をクリックしてください。表示された候補から自分のモバイルデバイスを選択すると、接続した端末の画面にアプリが立ち上がります。

KotlinでAndroidのアクティビティ間にオブジェクトを渡す方法を徹底解説

KotlinでAndroidのアクティビティ間にオブジェクトを渡す方法を徹底解説

  1. Androidでアクティビティからフラグメントへ変数を渡す方法を徹底解説

    はじめに この記事では、Androidアプリ開発においてアクティビティ(Activity)からフラグメント(Fragment)へ変数を渡す方法を、実際のコード例とともに段階的に解説します。 アクティビティからフラグメントへのデータ受け渡しには、Bundleを使うのが基本です。アクティビティ側でsetArguments()メソッドによりBundleをフラグメントにセットし、フラグメント側でgetArguments()メソッドを使って値を取り出します。 手順1:新規プロジェクトを作成する Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Projec

  2. Androidでアクティビティ間を画像を受け渡す方法をわかりやすく解説

    はじめに 本記事では、Androidアプリであるアクティビティ(Activity)から別のアクティビティへ画像を受け渡す方法を解説します。ここでは、Intentに画像のリソースIDを格納して渡す、最もシンプルで確実な手法を紹介します。 手順1:新規プロジェクトの作成 Android Studioで新しいプロジェクトを作成します。メニューから「File」→「New Project」を選択し、必要事項をすべて入力してプロジェクトを作成しましょう。 手順2:activity_main.xml の編集 res/layout/activity_main.xml に以下のコードを追加します。「Send