Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop reloading previous fragment by using Navigation architecure

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" />
like image 770
Vasim Avatar asked May 16 '19 06:05

Vasim


1 Answers

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
like image 149
Badhrinath Canessane Avatar answered Nov 14 '22 12:11

Badhrinath Canessane