如何在 kotlin 中通过意图传递自定义对象

问题描述 投票:0回答:10
fun launchNextScreen(context: Context, people: People): Intent {
    val intent = Intent(context, NextScreenActivity::class.java)
    intent.putExtra(EXTRA_PEOPLE, (Parcelable) people)
    //intent.putExtra(EXTRA_PEOPLE, people as Parcelable)
    //intent.putExtra(EXTRA_PEOPLE, people)
    // tried above all three ways
    return intent
}

我尝试使用上面的代码使用 kotlin 通过意图传递

People
类的实例,但出现错误。 我做错了什么?

android android-intent kotlin kotlin-android-extensions
10个回答
98
投票

首先,确保

People
类实现了
Serializable
接口:

class People : Serializable {
    // your stuff
}

People
类的内部字段也必须实现
Serializable
接口,否则会出现运行时错误。

然后它应该可以工作:

fun launchNextScreen(context: Context, people: People): Intent {
    val intent = Intent(context, NextScreenActivity::class.java)
    intent.putExtra(EXTRA_PEOPLE, people)
    return intent
}

要接收来自 Intent 的回复,您需要致电:

val people = intent.getSerializableExtra(EXTRA_PEOPLE) as? People

44
投票

在对象中实现可序列化:

data class Object (
        var param1: Int? = null,
        var param2: String? = null
) : Serializable

class Object : Serializable {
        var param1: Int? = null,
        var param2: String? = null
}

然后就可以使用Intent来传递对象了:

val object = Object()
...
val intent = Intent(this, Activity2::class.java)
intent.putExtra("extra_object", object as Serializable)
startActivity(intent)

最后,在 Activity2 中,您可以通过以下方式获得对象:

val object = intent.extras.get("extra_object") as Object

25
投票

找到了更好的方法:

在你的gradle中:

apply plugin: 'org.jetbrains.kotlin.android.extensions'

android {
    androidExtensions {
        experimental = true
    }
}

在您的数据类中:

@Parcelize
data class Student(val id: String, val name: String, val grade: String) : Parcelable

在源活动中:

val intent = Intent(context, Destination::class.java)
        intent.putExtra("student_id", student)
        context.startActivity(intent)

在目的地活动中:

student = intent.getParcelableExtra("student_id")

25
投票
从 Kotlin

1.3.60+
!
开始,Parcelize

不再是实验性的

定义一个数据类,添加

@Parcelize
注释并扩展
Parcelable

@Parcelize
data class People(val id: String, val name: String) : Parcelable

添加意图:

val intent = Intent(context, MyTargetActivity::class.java)
intent.putExtra("people_data", student)
context.startActivity(intent)

MyTargetActivity

val people: People = intent.getParcelableExtra("people_data")

如果您尚未启用扩展程序,请在应用程序的

build.gradle
中启用。这还支持数据绑定其他出色的高级功能

apply plugin: 'kotlin-android-extensions'

9
投票

我找到了一种更好的方法,使用 Parcelable 将对象从一个活动传递到另一个活动,它比序列化更快 Android:可打包和可序列化之间的区别?

首先,在 build.gradle(app) 中添加这些代码行

apply plugin: 'kotlin-android-extensions' in app.grable 

@Parcelize 
class Model(val title: String, val amount: Int) : Parcelable

意图传递--->

val intent = Intent(this, DetailActivity::class.java)
intent.putExtra(DetailActivity.EXTRA, model)
startActivity(intent)

从意图出发--->

val model: Model = intent.getParcelableExtra(EXTRA)

3
投票

这篇文章可能对您想做的事情有用:

有没有一种便捷的方法可以使用 Kotlin 在 Android 中创建 Parcelable 数据类?

基本上,kotlin 提供了一些额外的功能:

@Parcelize
class User(val firstName: String, val lastName: String) : Parcelable

查看帖子了解更多信息。


0
投票

在 kotlin 中启动活动并传递一些数据,你可以尝试这样的事情:

startActivity(intentFor<NameOfActivity>(STRING to data))

玩得开心


0
投票

你必须在 <> 中添加类型...它对我有用

val people = intent.getParcelableExtra<People>(EXTRA_PEOPLE) as People

在 PeopleDetailActivity 活动中,在 onCreate 中初始化 viewModel

viewModel = [email protected] { postPeopleId(getPeopleFromIntent().id) }

并初始化此方法:

private fun getPeopleFromIntent() = intent.getParcelableExtra<People>(peopleId) as People

编写以下代码来传递意图附加内容:

companion object {
        private const val objectId = "people"
        fun startActivityModel(context: Context?, people: People) {
            if (context != null) {
                val intent = Intent(context, PeopleDetailActivity::class.java).apply {
                    putExtra(
                        objectId,
                        people
                    )
                }
                context.startActivity(intent)
            }
        }
    }

在 PeopleListViewHolder onClick 中调用上述方法

override fun onClick(v: View?) = PeopleDetailActivity.startActivityModel(context(), people)

0
投票

用于链接两个活动并将名称传递给第二个活动的代码 MainActivity.kt

val button = findViewById<Button>(R.id.button)

    button.setOnClickListener() {
        val name = findViewById<EditText>(R.id.editText)
        val message = name.text.toString()

        intent = Intent(this, SecondActivity::class.java)
        intent.putExtra("EXTRA MESSAGE", message)
        startActivity(intent)
    }

主.xml

 <Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:text="Click"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<EditText
    android:id="@+id/editText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:ems="10"
    android:inputType="text"
    android:text="Name"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

第二活动.kt

 val message = intent.getStringExtra("EXTRA MESSAGE")
    val textView = findViewById<TextView>(R.id.textView2).apply {
        text = message
    }


    Toast.makeText(this, "Name is : $message",Toast.LENGTH_LONG).show()
    val button2 = findViewById<Button>(R.id.button2)
    button2.setOnClickListener(){
        intent = Intent(this,MainActivity::class.java)
        startActivity(intent)
    }

第二个.xml

  <TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginBottom="8dp"
    android:text="SecondActivity"
    android:textSize="18sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.345" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="back"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.774" />

-1
投票

您的 People 类需要像这样实现 Parcelable:

class People(): Parcelable{
// stuff


}

android studio 会显示一个错误。只需将光标移至“人物”并按 Alt+Enter。它现在应该显示生成 Parcelable 实现的选项。

生成的代码将包含类似

的内容
parcel.writeString(member1)
parcel.writeInt(member2)

还有其他地方

member1=parcel.readString()
member2=parcel.readInt()

确保所有成员都包含在这些方法中,并且在修改它时,确保读取和写入以完全相同的顺序发生。

© www.soinside.com 2019 - 2024. All rights reserved.