例如,我们有一个City类,我们希望将其传递给片段:
data class City(val id: Int, val name: String) {
constructor(city: City) : this(city.id, city.name)
fun isEmpty(): Boolean {
return id == 0 || name == ""
}
companion object {
val emptyCity = City(0, "")
}
}
如果我们想做每个人都说的事情-通过参数通过Bundle传输数据,那么我们需要做这样的事情。我们应该在我们的City类中实现Serializable:
data class City(val id: Int, val name: String) : Serializable {
...
}
然后,在片段中,我们必须将其放入Bundle并设置参数:
companion object {
private const val CITY_EXTRA = "CITY_EXTRA"
fun getInstance(city: City): MainFragment {
val fragment = MainFragment()
val bundle = Bundle()
bundle.putSerializable(CITY_EXTRA, city)
fragment.arguments = bundle
return fragment
}
}
最后,我们必须从片段实例中某处的参数中获取数据:
private fun getCityFromArgs(): City {
return arguments?.getSerializable(CITY_EXTRA) as City
}
但是起初我们可以这样做,并且一切正常:
companion object {
fun getInstance(city: City): MainFragment {
val fragment = MainFragment()
fragment.city = city
return fragment
}
}
那么,通过字段将数据传输到片段是否很令人难以接受,这是什么威胁?