Ad
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
}
}
I have wrote the above code in Kotlin to initialize a fragment. Though I can't figure out a way to pass a list of objects(eg: List<Human>
) to this fragment. I have tried with the Bundle()
but couldn't find a proper way.
Ad
Answer
You can pass List<Human>
as Parcelable
ArrayList
to the Bundle as follows:
companion object {
fun newInstance(myList : ArrayList<Human>): MyFragment {
val args = Bundle()
args.putParcelableArrayList("list",myList);
val fragment = MyFragment()
fragment.arguments = args
return fragment
}
}
To retrieve data:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = arguments
var myList : ArrayList<Human> = args.getParcelableArrayList<Human>("list")
}
Do Parcelable
implementation in Human
Data 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)
}
}
}
Ad
source: stackoverflow.com
Related Questions
- → should I choose reactjs+f7 or f7+vue.js?
- → Phonegap Android write to sd card
- → Local reference jquery script in nanohttpd (Android)
- → Click to navigate on mobile devices
- → How to allow api access to android or ios app only(laravel)?
- → Access the Camera and CameraRoll on Android using React Native?
- → React native change listening port
- → What is the default unit of style in React Native?
- → Google play market autocomplete icon
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → Using Laravel with Genymotion
- → react native using like web-based ajax function
- → react native pdf View
Ad