Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 442
DaniloDeQueiroz Avatar asked Dec 08 '18 11:12

DaniloDeQueiroz


People also ask

How to avoid fragment recreation in navigation Component?

Just add the pop inclusive to all your action in nav graph. What the above pop behavior will do is, when you are navigating from, say C > B, it will pop everything till B (inclusive) from the back stack and add the latest instance of B on the back stack.

What is NavController in Android?

NavController manages app navigation within a NavHost . Apps will generally obtain a controller directly from a host, or by using one of the utility methods on the Navigation class rather than create a controller directly. Navigation flows and destinations are determined by the navigation graph owned by the controller.

What is navigation Component?

Android Jetpack's Navigation component helps you implement navigation, from simple button clicks to more complex patterns, such as app bars and the navigation drawer. The Navigation component also ensures a consistent and predictable user experience by adhering to an established set of principles.


1 Answers

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

like image 147
AaronJ Avatar answered Sep 27 '22 19:09

AaronJ