将对象列表传递给片段

Passing List of Objects to Fragment

class CholesterolPagingFragment: Fragment() {

    companion object {
        fun newInstance(): CholesterolPagingFragment {
            val args = Bundle()
            val fragment = CholesterolPagingFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_paging_cholesterol, container, false)

        return view
    }

}

我已经在Kotlin中写了上面的代码来初始化一个fragment。尽管我想不出将对象列表(例如:List<Human>)传递给该片段的方法。我试过 Bundle() 但找不到合适的方法。

您可以将 List<Human> 作为 Parcelable ArrayList 传递给 Bundle,如下所示:

 companion object {
    fun newInstance(myList : ArrayList<Human>): MyFragment {
        val args = Bundle()
        args.putParcelableArrayList("list",myList);
        val fragment = MyFragment()
        fragment.arguments = args
        return fragment
    }
}

检索数据:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    val args = arguments
    var myList : ArrayList<Human> = args.getParcelableArrayList<Human>("list")
}

Human 数据中执行 Parcelable 实现 Class :

data class Human(val name: String, val phone: String) : Parcelable {
    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString()) {
    }

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun describeContents(): Int {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

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

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