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" />
Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
Vasim
  • 217
  • 2
  • 10

1 Answers1

20

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
Badhrinath Canessane
  • 3,408
  • 2
  • 24
  • 38
  • 2
    The Fragment already "holds the view" as indicated by `getView()` method. No need to cache it by hand too - because now `onDestroyView` won't *actually* destroy the view. Which could be strange. Although I guess it works, but it is kinda hacky. – EpicPandaForce Jul 04 '19 at 09:52
  • 1
    @EpicPandaForce I don't see anything hacky here. onCreateView() will be called no matter what, as fragment replace() has happened as per the use-case discussed. If the manual caching is not done, re-inflating on onCreateView() will impact the performance especially if its a complex layout. – Badhrinath Canessane Jul 04 '19 at 10:56
  • 1
    How should this work? The fragments are reconstructed completely every time you switch tabs – Boy Sep 13 '20 at 04:42
  • 1
    it still reloads – shehzy Feb 19 '21 at 07:25
  • Only view null condition is enough to avoid reloading. I have fixed with this. – Ashish Jain Feb 19 '21 at 10:53
  • @BadhrinathCanessane what about the data binding? – K.Hayoev Mar 12 '21 at 05:10