Stop reloading previous fragment by using Navigation architecure

坚强是说给别人听的谎言 提交于 2019-12-11 06:14:14

问题


How can we stop reload previous fragment from current fragment by pressing back button

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" />

回答1:


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. Once the view is created, store it in a variable and use it whenever onCreateView() is called.
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

 }

Source: https://twitter.com/ianhlake/status/1103522856535638016

  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


来源:https://stackoverflow.com/questions/56162112/stop-reloading-previous-fragment-by-using-navigation-architecure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!