使用 Jetpack 的 Android 导航组件销毁/重新创建片段 [英] Fragments destroyed / recreated with Jetpack's Android Navigation components

本文介绍了使用 Jetpack 的 Android 导航组件销毁/重新创建片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Jetpack 的架构组件实现导航 在我现有的应用中.

I'm trying to implement Navigation with Jetpack's architecture components in my existing app.

我有一个活动应用程序,其中主要片段 (ListFragment) 是一个项目列表.目前,当用户点击列表项时,第二个片段会通过 fragmentTransaction.add(R.id.main, detailFragment) 添加到堆栈中.因此,当按下返回时,DetailFragment 被分离,ListFragment 再次显示.

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.

使用导航架构,这是自动处理的.它没有添加新片段,而是替换,因此片段视图被销毁,onDestroyView() 被调用,onCreateView() 在按下返回键重新创建视图时被调用.

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.

我知道这是一个很好的模式,用于 LiveDataViewModel 以避免使用不必要的内存,但在我的情况下这很烦人,因为该列表具有复杂的布局,并且膨胀它既费时又费 CPU,还因为我需要保存列表的滚动位置并再次滚动到用户离开片段的相同位置.这是可能的,但似乎应该存在更好的方法.

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.

我尝试将视图保存"在片段的私有字段中,并在 onCreateView() 上重新使用它,如果它已经存在,但它似乎是一种反模式.>

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?

推荐答案

Ian Lake from google 回复我说我们可以将视图存储在变量中而不是膨胀一个新的布局,只需返回onCreateView()

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()

来源:https://twitter.com/ianhlake/status/1103522856535638016

Leakcanary 可能会将其显示为泄漏,但它的误报..

Leakcanary may show this as leak but its false positive..

这篇关于使用 Jetpack 的 Android 导航组件销毁/重新创建片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆