问题
I am using Navigation Architecture in an image gallery, when I go from fragment A to B and then return back to A, these 3 methods are called again which will cause my gallery to reload, where I should load my data in fragment so when I come back from B to A my methods don't get called? :
- OnCreateView
- OnViewCreated
- OnResume
回答1:
The fragment's lifecycle methods anyway will called again. You can google it how to work with fragment or activity lifecycle.
The main idea how to deal with lifecycle consists of saving view states, persisting data etc. If you are using fragments you can use retain fragments: just in your gallery fragment put the flag setRetainInstance(true)
and the system won't call onCreate()
and onDestroy()
methods while you will rotate your phone , for example. Next step I recommend you to use AndroidArchitectureComponent which was introduced in 2017 You can read about it here.
In your case, I guess, you should create ViewModel for your fragment, load data in your ViewModel and put the data inside the LiveData object. Moreover, you should override onCreate in fragment and make the fragment retain (how to do it I've just describe earlier) and init your ViewModel here. After that, in onViewCreated or in onActivityCreated you need to observe your data via LiveData and ViewModel and just show it without reloading.
It's basic algorithm. The similar behavior might be achieved with different approaches like MVP, RxPM, MVVM (based on RxJava and RxAndroid) etc. I suppose that it is not the main purpose of my answer to describe all these patterns here. There are a lot of information in the internet (on StackOverflow too) just try to find it.
The main idea of it that you should load something in the object that can survive while the view destroys and just say to the view to get the available data from this object when the view will ready to do that.
回答2:
navigate(...)
is implemented using Fragment.instantiate(...)
by FragmentNavigator
. In the example provided, I would recommend calling popBackStack()
to return to the previous fragment instead of navigate(...)
来源:https://stackoverflow.com/questions/54286392/navigation-architecture-fragment-reload-problem