gpt4 book ai didi

android - 如何在单独的 Activity 中接收 Parcelable 对象参数?

转载 作者:行者123 更新时间:2023-11-29 23:30:58 26 4
gpt4 key购买 nike

我希望能够在下一个 Activity 中接收我的 paracable 对象的各个参数。我相信我使用的方法是正确的,只是不明白如何在第二个 Activity 中输出一次参数输入。

我的 MainActivty.kt:

package com.example.favouritefood

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageButton

class MainActivity : AppCompatActivity() {

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

val food1: ImageButton = findViewById(R.id.imageButtonFood1)
val food2: ImageButton = findViewById(R.id.imageButtonFood2)
val food3: ImageButton = findViewById(R.id.imageButtonFood3)
val food4: ImageButton = findViewById(R.id.imageButtonFood4)

val pizza = Food(
"Pizza", "www.test.com", "Italy, Tomato",
"1/1/2018", "pizza@mail.com", 5)

food1.setOnClickListener()
{
val intent = Intent(this, MetaDataActivity::class.java).apply {
putExtra("Food", pizza)
}
startActivity(intent)
}
}
}

我的第二个 Activity (接收包裹):

package com.example.favouritefood

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Parcelable
import android.widget.EditText

class MetaDataActivity : AppCompatActivity() {

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

val name: EditText = findViewById(R.id.editTextName)

val food = intent.getParcelableExtra("Food") as Parcelable

val test = food.writeToParcel(food, 0)

name.setText(test.toString())
}
}

food.wrtieToParcel(food, 0) 抛出 Required: Parcel 的类型不匹配!发现:可通过 food 包裹。

我将如何读取对象中的参数?

我的对象类供引用:

package com.example.favouritefood

import android.os.Parcel
import android.os.Parcelable

class Food(val name: String?, val location: String?, val keywords: String?, val date: String?, val email: String?, val rating: Int) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readString(),
parcel.readInt()) {
}

override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeString(location)
parcel.writeString(keywords)
parcel.writeString(date)
parcel.writeString(email)
parcel.writeInt(rating)
}

override fun describeContents(): Int {
return 0
}

companion object CREATOR : Parcelable.Creator<Food> {
override fun createFromParcel(parcel: Parcel): Food {
return Food(parcel)
}

override fun newArray(size: Int): Array<Food?> {
return arrayOfNulls(size)
}
}
}

最佳答案

您不需要调用 val test = food.writeToParcel(food, 0)

改为使用 val food = intent.getParcelableExtra("Food") as Food

关于android - 如何在单独的 Activity 中接收 Parcelable 对象参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52679126/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com