Pass data back to previous fragment using Android Navigation

前端 未结 4 556
天命终不由人
天命终不由人 2021-01-07 21:54

I\'ve started using Android Architecture Components (Navigation and Safe Args, View Models) along with Koin library.

Currently, I\'ve got a problem with passing argu

4条回答
  •  攒了一身酷
    2021-01-07 22:33

    Currently, I've got a problem with passing arguments between two fragments - I need to pass a string value from fragment A to fragment B, modify this value in fragment B and pass it back to fragment A.

    The theoretical solution really is to have the two fragments in a shared tag, then scope the ViewModel to the ID of the navigation tag, this way you now share the ViewModel between the two screens.

    To make this reliable, it's best to use the NavBackStackEntry of the Navigation tag as both a ViewModelStoreOwner and SavedStateRegistryOwner, and create an AbstractSavedStateViewModelFactory that will create the ViewModel using the ViewModelProvider, while also giving you a SavedStateHandle.

    You can communicate the results from FragmentB to FragmentA using this SavedStateHandle, associated with the shared ViewModel (scoped to the shared NavGraph).

提交回复
热议问题