Search code examples
androidkotlinargumentsinstancedata-class

Sending whole Data Class instances in an argument


I'm really confused how to use a data class in an argument in an android. I know how to implement a data class. someone help me how to sending the data to the argument.


Solution

  • You just need to use @Parcelize annotation and inherit your class from Parcelable, like this:

    @Parcelize
    data class MyData(val abc: Int, val xyz: String): Parcelable
    

    Now in a "Add Argument" popup in the navigation editor, you should choose the "Custom parcelable" type of argument and it will be here.

    Further actions depend on your approach to navigation between fragments. Personally, I do something like this (inside current fragment):

    findNavController().navigate(R.id.destinationFragmentId, DestinationFragmentArgs(myDataInstance).toBundle())