Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
345 views
in Technique[技术] by (71.8m points)

Fragments destroyed / recreated with Jetpack's Android Navigation components

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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..


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...