Kotlin使用Parcelable将ListArray传递给另一个Activity

时间:2017-08-01 00:27:21

标签: android class arraylist kotlin parcelable

我有一个填充了用户信息的自定义类。我使用ArrayList来保存所有User类数据。我想将数组传递给另一个可以读取和修改它的活动。由于数组可能很大,我需要尽可能高效快速地完成此过程,这就是我选择使用Parcelable而不是Serializable的原因。

我在使用Kotlin时遇到了麻烦。有很多Java教程,但没有一个在Kotlin中,这使得这个问题与其他所有问题不同。有人可以提供并解释Kotlin中有关如何实现这一目标的代码吗?

这是我到目前为止所做的:

constructor(`in`:Parcel) {
    CollegeName = `in`.readString()
}

override fun describeContents(): Int {
    return 0
}

override fun writeToParcel(dest: Parcel?, flags: Int) {

}

private fun readFromParcel(`in`:Parcel) {
    CollegeName = `in`.readString()
}

companion object {
    @JvmField final val CREATOR: Parcelable.Creator<College> = object: Parcelable.Creator<College> {

        override fun createFromParcel(source: Parcel): College {
            return College(source)
        }

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

1 个答案:

答案 0 :(得分:2)

使用类似的东西......

   class Series() : Parcelable {
  private var name: String? = null
  private var numOfSeason: Int = 0
  private var numOfEpisode: Int = 0

  constructor(parcel: Parcel) : this() {
    val data = arrayOfNulls<String>(3)
    parcel.readStringArray(data)
    this.name = data[0]
    this.numOfSeason = Integer.parseInt(data[1])
    this.numOfEpisode = Integer.parseInt(data[2])
  }


  override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(name);
    parcel.writeInt(numOfSeason);
    parcel.writeInt(numOfEpisode);
  }

  private fun readFromParcel(parcel: Parcel){
    name = parcel.readString()
    numOfSeason = parcel.readInt()
    numOfEpisode = parcel.readInt()
  }
  override fun describeContents(): Int {
    return 0
  }

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

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

}

然后在你的活动中

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

        val i = Intent(this, SecondActivity::class.java)

val testing = ArrayList<testparcel>()

i.putParcelableArrayListExtra("extraextra", testing)
startActivity(i)
}

class SecondActivity :Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
        setContentView(R.layout.secondActivty_activity)

val testing = this.intent.getParcelableArrayListExtra<Parcelable>("extraextra")
    }
}