Kotlin - Pass data between Fragments

Asked

Viewed 65 times

0

I’m having a problem with an app I’m designing. I have 3 Fragments ( F1, F2, and F3):

  • In F1 (contains a list with a series of sports) the user makes the choice regarding a sport (I use a Recycleview for this).
  • In F2 (contains a list with a series of spaces) the use choose the space ( I also use a Recycleview)

The point is that in F3 I want to "summarize" the user’s choices( Selected sport, selected space).

My question is what is the most efficient way to pass these arguments between the 3 Fragments?! Sharedviewmodel or used Safeargs?! I tried to use Sharedviewmodel but in F3 the variable will always null.

   override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.itemview.text=listsports[position]

holder.itemview.setOnClickListener{

val sViewModel=SharedViewModel()

sViewModel.setSport(adapterposition)

v:View->v.findNavcontroller().navigate(R.id.action_F1_to_F2)}
    }
}


1 answer

0


As recommended by google, better use Safeargs to do this task.

Inside your code would look something like this:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.itemview.text=listsports[position]

    holder.itemview.setOnClickListener{

        val sport = listsports[position]

        val navegarF2 = F1Directions.actionF1toF2(sport)
        v:View->v.findNavcontroller().navigate(navegarF2)
    }
}

It will be necessary to declare the type of data that is passing between fragments, if you need to pass some kind of object it is necessary that the class of the same extenda Parcelable and alt+enter in the class that will be automatically generated the implementation.

If you were to pass a so-called "sports" class with 3 parameters, with parcelable it would look like this:

clas Sports(val nome: String?, val time: String?, val jogadores: ArrayList<String>?): Parcelable {
constructor(parcel: Parcel) : this(
    parcel.readString(),
    parcel.readString(),
    parcel.createStringArrayList()) {
}

override fun writeToParcel(parcel: Parcel, flags: Int) {
    parcel.writeString(nome)
    parcel.writeString(time)
    parcel.writeStringList(jogadores)
}

override fun describeContents(): Int {
    return 0
}

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

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

Remember that all code inside {.. } was automatically generated.

Documentation: https://developer.android.com/guide/navigation/navigation-pass-data?hl=pt-br https://developer.android.com/reference/android/os/Parcelable

Browser other questions tagged

You are not signed in. Login or sign up in order to post.