DaniloDeQueiroz
DaniloDeQueiroz

Reputation: 412

Android Navigation Architecture component avoid Fragment recreation

I have the following flow where within Fragment's content is a Form with various input fields.

Fragment A -> Fragment B -> Fragment C -> Fragment D ...

when the user has filled, for example, the Frag C completely, and move back to Frag B, all the Frag B data is stored and kept as intact, but when moving forward back to C, all the input data is gone. Imagine the same scenario, the user Filled Frag A, B and he had filled half of the Frag C fields, and he chooses to go back to Frag A, when he's navigating back all the input data is intact on the previous Frags (B and A), but once he decides to move forward back to C where he was, the data from B and C are lost and replaced with new fragment every new step. So the input data is only kept when going back (android back button), when he opens the Fragment where he's already have been there before, a new Fragment with all input as blank is created. Is it possible to keep fragment as unique whenever the user moves back or moves forward to it on Navigation architecture component?

Upvotes: 8

Views: 2441

Answers (1)

AaronJ
AaronJ

Reputation: 714

This isn't a way to stop fragment recreation but it addresses your problem. Create an activity scoped ViewModel to hold the form data, and then have your fragments observe this ViewModel. The ViewModel will outlive the fragments, so when they are recreated they will use the value that you previously stored in the ViewModel.

How to implement ViewModel

Upvotes: 1

Related Questions