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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…