iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

【Kotlin】Activity の画面遷移時にカスタムデータを渡す

今回はタイトルの通り、Kotlin で Activity の画面遷移時にカスタムデータを渡す方法を紹介したいと思います🧑‍🔧

それではやっていく🧑🏻‍💻

まずは遷移先の Activity に渡すデータクラスを定義し、Serializable に準拠させます。

data class PlaceItemEntity(val name: String = "", val countryName: String = "", val imagePath: String = "") : Serializable

Serializable とは?

Json、Protocol buffers、CBOR などのフォーマットをサポートしたシリアライザインターフェースです。 詳しくは下記のドキュメントを参照してください。

Serialization - Kotlin Programming Language

次に遷移元の Activity に遷移処理を Intent を使って記述します。この時に intent.putExtra("hoge", entity) で、key(ここではhoge) と一緒に Serializable に準拠したデータを渡すことで、カスタムデータクラスを遷移先に渡すことができます。

  val intent = Intent(this, DetailsActivity::class.java)
  intent.putExtra("hoge", placeItem)
  startActivity(intent)

最後に遷移元で Key をもとにカスタムデータクラスを取得すれば完了です🎉 なお、Intent からデータを取得する際は getSerializableExtra メソッドを使用して Serializable に準拠したデータクラスを取得します。

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_details)

        val state = intent.getSerializableExtra("hoge")
        if(state is PlaceItemEntity){
            val placeName = findViewById<TextView>(R.id.placeName)
            val prefectureName = findViewById<TextView>(R.id.prefectureName)

            placeName.text = state.name
            prefectureName.text = state.countryName
        }
    }

参考

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com