将对象列表传递给片段


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(),但找不到适当的方法。

您可以将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

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)
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新