问题
Passing data between Fragments in Navigation Component is easy. Say going from A
to B
you just set arguments
with SafeArgs
and you are done.
But, it gets tricky when passing data from B
back to A
.
According to documentation, we can use SharedViewModel
which is works well. But I am looking for better way of passing data back to A
from B
.
The problem of using SharedViewModel
is, you have to create SharedViewModel
for every fragment pair that you need to pass data.
Any suggestions? If any annotation-processing method you can think about, you are more than welcome to recommend.
回答1:
You don't need to create a ViewModel per Fragment pair. What I am doing is creating a ViewModel per Fragment. Each ViewModel would have a map[Class[Fragment], Any] named mailBox.
Each Fragment will define a FragmentResult type which is different per Fragment class.
In the child Fragment onBackPressedHandler, before pop-up, fetch the parent ViewModel from the Activity and put your result in the mailBox for your class. You will need a ViewModel class for that. See below.
The parent Fragment needs to pass it's ViewModel.class to the child Fragment, before launching it.
When the Parent Fragment is re-started after popping up the child from the stack. Get the mailBox map from it's ViewModel, check if there is a key with value from the expected FragmentChild::class. If so, then cast to the desired type.
The parent Fragment ViewModel needs to save who was the last child it launched.
回答2:
I am using an callback interface for this. So i have created an interface with some methods. I implemented that interface 'A' and then call if from 'B'. Very easy and works great.
来源:https://stackoverflow.com/questions/56286907/better-way-to-pass-data-between-fragments-navigation-component