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

我了解这是与 LiveData 一起使用的好模式和 ViewModel 以避免使用不必要的内存,但是在我的情况下,之所以令人烦恼,是因为列表的布局复杂,并且夸张它既浪费时间和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.

我试图将视图保存在私有字段中的片段上,并在<$上重用c $ c> 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)来自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 may show this as leak but its false positive..

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

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