I've been struggling with this problem for like a week, it's basically a Backstack problem I didn't found an optimal solution yet. I am working on a project which's flow is like this:
Activity (Fragment_A -> Fragment_B -> Fragment_C -> Fragment_A)
I am setting on Fragment_A
one DatePicker
and a TimePicker
and I have 2 TextViews
that redirect the user to Fragment_B
. From Fragment_B
I send some data to Fragment_C
that converts the data and sends it back to Fragment_A
.
The problem is that as far as I've understood is that when going back to Fragment_A
it goes with a new instance, not the old, so my data there is lost. I resolved for now with sharedPreferences
but it seems too complicated for a solution. I've tried with custom beginTransaction()
and Navigation component
but it didn't turn out well.
I was close, and when going from Fragment_C
to Fragment_A
there was the new instance on top of the old and at onBackPressed
it popped the new instance, and showed me the old but how can I resolve so I won't need to press the back button? I tried to send a Boolean so if it's a new instance pop it, but it popped the old one I guess, because when I pressed back, it just quit the Activity instead of popping the new one.
Any help is appreciated!
An Activity-scoped ViewModel
will make sharing data between child Fragments
easier. Your Fragments
observe the data in the ViewModel
, so you don't even have to worry about passing data around. And with Navigation Component, you can use popUpTo
and popUpToInclusive
to pop Fragments
B and C off the back stack, leaving just Fragment
A.
If you're not familiar with these concepts, this free course covers them all wonderfully:
https://www.udacity.com/course/developing-android-apps-with-kotlin--ud9012