通过使用导航架构停止重新加载先前的片段 [英] Stop reloading previous fragment by using Navigation architecure

查看:169
本文介绍了通过使用导航架构停止重新加载先前的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过按后退按钮

例如 就像我们正从背面的列表片段移动到详细信息片段一样,无需使用Android Jet Pack和导航架构再次重新加载列表片段

Ex. As if we are moving from List-fragment to Details Fragment on back pressed no need to reload List-fragment again by using Android Jet Pack and Navigation Architecture

<fragment
        android:id="@+id/my_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_graph" />

推荐答案

导航组件目前仅支持片段替换.因此,您将无法像手动片段事务那样添加()片段.

Navigation component only supports fragment replacement as of now. So you won't be able to add() a fragment as you do it with Manual fragment transaction.

但是,如果您担心要重新扩大布局并重新获取片段的数据,则可以通过以下两种方法轻松解决.

However, if your worry is about re-inflating the layout and re-fetching the data for the fragment, it could be easily resolved with below two methods.

  1. 创建视图后,将其存储在变量中,并在调用onCreateView()时使用它.

private var view: View? = null

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    if (view == null) {
        view = inflater.inflate(R.layout.fragment_list, container, false)
                //...
    }

    return view

 }

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

  1. 将ViewModel与Fragment一起使用,并保留所需的数据作为成员变量. 这样,替换关联的片段时不会清除数据.仅在片段的onDestroy()上清除ViewModel,这仅在销毁父活动时才会发生. https://developer.android.com/images/topic/libraries/architecture/viewmodel-lifecycle.png
  1. Use ViewModel with the Fragment and hold the data required as a member variable. By this way, the data is not cleared when you replace the associated fragment. The ViewModel gets cleared only on onDestroy() of the fragment, which will only happen when you destroy the parent activity. https://developer.android.com/images/topic/libraries/architecture/viewmodel-lifecycle.png

这篇关于通过使用导航架构停止重新加载先前的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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