Reputation: 467
I Have huge probleme in my project when I go back from fragment B to fragment A just like this :
findNavController().navigateUp()
or
activity?.onBackPressed()
causes that a old fragment is recreated And I do not why
this is my action:
<action
android:id="@+id/action_fragmentA_to_fragmentB"
app:destination="@id/fragmentB" />
val action = ScanningFragmentDirections.action_fragmentA_to_fragmentB(
scanningViewModel.containerLevel,
container
)
NavHostFragment.findNavController(this).navigate(action)
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding =
DataBindingUtil.inflate(inflater, R.layout.scanning_fragment, container, false)
binding!!.viewmodel = scanningViewModel
binding!!.lifecycleOwner = this
return binding!!.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init()
}
Upvotes: 1
Views: 3153
Reputation: 4951
When you navigate from one fragment to another your fragment view is destroyed(onDestroyView
is called). When you navigate back to a fragment you previously were in the view is recreated (onCreateView
is called).
There may be scenarios wherein you do not want your fragment to be recreated (Some time ago I had a fragment with a MapView
and I didn't want to have to add all the different markers and polygons again). You can try something like this:
Create a field in your fragment class to save your view:
private lateinit var contentView: View
In the onCreateView
function only inflate the view if your variable has not been intialised.
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
if (!::contentView.isInitialized) {
contentView = inflater.inflate(R.layout.fragment_home, container, false)
}
return contentView
}
Upvotes: 4
Reputation: 4776
When you calling findNavController().navigate(...)
under the hood system calling :
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.replace(mContainerId, frag);
That mean that your fragment will be fully destroyed and recreate again when you return to him via backstack.
Upvotes: 0