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 中编写了上述代码来初始化片段。虽然我无法找到将对象列表(例如:List<Human>
)传递给此片段的方法。我尝试过Bundle()
,但无法找到合适的方法。
答案 0 :(得分:10)
您可以将List<Human>
Parcelable
ArrayList
传递到捆绑,如下所示:
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")
}
在Parcelable
数据类中执行Human
:
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)
}
}
}