I'm trying to implement Navigation with Jetpack's architecture components in my existing app.
I have a single activity app where the main fragment (ListFragment
) is a list of items. Currently, when the user taps on a list item a second fragment is added to the stack by fragmentTransaction.add(R.id.main, detailFragment)
. So when back is pressed the DetailFragment
is detached and the ListFragment
is shown again.
With Navigation architecture this is handled automatically. Instead of adding the new fragment it's replaced, so the fragment view is destroyed, onDestroyView()
is called and onCreateView()
is called when back is pressed to recreate the view.
I understand that this is a good pattern used with LiveData and ViewModel to avoid using more memory than necessary, but in my case this is annoying because the list has a complex layout and inflating it is time and CPU consuming, also because I'll need to save the scroll position of the list and scroll again to the same position user left the fragment. It's possible but seems it should exists a better way.
I've tried to "save" the view in a private field on fragment and re-use it on onCreateView()
if is already there, but it seems an anti-pattern.
private View view = null; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (view == null) { view = inflater.inflate(R.layout.fragment_list, container, false); //... } return view; }
Is there any other, more elegant, way to avoid re-inflating the layout?
Use Up or Back button to go to a previous step of the order flow.
NavHostFragment provides an area within your layout for self-contained navigation to occur. NavHostFragment is intended to be used as the content area within a layout resource defining your app's chrome around it, e.g.: <androidx.drawerlayout.widget.DrawerLayout.
Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app. 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.
Note: If your app uses multiple activities, each activity uses a separate navigation graph. To take full advantage of the Navigation component, your app should use multiple fragments in a single activity. However, activities can still benefit from the Navigation component.
Ian Lake from google replied me that we can store the view in a variable and instead of inflating a new layout, just return the instance of pre-stored view on onCreateView()
Source: https://twitter.com/ianhlake/status/1103522856535638016
Leakcanary may show this as leak but its false positive..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With